diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 2c234450..c8690d57 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -7,17 +7,35 @@ 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: 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 + # `.nvmrc` pins the runtime so a Node release cannot change the build + # without a commit. + node-version-file: .nvmrc cache: npm - name: Install dependencies @@ -45,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 1393d076..71dc1347 100644 --- a/.github/workflows/test-deploy.yaml +++ b/.github/workflows/test-deploy.yaml @@ -1,26 +1,74 @@ 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: 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 + # `.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` takes `cgp` from crates.io, so the website is the only + # checkout. + - name: Check out the website + uses: actions/checkout@v4 + with: + path: contextgeneric.dev + # `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 + # here; 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/.gitmodules b/.gitmodules new file mode 100644 index 00000000..6871eb40 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "cgp-skills"] + path = cgp-skills + url = https://github.com/contextgeneric/cgp-skills.git 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/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..774c7877 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,159 @@ +# AGENTS.md: the CGP website + +Follow these rules for every change to this repository. Read the knowledge base's +[website section](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/README.md) +before writing, from the checkout at `../cgp-knowledge-base`, or on GitHub when it is absent. + +## Universal rules + +These rules hold in every CGP repository. The +[knowledge base's AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md) +holds their canonical wording: read it first, and change a rule there before updating this block: + +- Learn CGP and its tools from the `/cgp` skill and the knowledge base; never restate them in this + file. +- 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, and natural writing to public-facing documents + such as READMEs, using the optional `/point-first-writing` skill when it is available. + +## Task guides + +Each kind of task has a guide in the knowledge base's `website/` section. Read it before the task: + +- **Writing or revising a page:** the page kind's guide in `writing-guides/`, with the shared set + and the page kind's row of its + [reading map](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/README.md#the-reading-map), + and the page's record. +- **Adding or moving a page, or writing a blog post:** `writing-guides/README.md` and + `information-architecture.md`. +- **Changing the theme or a page's styles:** `visual-design.md`. +- **Changing the build, the navigation, or the `example-code` crate:** `site.md` and + [example-code/README.md](example-code/README.md). + +## Public prose + +Every page follows the communication strategy's claims, name, and style, and the author reads the +pages that carry the argument: + +- Read the knowledge base's `communication-strategy/message.md` whenever a page makes a claim about + what CGP is good for, satisfying its pain, strength, objection, and boundary, and read any strategy + document whole when the page makes a claim its reading-map 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); + 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 + them. +- Write every page in natural-writing's natural style by default, the front page and every page under + `docs/` included; follow a page kind's writing guide where it names another style. +- Let agents draft the pages, and have the author read in full before publication the pages the + knowledge base's + [AI disclosure policy](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/communication-strategy/ai-disclosure.md#the-two-claims-that-are-easiest-to-get-wrong) + lists; ship everything else on its guide plus a spot check, and flag a judgement call for the + author's reading rather than deciding alone. +- Add one provenance line at the foot of each page written or substantially rewritten, linking the + section of the AI disclosure page that matches how it was made, and record the level in the page's + record; leave the front page without one, add none to an existing page unless the author asks, and + add none to a scaffolded stub. + +## Code + +Every snippet on a page is verified against current CGP: + +- Invoke the `/cgp` skill before writing CGP code, and verify every snippet against the current `cgp` + release, the `cgp` source, or its tests. +- Prefer code already verified in the knowledge base's `examples/` directory, and the idioms its + guides teach. +- Say which context shape a page's code is in, with the qualifiers the knowledge base's + `vocabulary.md` defines; an introductory page may record the shape in its record instead. +- Never take current syntax from an existing blog post; read the post's record for its stale parts + first, and use the knowledge base's `releases/` directory to date an unfamiliar construct. +- Put a page's code in the `example-code/` crate, one module per heading, except a Projects page, + whose code is checked against the project's repository; do not mirror the knowledge base's own + snippets there. +- Run the `example-code` tests after changing a page's code, as + [example-code/README.md](example-code/README.md) describes. +- Fill an elided body with a comment saying so, write a rejected snippet as a compile-fail fixture, + and prefer duplication between files over a shared helper neither page shows. +- Treat a page without an `example-code` file as unvisited, not unverified, and check generated code + with `cargo cgp expand`, which the crate does not replace. + +## Links + +A published page links only public resources, and links into the knowledge base only through the +exceptions below: + +- Never link a published page into the knowledge base. +- Make only three hand-written exceptions: `docs/ai/disclaimer.md`, which may link the base's + repository page and its issue tracker; `docs/contribute.md`, which may link the issue tracker + alone; and the pages under `docs/ai/knowledge-base/`, which may also link the four top-level entry + files (`README.md`, `summary.md`, `AGENTS.md`, and `sibling-projects.md`) and name a section's + directory in prose rather than link a document inside it. +- Let only the published skill pages under `docs/ai/skills/` 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. +- 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 + +The site presents only current resources: + +- Do not link, list, or recommend the CGP Patterns book or the Hermes SDK, or direct a page to + present either. +- 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, and raise a page that already + mentions a legacy resource with the author. + +## The agent skill + +The skill pages are a published snapshot of `cgp-skills`, which is the only place to change them: + +- Do not edit the symlinks under `docs/ai/skills/`; correct the skill in `cgp-skills`. +- Leave the `cgp-skills` submodule pointer to the author. +- Read the `../cgp-skills` checkout for what the skill says, and treat a lagging published snapshot + as normal: it is not a defect and does not need an issue, note, or fix. + +## Blog posts + +A published post is a dated artifact, so a correction goes beside it rather than into it: + +- Do not rewrite a published post; it is a dated artifact, edited only when its record says it was + published unfinished. +- Annotate a misleading post, supersede it with a new one, or record the drift in its record, as the + author decides; record the drift by default for release posts. +- Never change a published post's `slug`, and never rewrite a snippet in it. +- Correct a page under `docs/` in place, without a changelog note, except a page under + `docs/release-notes/`: it is dated like a post, so correct it only where it misstates its own + release, and record a later change on the later release's page. + +## Build + +The site stays a stock Docusaurus build that fails on a broken link or anchor: + +- Build and serve the site with the commands in [README.md](README.md), and check the build's exit + status rather than its output. +- 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. +- Use the theme's tokens from `src/css/custom.css` in page styles, never a hex colour. +- Treat `notes/` as working material, not site content; do not edit or copy from it. + +## Knowledge base + +Each page has a record in the knowledge base that changes with it: + +- Add or revise the page's knowledge-base record in the same change. +- State what needs updating in the knowledge base when its checkout is absent. 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..65e44551 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,105 @@ -# 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) +[![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 24+](https://img.shields.io/badge/node-24+-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 24 or newer is required. CI runs the version `.nvmrc` pins, and +`nvm use` selects the same one locally. + +## 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 +The social card, the image a shared link to the site shows, is `static/img/social-card.jpg`, rendered +from the hero illustration, the project's name, and its tag line. Regenerate it after changing either +with `python3 scripts/social-card/make.py`, which needs `google-chrome` and ImageMagick, and commit +the result. + +## Theme -Using SSH: +The site's colours are tokens in [`src/css/custom.css`](src/css/custom.css), defined once for each +theme, with the code colours in [`src/prism/themes.ts`](src/prism/themes.ts); page styles use the +tokens rather than hex colours. After changing a colour, run the contrast check, which needs only +Python 3 and exits non-zero when a pair falls below WCAG AA: -```bash -USE_SSH=true yarn deploy +```sh +python3 scripts/theme/contrast.py ``` -Not using SSH: +The heading and code fonts are self-hosted under `static/fonts/`, and +[`scripts/fonts/README.md`](scripts/fonts/README.md) gives the commands that cut them. -```bash -GIT_USER= yarn deploy -``` +## Deployment + +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. 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 + +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. + +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/blog/2024-12-19-early-preview-announcement.md b/blog/2024-12-19-early-preview-announcement.md index 11fe46d8..97e50844 100644 --- a/blog/2024-12-19-early-preview-announcement.md +++ b/blog/2024-12-19-early-preview-announcement.md @@ -3,12 +3,13 @@ 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, to introduce a new modular programming paradigm for Rust. -{/* truncate */} + ## A Quick Overview of Context-Generic Programming @@ -252,4 +253,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..ba226453 100644 --- a/blog/2025-01-09-v0.3.0-release.md +++ b/blog/2025-01-09-v0.3.0-release.md @@ -3,11 +3,12 @@ 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. -{/* truncate */} + ## New Book Chapters @@ -101,6 +102,7 @@ For more details on `#[cgp_auto_getter]`, refer to the [Generic Accessor Provide The `#[cgp_getter]` macro, like `#[cgp_auto_getter]`, generates blanket implementations that make use of `HasField`. However, `#[cgp_getter]` extends functionality by also creating full CGP constructs for the trait, similar to `#[cgp_component]`. This requires explicit wiring in the context using `delegate_components!`. Additionally, `#[cgp_getter]` derives a blanket implementation for the `UseFields` provider, so that it can be used inside the component wiring as follows: ```rust +use cgp::core::component::UseFields; use cgp::prelude::*; #[cgp_getter { diff --git a/blog/2025-05-09-v0.4.0-release.md b/blog/2025-05-09-v0.4.0-release.md index 8936fa4e..8f778c21 100644 --- a/blog/2025-05-09-v0.4.0-release.md +++ b/blog/2025-05-09-v0.4.0-release.md @@ -3,13 +3,14 @@ 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! 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..9d28f022 100644 --- a/blog/2025-06-14-hypershell-release/index.md +++ b/blog/2025-06-14-hypershell-release/index.md @@ -3,11 +3,20 @@ 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.' --- +:::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. -{/* 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..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`. @@ -14,7 +15,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..e3286869 100644 --- a/blog/2025-07-07-extensible-datatypes-part-1.md +++ b/blog/2025-07-07-extensible-datatypes-part-1.md @@ -3,13 +3,23 @@ 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.' --- +:::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. -{/* 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..3aeada7a 100644 --- a/blog/2025-07-09-extensible-datatypes-part-2.md +++ b/blog/2025-07-09-extensible-datatypes-part-2.md @@ -3,13 +3,23 @@ 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.' --- +:::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. -{/* 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..365df548 100644 --- a/blog/2025-07-12-extensible-datatypes-part-3.md +++ b/blog/2025-07-12-extensible-datatypes-part-3.md @@ -3,8 +3,17 @@ 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.' --- +:::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. @@ -13,7 +22,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..ba28f06b 100644 --- a/blog/2025-07-30-extensible-datatypes-part-4.md +++ b/blog/2025-07-30-extensible-datatypes-part-4.md @@ -3,15 +3,26 @@ 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.' --- +:::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. 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..a2c0a8a4 100644 --- a/blog/2025-10-12-v0.5.0-release.md +++ b/blog/2025-10-12-v0.5.0-release.md @@ -3,13 +3,14 @@ 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. 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..377d364c 100644 --- a/blog/2025-10-26-v0.6.0-release.md +++ b/blog/2025-10-26-v0.6.0-release.md @@ -3,11 +3,12 @@ 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. -{/* 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..11f3fc2a 100644 --- a/blog/2025-11-03-cgp-serde-release.md +++ b/blog/2025-11-03-cgp-serde-release.md @@ -3,15 +3,25 @@ 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.' --- +:::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**. 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..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 @@ -10,7 +11,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..d38bc044 100644 --- a/blog/2026-02-21-new-website.md +++ b/blog/2026-02-21-new-website.md @@ -1,13 +1,14 @@ --- 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 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 +50,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..35a5da1e 100644 --- a/blog/2026-02-28-v0.7.0-release.md +++ b/blog/2026-02-28-v0.7.0-release.md @@ -2,13 +2,14 @@ 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 [**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 +623,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..9aa67271 100644 --- a/blog/2026-03-07-rustlab-2025-coherence/index.md +++ b/blog/2026-03-07-rustlab-2025-coherence/index.md @@ -1,10 +1,20 @@ --- 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 +:::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. + +::: +

@@ -15,7 +25,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-11-18-v0.8.0-release.md b/blog/2026-11-18-v0.8.0-release.md new file mode 100644 index 00000000..bd768440 --- /dev/null +++ b/blog/2026-11-18-v0.8.0-release.md @@ -0,0 +1,1074 @@ +--- +slug: 'v0.8.0-release' +authors: [soares] +tags: [release, deepdive] +description: 'CGP v0.8.0 introduces cargo-cgp diagnostics, expanded documentation, and namespace groups for component wiring.' +--- + +# CGP v0.8.0 - cargo-cgp, new documentation, and namespaces + +**[Context-Generic Programming](/docs/) (CGP) v0.8.0 is out!** With this release, I want to make CGP easier to learn and maintain. When a provider needs a field that your type lacks, cargo-cgp can tell you which field to add, and the expanded documentation explains why the provider needs it. As your application grows, namespaces let you choose providers for a whole group of components in one wiring entry. + + + +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, and you can adopt it one component at a time. The [Overview](/docs/overview) explains the model. + +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 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) +- [Breaking changes and migration](#breaking-changes-and-migration) + +## Diagnosing wiring with cargo-cgp + +Since CGP began, verbose and confusing compiler errors have been one of the largest obstacles to adopting it. Leave out a field or a component binding, and the error message can name a generated trait or show a field name encoded as a Rust type. The compiler checks the Rust produced by macro expansion, so its explanation can be far removed from the code where we made the mistake. + +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. Because the difficulty lies in how the compiler reports the expanded code, better syntax alone cannot address it. + +I built [cargo-cgp v0.1.0](/docs/tooling/cargo-cgp), CGP's new error toolchain, to help with that investigation. It 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 + +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"`: + +```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, + } +} +``` + +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` + --> src/lib.rs:23:9 + | +23 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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` +``` + +The help line gives us the edit, `height: f64`. To see why the provider needs it, the dependency tree takes us 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 + +```text +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> src/lib.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 + --> 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) +``` + +
+ +Following that suggestion, we add the missing field: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} +``` + +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`. + +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 + +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 --locked cargo-cgp +cargo cgp setup +# Run this from your CGP project's directory: +cargo cgp check +``` + +`cargo cgp setup` installs the tool's pinned nightly and builds the matching driver. That nightly runs only cargo-cgp's checks, so your application keeps its normal toolchain for ordinary cargo builds. CGP itself still compiles on stable Rust, and you can use it without installing cargo-cgp at all. + +Use plain cargo to build, run, and test applications. cargo-cgp supplies `check` for diagnostics and [`expand`](/docs/tooling/cargo-cgp/expand) for reading the Rust generated by macros, with CGP's type-level constructs restored to readable notation. The [installation guide](/docs/tooling/cargo-cgp/installation) covers setup, updates, and the Nix alternative, and the [cargo-cgp v0.1.0 release notes](/docs/release-notes/cargo-cgp/v0.1.0) list what this first release supports. + +## 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. + +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. + +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/): 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. + +Across more than 360 pages, the website now contains roughly 365,000 words of documentation prose, excluding code blocks and the mirrored skill files. At 300 words per printed page, that would be about 1,200 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. + +### How the documentation is written + +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. + +When a page needs an update, the agent can pick up from the same record. That saves me time because each revision starts from what the record already holds about CGP. 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 [can still contain errors](/docs/ai/knowledge-base/#its-current-state), because both source checks and human review can miss them. I remain responsible for what the project publishes. + +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 + +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 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. + +Before it works on your code, the skill checks which `cgp` release your project uses and tells you when that differs from the release it describes. You still need to review and verify the assistant's suggested code. The [installation page](/docs/ai/skills/installation) explains how to install the skill in your agent, 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 + +The release also introduces [**namespaces**](/docs/concepts/namespaces), for grouping components as an application grows. + +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 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. + +### Start with a manager per domain {#an-example-social-media-web-app} + +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/main/web-app) uses placeholder database operations. + +Our service starts with one manager trait for users and another for posts. + +```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>; +} +``` + +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. + +Choosing a manager provider chooses all its methods together. That is a deliberate choice for this first version, since 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. + +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)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + // ... + } + + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + // ... + } + + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + // ... + } +} + +#[cgp_impl(new PostgresPostManager)] +impl PostManager { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + // ... + } + + fn get_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result { + // ... + } + + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + // ... + } + + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + // ... + } +} +``` + +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. + +For our production application, we supply the database field and choose the PostgreSQL managers: + +```rust +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + } +} +``` + +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 + +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)] +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); + } + + // ... + } + + // ... +} +``` + +Each manager compares its filter's score with a rejection threshold before writing to the database. The `#[uses]` attribute declares the new trait dependency, while `#[implicit] database` still supplies the database handle. The remaining manager methods are omitted here. + +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)] +pub struct ProductionApp { + pub database: PostgresDb, + // ... // AI client credentials +} + +delegate_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: AiUserCensor, + SpamMessageDetectorComponent: AiSpamMessageDetector, + } +} + +#[derive(HasField)] +pub struct TestApp { + pub database: PostgresDb, +} + +delegate_and_check_components! { + TestApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } +} +``` + +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. + +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} + +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. + +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. + +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. + +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)] +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>; +} +``` + +The user-creation provider needs the censor, while the getter needs only the database: + +```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 { + // ... + } +} +``` + +`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 + +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)] +#[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 { + // ... + } +} +``` + +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. + +`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 + +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! { + ProductionApp { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} +``` + +Splitting the managers took our wiring table from four entries to nine. A larger application might have dozens or hundreds. To find out how it handles users, a reader has to pick the user bindings out of that list. + +We can make the list easier to read by collecting the user bindings into their own provider bundle: + +```rust +delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} +``` + +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](/docs/reference/macros/delegate_components#the-key-forms): + +```rust +delegate_components! { + ProductionApp { + [ + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + ]: + PostgresUserComponents, + [ + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + ]: + PostgresPostComponents, + [ + UsernameCensorComponent, + SpamMessageDetectorComponent, + ]: + AiContentFilterComponents, + } +} +``` + +The bundle groups the implementations. The application still has to list every component it delegates to that bundle. 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 + +Ideally, the configuration would say something like this, with a key for each group: + +```text +delegate_components! { + ProductionApp { + ???: // all user components + PostgresUserComponents, + ???: // all post components + PostgresPostComponents, + ???: // all content filter components + AiContentFilterComponents, + } +} +``` + +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. + +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! { + ProductionApp { + all_user_components!(): + PostgresUserComponents, + all_post_components!(): + PostgresPostComponents, + all_content_filter_components!(): + AiContentFilterComponents, + } +} +``` + +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 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. + +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} + +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)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} +``` + +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`. + +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)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} +``` + +Post operations get their own `@app.core.post` prefix: + +```rust +#[cgp_component(PostCreator)] +#[prefix(@app.core.post in DefaultNamespace)] +pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; +} +``` + +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. + +### 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: + +```rust +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 + } +} +``` + +Notice that these intermediate bundles also join `DefaultNamespace`. When a lookup reaches a bundle, it receives the bare component key, and 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: + +```rust +delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: ProductionExtraComponents, + } +} +``` + +For testing, the core stays the same. Only the extras entry changes, selecting `DummyExtraComponents` for deterministic filtering: + +```rust {6} +delegate_components! { + TestApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: DummyExtraComponents, + } +} +``` + +For a local configuration, we could make the other choice: keep the production filters and select a SQLite-backed core: + +```rust {5} +delegate_components! { + LocalApp { + namespace DefaultNamespace; + + @app.core: SqliteCoreComponents, + @app.extra: ProductionExtraComponents, + } +} +``` + +In each case, one entry tells us how the configuration differs from production. `TestApp` changes the extras, while `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. + +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 + +Will these providers work together? A `delegate_components!` block can compile before Rust has checked the providers' dependencies. We can ask Rust to check them now by naming the components we need on the concrete application. + +```rust +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } +} +``` + +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`. + +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} + +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. + +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**. + +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 using the new [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) macro: + +```rust +cgp_namespace! { + new DefaultAppComponents: DefaultNamespace +} +``` + +`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]`](/docs/reference/attributes/default_impl) to our earlier `GetUserWithPostgres` definition: + +```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 + } +} +``` + +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! { + DefaultAppComponents { + @app.core.user.UserGetterComponent: GetUserWithPostgres, + } +} +``` + +These are alternative ways to register the same binding, so 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](/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 + +`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! { + DefaultAppComponents { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + } +} +``` + +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: AiContentFilterComponents, + } +} +``` + +Every context that joins `DefaultAppComponents` gets its user and post providers from it. We left the filter path open so a test context can select `DummyContentFilterComponents` there instead. + +### Choose how much wiring to share + +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. + +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. + +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. + +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 + +Namespaces are the largest change, but several smaller additions also make CGP easier to write, read, and use in more kinds of crates. You can use these without following the full application refactoring above: + +- **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. +- **Build without the standard library.** With its default features, `cgp` needs neither `std` nor an allocator, so it fits a `no_std` crate on a target without either. The two error providers that format an error into a `String`, `DebugError` and `DisplayError`, need the new `alloc` feature. +- **Borrow any string field.** An [`#[implicit]`](/docs/reference/attributes/implicit) `name: &str` argument now reads any field whose type implements `AsRef`, such as `String`, `Box`, or `Cow<'static, str>`, where v0.7.0 required a `String`. An `Option<&str>` argument reads an `Option` of any of them. +- **Document what the macros generate.** Every macro that declares a public item gives it a short doc line when you write none, so a crate can turn on `#![warn(missing_docs)]` without the lint flagging a component marker or a provider struct. A provider trait's doc also names its component key, so hovering the trait in an editor shows the key to import. + +That last point helps with a mistake newcomers commonly make. A provider header such as `impl Greeter` names its component key by adding `Component` to the trait's name, giving `GreeterComponent`. So a provider written in another module imports the key beside the trait, as the [`#[cgp_impl]` reference](/docs/reference/macros/cgp_impl#importing-the-component-key) explains: + +```rust +use crate::components::{Greeter, GreeterComponent}; + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} +``` + +Forget `GreeterComponent`, and the compiler reports that it cannot find the key, pointing at `Greeter` in the header. `cargo cgp check` reports this as [`CGP-E041`](/docs/tooling/cargo-cgp/error-codes#cgp-e041), with a fix that inserts the `use` line. An editor running the checker offers that fix on the trait's name. If the trait is imported under another name, or the component renames its key, the checker reports [`CGP-E070`](/docs/tooling/cargo-cgp/error-codes#cgp-e070) instead and offers to name the key in the attribute. + +You can also skip the import by naming the trait by its path, as in `impl crate::components::Greeter`. The key then follows the same path, so the module needs no `use` line for it. + +The handler macros now generate self-contained code, so you can use them without importing the prelude 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 + +Upgrading from v0.7.0 needs source changes. The largest is the removal of presets, which namespaces replace in this release, and most applications will also need explicit imports for items that used to come from the prelude. The [v0.8.0 release notes](/docs/release-notes/cgp/v0.8.0) list every change, with the upgrade steps in order. + +Two projects built with CGP move to v0.8.0 at the same time. [cgp-serde](/docs/projects/cgp-serde) 0.3.0 can now serialize and deserialize enums, and [Hypershell](/docs/projects/hypershell) 0.2.0 assembles its language from a namespace instead of presets. If your code builds on either, the [cgp-serde v0.3.0](/docs/release-notes/cgp-serde/v0.3.0) and [Hypershell v0.2.0](/docs/release-notes/hypershell/v0.2.0) release notes give the upgrade steps. + +### 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. + +The removed preset constructs and their replacements are: + +| 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. | +| `replace_with!` | Nothing. The macros that presets generated expanded through it, so remove any call you wrote yourself. | + +### Import what the prelude no longer exports + +`cgp::prelude` now exports only the names CGP code usually writes: the macros, the derives, `PhantomData`, and a few traits and providers such as `HasErrorType`, `CanRaiseError`, `UseType`, and `DefaultNamespace`. The code the macros generate reaches CGP's items through a separate `cgp::macro_prelude`, so the prelude no longer has to carry those items. If your code names one of the dropped items through the glob import, the compiler reports that it cannot find it, and you import it from its module: + +```rust +use cgp::core::component::DelegateComponent; +use cgp::core::field::traits::HasField; +use cgp::extra::handler::{Computer, ComputerComponent}; +``` + +The dropped names come from these modules: + +- **Wiring traits** such as `DelegateComponent` and `IsProviderFor`: `cgp::core::component`. +- **Field-access traits and type-level types** such as `Cons`, `Nil`, and `Index`: the modules under `cgp::core::field`. +- **`HasType` and `TypeProvider`**: `cgp::core::types`. +- **The handler family**, with its traits, keys, and providers: `cgp::extra::handler`. + +A derive does not need its trait imported, so `#[derive(HasField)]` still works through the prelude, while a `HasField` bound or a `.get_field()` call needs the import. A provider for a handler trait such as `Computer` imports its key, `ComputerComponent`, beside the trait, because the provider's header names the key, as [Other improvements](#other-improvements) describes. + +Raw compiler output changes slightly as a result. Where v0.7.0 printed a type such as `cgp::prelude::Chars`, the compiler can now print `cgp::macro_prelude::Chars`, as in the [`cargo check` comparison](#find-a-missing-field) above. + +The type-level types also lose their Greek-letter names. v0.7.0 declared them as `π`, `ε`, `σ`, `θ`, `ζ`, `ψ`, `δ`, and `ω`, with `Cons`, `Nil`, `Either`, `Void`, `Chars`, `Symbol`, `Index`, and `Field` as aliases, and the prelude exported both spellings. Only the English names remain, so code that wrote a Greek name switches to the English one, imported from `cgp::core::field::types`. Raw compiler output changes with them, printing `Cons<…>` and `Chars<…>` where v0.7.0 printed `π<…>` and `ζ<…>`. + +### Turn on `alloc` for the formatting error providers + +The default features of `cgp` are now empty, so the library builds without `std` or an allocator. In v0.7.0, the defaults turned on `DebugError` and `DisplayError`, the error providers that format an error into a `String`. If your wiring uses either, turn on the `alloc` feature: + +```toml +[dependencies] +cgp = { version = "0.8.0", features = ["alloc"] } +``` + +### Update attribute syntax and direct dependencies + +The associated-type separator in `#[use_type]` changes from `::` to `.`: + +```rust +// v0.7.0 +#[use_type(HasErrorType::Error)] + +// v0.8.0 +#[use_type(HasErrorType.Error)] +``` + +Equality imports use the new separator too. Write `#[use_type(HasErrorType.{Error = AppError})]`. An import from another context changes shape as well, with the context named after `in`: `#[use_type(@Types::HasScalarType::Scalar)]` becomes `#[use_type(HasScalarType.Scalar in Types)]`. The [`#[use_type]` reference](/docs/reference/attributes/use_type) covers each form. + +A component that generates a `UseDelegate` dispatcher moves the `derive_delegate` key of `#[cgp_component]` into [an attribute of its own](/docs/reference/attributes/derive_delegate), one per dispatcher: + +```rust +// v0.7.0 +#[cgp_component { + provider: AreaCalculator, + derive_delegate: UseDelegate, +}] + +// v0.8.0 +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +``` + +A new component does not need either form, because the `open` statement from [Other improvements](#other-improvements) dispatches it per type. + +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. + +Self-contained handler-macro expansions may leave imports unused. Remove imports the compiler reports when they existed only for the old expansion. + +`#[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. + +`DelegateComponent`, `IsProviderFor`, `HasField`, and `HasFieldMut` no longer carry custom `#[diagnostic::on_unimplemented]` messages. Plain `cargo check` now reports an unmet bound on them in the compiler's own wording, and `cargo cgp check` rewrites those errors into its own summary. If a test compares compiler output, as a UI test does, update the messages it expects. + +### 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 + +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 takes time to learn. Its ecosystem is small, and I still have work to do on the tooling and documentation. My suggestion is to try it on one problem you already have. If you already use CGP, try grouping one area 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. + +--- + +*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/cgp-skills b/cgp-skills new file mode 160000 index 00000000..e227ebed --- /dev/null +++ b/cgp-skills @@ -0,0 +1 @@ +Subproject commit e227ebed254e1de5c4a8d38f7a5edb7da3cda113 diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index df9a1b38..38db7caf 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,7 +1,8 @@ { - "label": "AI Assisted Development", - "position": 4, + "label": "AI-Assisted Development", + "position": 10, "link": { - "type": "generated-index" + "type": "doc", + "id": "ai/index" } } diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md new file mode 100644 index 00000000..c44098b2 --- /dev/null +++ b/docs/ai/disclaimer.md @@ -0,0 +1,150 @@ +--- +title: 'How AI Is Used in the CGP Project' +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 + +AI agents do much of the work on [Context-Generic Programming (CGP)](/docs/), a Rust library for +writing several implementations of a trait and choosing which one each type uses. They write most of +its documentation and most of its error toolchain, maintain much of its test suite, and help +implement parts of the library. The author designs every CGP construct and interface, and writes the +core library almost entirely by hand. To explain why their roles differ, this page goes through each +part of the project, from the most agent-written to the least, describing who works on it, how that +work is checked, and what those checks can miss. + +## Why the levels differ + +How much agents write depends partly on whether their work becomes part of your compiled program. +Library code does, so you have to trust it. Documentation, tools, and tests stay outside that +program: a tool runs on your project, and a test exercises the library. + +It also matters whether the work can be checked against something that already exists. A claim about +a macro can be checked against the macro's source and expansion snapshots, and a tool's output +against its test fixtures. Design, however, decides what the library should do in the first place. +There is no existing implementation to check that decision against, and passing tests cannot settle +it. + +Agents therefore do the most writing where the result stays out of your program and can be checked, +and the least in the core library, whose design sets the behavior everything else must follow. These +criteria decide who writes each part, but they do not make any part correct. + +## Documentation and reference pages + +AI agents write most of CGP's reference pages, explanations, guides, and error documentation using +the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). This public +repository, also written by agents, records how CGP works and the rules agents must follow. The +pages on this site adapt that record for people. + +**The source code is authoritative.** Agents must check claims about accepted syntax, generated +names, and macro expansions against the code, the tests, or the expansion snapshots, and when a +document disagrees with the code, the document is corrected. A change to how CGP behaves must update +its documentation in the same change. + +Some of these checks are mechanical: expansion snapshots fail when a macro's output changes, and +the 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, both of which can miss +a stale sentence. As a result, some documents still contain +errors that no review has found yet, and the pages written from them share those errors. + +The author directs this work by designing CGP, writing the rules agents follow, and choosing what +gets documented. Those rules tell an agent to ask rather than guess when a choice has more than one +reasonable answer. To make the agent's contribution visible, each commit it contributes to carries a +`Co-Authored-By` trailer naming the model. That record shows who contributed, not that every +statement is correct. [How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented) +gives the full account of the process. + +**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 page, the page describing how the +documentation is written, and every blog post. On each Comparisons page, which describes another +community's tool beside CGP, the author reads in full the 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 rest of each comparison page, follows a writing guide +and receives spot checks, without the author reading each one line by line. + +Source checks and human review catch different mistakes. Checking an expansion against the source +can reveal a technical error, while reading an explanation can reveal a misleading argument. Neither +catches every error, and the project remains responsible for correcting the ones that get through. + +## Blog posts and tutorials + +The author drafts blog posts and tutorials, supplying their argument, their examples, and the +judgment about what to teach. An agent then revises the prose and checks the code and claims against +the knowledge base. This differs from reference pages, where an agent writes the first draft. +Although the revision improves the prose and checks the code, it does not make the argument correct. + +Older text on this site went through broader LLM refinement, as +[the post about this website](/blog/2026/02/21/new-website) describes. This section describes the +current process for blog posts and tutorials. + +## Tooling and tests + +Agents write most of [cargo-cgp](/docs/tooling/cargo-cgp), CGP's error toolchain, and maintain much +of CGP's test suite. Neither becomes part of your compiled program: `cargo-cgp` runs on your +project, and the tests exercise the library. Their results can also be checked against existing +evidence: `cargo-cgp`'s output against its test fixtures, and the tests against the library's +behavior. + +Agents also extend the tests across the many syntax forms the procedural macros accept. That work is +broad and repetitive, and agents make coverage practical beyond what the author could maintain +alone. Passing tests are evidence only for the cases they cover, though, and a wrong expectation or +a missing case can still let a bug through. + +`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 + +The author designs every CGP construct and interface, and writes the core library almost entirely +by hand. This is the code your application imports and compiles, so the author takes direct +responsibility for its design and implementation. + +Agents help with correctness checks, code-quality review, and the implementation of the procedural +macros, and the author directs and reviews that work. The +[cgp repository](https://github.com/contextgeneric/cgp) records that work with `Co-Authored-By` +trailers, including for contributions to the macros. The author decides what CGP provides and how +its interfaces fit together, while agents help implement and check some of those decisions. The +library does contain AI contributions, and its checks cannot guarantee that every implementation is +correct. + +## Contributions from others + +Contributions from outside the project follow a deliberately light policy, with a more detailed one +to follow. For now, AI-assisted contributions must meet these requirements: + +- Use the knowledge base for contributions to any CGP repository, so the agent works from the + current syntax and updates the documentation its change affects. +- Include the prompts used to verify the issue or apply the fix in any AI-assisted pull request or + issue. 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. + +Finding a problem in the knowledge base is a useful contribution in its own right, because the +checks can miss one. File it on the knowledge base's +[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. 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 + +A new or substantially rewritten page carries a short note at the bottom, linking to the section +of this page that describes how it was made. The front page is the one exception and carries no +note. An older page gets a note only once its provenance has been established, so a page without +one may still have been written with AI assistance. + +--- + +*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/index.md b/docs/ai/index.md new file mode 100644 index 00000000..0715100a --- /dev/null +++ b/docs/ai/index.md @@ -0,0 +1,59 @@ +--- +title: 'AI-Assisted Development' +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'How a coding agent can help you work with CGP through its agent skill and knowledge base, and how the CGP project itself uses AI to write its documentation, tools, and tests.' +--- + +# AI-Assisted Development + +If you use a coding agent to work with [Context-Generic Programming (CGP)](/docs/), a Rust library +that lets you write several implementations of a trait and choose which one each type uses, the +agent needs more information about CGP than its training provides. This section explains how to give +your agent that information. It also explains how the CGP project itself uses agents, including how +much of the documentation they write and how that work is checked. + +## Working with CGP through an agent + +Much of what has been published about CGP shows syntax the library no longer accepts. An agent +reading your code also cannot see what CGP's macros generate from it. To fill these gaps, CGP +provides an agent skill that teaches the agent CGP's vocabulary, its current syntax, and how to read +its compile errors. The skill draws on a knowledge base that holds the complete record behind it. + +Together, the skill and knowledge base can make it easier to learn CGP, write its wiring, and read +its diagnostics. Your agent can still write wrong code, though, so review what it produces as you +would any other change. + +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), + then follow [Installing the CGP Skill](/docs/ai/skills/installation) for the agent you use. +- **Find details the skill does not cover,** such as a macro's corner case or how it is + implemented. [Using the Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) + shows how to point your agent at the full record. +- **Change CGP itself with an agent's help.** [Contributing to CGP with an + Agent](/docs/ai/knowledge-base/contributing-with-an-agent) gives the contribution policy, the + setup, and the rules your agent follows. + +The skill and knowledge base are written for agents. If you want to learn CGP yourself, start with +the [tutorials](/docs/tutorials/hello) and the [Concepts](/docs/concepts) pages. + +## How the CGP project uses AI + +AI agents write most of CGP's documentation and most of `cargo-cgp`, maintain much of its test +suite, and help implement parts of the library. The author designs every CGP construct and writes +the core library almost entirely by hand. The following pages explain who does this work and how +it is checked: + +- **Which parts of the project do agents write, and who reviews them?** Read [How AI Is Used in the + CGP Project](/docs/ai/disclaimer). Pages written with an agent's help link to it from a note at + the bottom of each page. +- **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 record that 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..325a7069 --- /dev/null +++ b/docs/ai/knowledge-base/contributing-with-an-agent.md @@ -0,0 +1,152 @@ +--- +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 Rust library for writing several implementations +of a trait and choosing which one each type uses. This page is for contributors who want to change +CGP itself with a coding agent's help. Your contribution might involve the library, the +[cargo-cgp](/docs/tooling/cargo-cgp) toolchain, the agent skill, or the documentation. Before you +start, you'll need to know the contribution policy and how to set up the repositories so your agent +can follow their rules. This page walks through that preparation and explains how to report +problems you find in the knowledge base. It assumes you already use an agent and have contributed +to a Rust project through GitHub before. + +## Contribution policy + +If an agent writes or changes code or documentation in your contribution, it must use the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). This requirement applies +to every CGP repository. Direct your agent to read the knowledge base, which is written for agents, +and to follow the `AGENTS.md` file of each repository it touches. These sources give it CGP's +vocabulary and current syntax, and tell it which documentation and skill updates to include with +your change. + +The policy exists because an agent working from its training alone reproduces CGP's outdated +syntax and invents semantics the knowledge base already records. +[How CGP's Documentation Is Written](how-cgp-is-documented.md) explains the problem and the process +used to address 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. + +The policy is deliberately light, and a more detailed one will follow. For now, it asks only that +your agent use the knowledge base and that you include the prompts. 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 ways to contribute, and you can do +it without setting up anything locally. Its checks can miss errors, so some documents still contain +them, as [its current state](index.md#its-current-state) describes. When you find an error or an +inconsistency between documents or between a document and the code, you save the project review work +it 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 +``` + +Some repositories have specific requirements for this layout: + +- **The skill.** The CGP skill lives in `cgp-skills`. A change to a construct must update the skill + in the same contribution, so clone it beside `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`. + +For the full list of repositories, including projects built with CGP, see the knowledge base's +[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md). + +## Follow the repository rules + +Once the repositories are in place, have your agent read the `AGENTS.md` at the root of each one +it will work in. This should be the first file it reads in that repository. Each file gives the +repository's rules and names the guide to read for each kind of task, so your agent loads the +detailed instructions relevant to its work. In code repositories, it also points to the build and +test checks. + +You can find these rules in the following repositories: + +- [`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) +- [The website](https://github.com/contextgeneric/contextgeneric.dev/blob/main/AGENTS.md) +- [`cgp-examples`](https://github.com/contextgeneric/cgp-examples/blob/main/AGENTS.md) +- [`hypershell`](https://github.com/contextgeneric/hypershell/blob/main/AGENTS.md) +- [`cgp-serde`](https://github.com/contextgeneric/cgp-serde/blob/main/AGENTS.md) + +All of these repositories require you to include documentation updates in the same contribution as +the change. The code is the authority, so the knowledge base, skill, and site must stay consistent +with it. The updates you need depend on what you change: + +- **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, then applies to the material written + from it: the matching part of the skill and the page on this site adapted from it. + +A contribution that spans repositories needs a pull request in each. Link them to each other so +they can be reviewed together. + +Before your agent starts, the rules ask it to load the CGP skill from +[`cgp-skills`](https://github.com/contextgeneric/cgp-skills), so make that skill available in the +way your agent loads skills, as [Installing the CGP Skill](/docs/ai/skills/installation) describes. +For prose, the rules also name the `point-first-writing` skill. That skill is optional and isn't +part of the CGP repositories, so your agent uses it only when it is available. + +The rules also shape how the agent works with you. When a choice has more than one defensible +answer, such as when the intended behavior is unclear, it stops and asks you. It also creates +commits only when you ask, so you decide when the work is ready to commit and submit. + +## Use an established workflow + +For common tasks, your agent can follow a complete workflow in the knowledge base. The `cgp` and +`cargo-cgp` repositories each point to one: + +- **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 by 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..37b9992c --- /dev/null +++ b/docs/ai/knowledge-base/how-cgp-is-documented.md @@ -0,0 +1,151 @@ +--- +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 + +How much can you trust documentation written by an AI agent? Agents write most of the documentation +for [Context-Generic Programming (CGP)](/docs/), a Rust library for writing several implementations +of a trait and choosing which one each type uses. To assess that work, it helps to understand what +the agents write from and how their claims are checked. + +The agents use 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 explains why that record is needed, how it is maintained, +and where the checks stop. For details of who reviews which pages, see the [AI +disclaimer](/docs/ai/disclaimer). + +## The problem with one-shot prompts + +When an agent is asked to write about CGP in a single prompt, without a written record to work from, +it falls back on what it learned in training. For CGP, that is a poor source: the 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 fills the gaps in what it +remembers with plausible guesses about what the macros generate. + +Giving the agent the source code does not solve the problem on its own. 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 reconstruction in prose so that later agents can read the conclusion +without deriving it again. Each document covers one subject: a construct, a concept that applies +across constructs, a class of compile errors, a worked example, the internals of one macro, or a +page of this site. When it mentions another subject, it links to the document that explains that +subject. This leaves one explanation to keep current and avoids duplicating accounts that can drift +apart. + +For that record to remain useful, it must stay accurate. 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. +- **Behavior and documentation change together.** When a change affects how a construct behaves, + the matching documents must be updated 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 encounters old syntax can + find what replaced it. + +## One construct, five views + +The rules require the accounts of a construct to agree wherever it is described. For +`#[cgp_component]`, that means keeping the following sources in sync: + +- **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/cgp/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 + +These rules are public. The knowledge base's +[AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md) holds the +rules that apply to every document, while each section has a writing guide for its own kind of +document. Those guides explain how to structure a reference document, index tests in an +implementation document, or document an error class with an example that produces it. + +Each code repository has an `AGENTS.md` of its own, which directs agents to the CGP skill and the +knowledge base to learn CGP. Before a task, agents load the skill, the rules, and the guide for the +kind of document they are working on. They also read +[summary.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/summary.md), a one-line +index of every document, to find the documents the task needs. + +Public writing follows written rules too. The `communication-strategy/` section sets out how to +present CGP, including the voice of each kind of page, the vocabulary, how to state costs alongside +benefits, and how to describe other projects. The `website/` section provides a writing guide for +each kind of page on this site. It also records which documents each page draws on, how it was +written, 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. When a choice has more than one defensible answer, the rules tell the agent to +stop and ask the person directing it. For example, an agent must ask when the intended behavior is +unclear or it is uncertain where a document belongs, so it does not build further work on a guess. + +The work proceeds in separate passes. During review, every claim in a document is checked against +the source before its prose is improved, so polished wording cannot hide a wrong claim. Before a new +kind of page is written for this site, a writing guide defines its purpose and what must not appear +on it. The draft is then checked against that guide. + +## From the record to this site + +The knowledge base also supplies the material for the agent skill and this site's pages. The skill +condenses that material, while the site's pages adapt it for people. Reference pages come from the +knowledge base's reference documents, Concepts pages from its concept documents, and comparison +pages from its related-work documents. + +When a page is written or revised, its code examples are also added to a test crate in the website's +repository. If one of those snippets stops compiling, it 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 of these checks are mechanical, but most depend on judgment. Expansion snapshots fail a test +when a macro's output changes, the [cargo-cgp](/docs/tooling/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's [current state](index.md#its-current-state) explains how to assess a +document with that limitation in mind. The aim is to improve the knowledge base step by step toward +full accuracy, meaning agreement with the author's intent as well as with the source. + +This process cannot guarantee that agent-written documentation is correct. It does, however, make an +error checkable against a public record and correctable at its source, after which the correction +reaches both 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..4991c4da --- /dev/null +++ b/docs/ai/knowledge-base/index.md @@ -0,0 +1,107 @@ +--- +title: 'The CGP Knowledge Base' +sidebar_label: 'Overview' +sidebar_position: 1 +description: 'The public, agent-written record behind CGP''s documentation and agent skill: what it contains, who reads it, and how it relates to the source code.' +--- + +# The CGP Knowledge Base + +[Context-Generic Programming (CGP)](/docs/) is a Rust library for writing several implementations +of a trait and choosing which one each type uses. Most of its documentation, both on this site and +in its [agent skill](/docs/ai/skills), draws on a public repository: the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). It records what each of +CGP's constructs means, 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. + +## What it is for + +An agent working with CGP needs to understand its syntax, but neither its training nor the macro +source reliably provides that understanding. The source shows token-stream transformations rather +than the traits and impls they produce, while much of the published material shows syntax the +library no longer accepts. The knowledge base records what that syntax means so an agent can read +the explanation instead of reconstructing it or guessing. + +That explanation includes the syntax each construct accepts and the code its macro expands to. +Alongside it, the knowledge base documents the internals of the macros and of +[cargo-cgp](/docs/tooling/cargo-cgp), the classes of compile error CGP produces, worked examples, and +comparisons with related ideas from other languages. + +For everyday work, the agent skill condenses this record to fit in an agent's context alongside your +code and teaches it to read and write CGP. When the skill leaves a question unanswered, the agent +can turn to the complete record in the knowledge base. It might need to understand a macro's corner +case or implementation, for example, or find out why a diagnostic is worded a certain way. + +## Who reads it + +Because the knowledge base is written for agents, its documents assume the skill's vocabulary and +favor completeness over a gentle introduction. They also record unfinished work and known defects +alongside current behavior. If you're learning CGP yourself, start with the +[tutorials](/docs/tutorials/hello) and the [Concepts](/docs/concepts) pages. + +You may still find the knowledge base useful when you want the complete record of a construct, +want to check how a page on this site was produced, or are deciding whether to contribute. + +## How it relates to the code + +CGP's source code is the final authority. When a document disagrees with the code, the document is +wrong and is corrected. The knowledge base explains what the source means, the agent skill +condenses that explanation, and the pages on this site adapt it for people. Corrections follow the +same path, starting in the source or the knowledge base and then reaching the skill and the site. + +## Its current state + +Agents check the knowledge base against the source code, but the checks can miss a stale sentence +or an inconsistency. Some documents therefore still contain errors that review has yet to uncover. +Treat each document as the best available record, checked against the source but without a +guarantee that it is free of errors. + +Reporting and fixing these errors helps the knowledge base reflect both the source and the +author's intent for CGP more accurately. If you find an error, 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#report-problems-in-the-knowledge-base) +describes. + +## What it contains + +Each top-level section of the knowledge base has a `README.md` that lists 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 supply most of the code on + this site. +- **`related-work/`:** comparisons with the 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/`:** the libraries built with CGP, such as Hypershell and cgp-serde. + +The top-level files help an agent find its way before it opens a 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, each with a one-line summary. +- **[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..d60a6d91 --- /dev/null +++ b/docs/ai/knowledge-base/using-it-with-your-agent.md @@ -0,0 +1,101 @@ +--- +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 goes beyond the agent skill, from corner cases and unfamiliar errors to implementation details and comparisons.' +--- + +# Using the Knowledge Base with Your Agent + +[Context-Generic Programming (CGP)](/docs/) is a Rust library for writing several implementations of +a trait and choosing which one each type uses. Your agent can learn its everyday use from the +[agent skill](/docs/ai/skills), but some questions go beyond what the skill covers. For those, you +can point the agent at the public +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), the full record the +skill is written from. + +The knowledge base is written for agents, so this page explains how to direct your agent to it. +It assumes you already use a coding 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, how to wire components together, and how to read compile errors. It is also +sized to fit in the agent's context alongside your code. For tasks such as writing a component, +wiring a context, or fixing a missing dependency, the skill is usually enough. + +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/tooling/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/tooling/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 the details it leaves out, so an agent +with the skill may fetch some of them on its own. You can also direct it to the documents that +address your question. + +## 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 uses this layout when referring to sibling +repositories, which are listed in +[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md). + +## 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 these 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/main/cgp/SKILL.md) + instead, as [Installing the CGP Skill](/docs/ai/skills/installation#agents-without-skill-support) + 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 knowledge base. +3. **Read the section that covers 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 knowledge base's `AGENTS.md` and the writing guides in its sections describe how its own +documents are written and maintained. As the README explains, those rules apply when an agent +edits the knowledge base, but an agent that only reads it does not need to follow them. + +Ask the agent to read selectively, because each document takes up space in its context. The full +document index, +[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 covers 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. A document can also lag behind the code or +contain an error that reviewers have not found, as the knowledge base's +[current state](index.md#its-current-state) explains. 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/cgp/SKILL.md b/docs/ai/skills/cgp/SKILL.md new file mode 120000 index 00000000..bd6b3e8f --- /dev/null +++ b/docs/ai/skills/cgp/SKILL.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/SKILL.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/_category_.json b/docs/ai/skills/cgp/_category_.json new file mode 100644 index 00000000..acaa490f --- /dev/null +++ b/docs/ai/skills/cgp/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "/cgp", + "position": 3, + "link": { + "type": "doc", + "id": "ai/skills/cgp/SKILL" + } +} diff --git a/docs/ai/skills/cgp/references/_category_.json b/docs/ai/skills/cgp/references/_category_.json new file mode 100644 index 00000000..89db67f3 --- /dev/null +++ b/docs/ai/skills/cgp/references/_category_.json @@ -0,0 +1,7 @@ +{ + "label": "References", + "link": { + "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/ai/skills/cgp/references/abstract-types.md b/docs/ai/skills/cgp/references/abstract-types.md new file mode 120000 index 00000000..35ae0159 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/checking.md b/docs/ai/skills/cgp/references/checking.md new file mode 120000 index 00000000..71ce7a7d --- /dev/null +++ b/docs/ai/skills/cgp/references/checking.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/checking.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/components.md b/docs/ai/skills/cgp/references/components.md new file mode 120000 index 00000000..f864f723 --- /dev/null +++ b/docs/ai/skills/cgp/references/components.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/components.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/error-backends.md b/docs/ai/skills/cgp/references/error-backends.md new file mode 120000 index 00000000..c37276be --- /dev/null +++ b/docs/ai/skills/cgp/references/error-backends.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/error-backends.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/error-extraction.md b/docs/ai/skills/cgp/references/error-extraction.md new file mode 120000 index 00000000..1b2a5032 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/error-handling.md b/docs/ai/skills/cgp/references/error-handling.md new file mode 120000 index 00000000..456aa26b --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/extensible-data.md b/docs/ai/skills/cgp/references/extensible-data.md new file mode 120000 index 00000000..b2c89344 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/functions-and-getters.md b/docs/ai/skills/cgp/references/functions-and-getters.md new file mode 120000 index 00000000..77f425da --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/handlers.md b/docs/ai/skills/cgp/references/handlers.md new file mode 120000 index 00000000..360a41c1 --- /dev/null +++ b/docs/ai/skills/cgp/references/handlers.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/handlers.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/higher-order-providers.md b/docs/ai/skills/cgp/references/higher-order-providers.md new file mode 120000 index 00000000..0b0041f1 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/macro-grammar.md b/docs/ai/skills/cgp/references/macro-grammar.md new file mode 120000 index 00000000..1af768fb --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/modern-idioms.md b/docs/ai/skills/cgp/references/modern-idioms.md new file mode 120000 index 00000000..df8988c2 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/modularity-hierarchy.md b/docs/ai/skills/cgp/references/modularity-hierarchy.md new file mode 120000 index 00000000..fdde6b2f --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/namespaces.md b/docs/ai/skills/cgp/references/namespaces.md new file mode 120000 index 00000000..d9cf5b2b --- /dev/null +++ b/docs/ai/skills/cgp/references/namespaces.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/namespaces.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/type-level-primitives.md b/docs/ai/skills/cgp/references/type-level-primitives.md new file mode 120000 index 00000000..8e76e5f6 --- /dev/null +++ b/docs/ai/skills/cgp/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/cgp/references/versions.md b/docs/ai/skills/cgp/references/versions.md new file mode 120000 index 00000000..89fa8720 --- /dev/null +++ b/docs/ai/skills/cgp/references/versions.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/versions.md \ No newline at end of file diff --git a/docs/ai/skills/cgp/references/wiring.md b/docs/ai/skills/cgp/references/wiring.md new file mode 120000 index 00000000..e072a6ae --- /dev/null +++ b/docs/ai/skills/cgp/references/wiring.md @@ -0,0 +1 @@ +../../../../../cgp-skills/cgp/references/wiring.md \ No newline at end of file diff --git a/docs/ai/skills/index.md b/docs/ai/skills/index.md index 231020d3..58096fa0 100644 --- a/docs/ai/skills/index.md +++ b/docs/ai/skills/index.md @@ -1,2256 +1,60 @@ --- +title: Agent Skills +description: The agent skills that teach a coding agent to read, write, and debug Context-Generic Programming code, and the skill pages this site publishes. sidebar_position: 1 --- -# CGP Skills +# Agent Skills -## Using Agent Skills to Learn CGP +A coding agent working on a [Context-Generic Programming (CGP)](/docs/) project needs more than +the source code to understand it. CGP's macros generate the traits and impls that its wiring +connects, while the agent's training may show syntax the library no longer accepts. An agent skill +supplies that missing knowledge through Markdown instructions that the agent loads when a task +needs them. This section publishes CGP's skills from the +[cgp-skills repository](https://github.com/contextgeneric/cgp-skills), so you can read what your +agent reads. -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. +## The `/cgp` skill -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. +The [`/cgp` skill](/docs/ai/skills/cgp/SKILL) teaches an agent to read, write, debug, and explain +CGP code. Its main page introduces consumer and provider traits, wiring, and impl-side dependencies, +shows what the macros expand to, and recommends `cargo-cgp` for readable compiler errors. It then +directs the agent to references for the task at hand, covering topics from +[components](/docs/ai/skills/cgp/references/components) and +[wiring](/docs/ai/skills/cgp/references/wiring) to +[namespaces](/docs/ai/skills/cgp/references/namespaces). The sidebar lists all the references. -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. +The skill supports `cgp` v0.8.0 and every later release. If your project uses a newer `cgp` release +than the skill describes, the instructions tell the agent to check for a newer version of the +skill. ---- - -## 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; -} -``` +These instructions help the agent work with CGP, but they do not guarantee correct code. Review +what the agent writes as you would any other change. You can also read the skill to see the +instructions the agent follows. -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. +To install it, give your agent the repository's URL and ask it to install the `/cgp` skill, or +follow the steps for your agent in [Installing the CGP Skill](/docs/ai/skills/installation). -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. +## Beyond the skill -## `#[extend_where]` Attribute +The skill gives an agent dense rules and worked examples for one task at a time. That format is +not well suited to learning CGP yourself, so start with the [tutorials](/docs/tutorials/hello) and +the [Concepts](/docs/concepts) pages instead. -The `#[extend_where]` attribute can be used in `#[cgp_fn]` to add `where` clauses to the generated trait definition. For example: +Your agent may also need more detail than the skill provides, such as a macro's corner cases or +how it is implemented. That detail lives in the CGP knowledge base, which provides the material +for the skill. +[Using the Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) shows +how to point your agent at it. -```rust -#[cgp_fn] -#[extend_where(Scalar: Clone)] -fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar -where - Scalar: Mul, -{ - width * height -} -``` +## What is published here -would produce the following trait definition: +The skill pages on this site reproduce one revision of the repository without changes. Because +the repository may already have a newer version, install the skill from there as described on the +installation page. If you find a mistake in a skill, report it in the repository too. Each skill +has its own directory in this section, so more skills can be added alongside `/cgp` later. -```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. - -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. - -`#[use_type]` can also be used in both `#[cgp_impl]` and `#[cgp_component]` to import abstract types in the same way. For example: - -```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, - } -} -``` - -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. - -## Modularity Hierarchy - -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. - -## Debugging Techniques - -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. - -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. - -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()`. +*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/ai/skills/installation.md b/docs/ai/skills/installation.md new file mode 100644 index 00000000..fa6572fd --- /dev/null +++ b/docs/ai/skills/installation.md @@ -0,0 +1,210 @@ +--- +title: Installing the CGP Skill +description: How to install and update the /cgp agent skill in Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, OpenCode, Pi, or another agent, from the main branch that supports cgp v0.8.0 and later. +sidebar_label: Installation +sidebar_position: 2 +--- + +# Installing the CGP Skill + +The `/cgp` skill teaches a coding agent to read, write, and debug +[Context-Generic Programming (CGP)](/docs/) code, and this page shows how to install it in the agent +you use. The skill consists of Markdown files, with no scripts to run, so installing it means +putting those files where your agent looks for skills. + +Every installation method below uses the `main` branch of the +[cgp-skills repository](https://github.com/contextgeneric/cgp-skills). That branch supports `cgp` +v0.8.0 and later, but not older releases. The skill keeps improving between releases, so +[update it from time to time](#updating-the-skill). + +## Ask your agent to install it + +Your agent already knows where it keeps its skills, so the simplest way to install the skill is to +ask it. Give it the repository's URL and a request such as this one: + +```text +Install the /cgp agent skill from +https://github.com/contextgeneric/cgp-skills, +following the installation steps in the repository's README. +Ask me first whether to install it for me in every project +or only in this project. +``` + +The repository's README gives the agent installation steps. Following those steps, the agent asks +you where the skill should be available, then uses its own installer if there is one. Otherwise, it +copies the skill into its skills directory. + +Some agents, including Claude Code and Codex, protect their skills folders, so expect to approve the +step that copies the skill there. Review that command, and any others the agent proposes, before it +runs them. After installation, [check that the skill loaded](#checking-that-it-loaded). + +## Installing it yourself + +If you would rather run the commands yourself, find your agent below. Each section describes its +installer, if it has one, and the directories you can copy the skill into. The first directory makes +the skill available to you in every project; the second limits it to a single project. See +[Copying the skill by hand](#copying-the-skill-by-hand) for the copy commands. + +Choose one installation method per agent. Installing both a plugin and a separate copy gives the +agent two copies of the skill. + +### Claude Code + +Claude Code installs the skill as a plugin from the repository, which serves as its own +marketplace. Run these commands inside Claude Code: + +```text +/plugin marketplace add contextgeneric/cgp-skills +/plugin install cgp@cgp-skills +``` + +A plugin's skills carry the plugin's name, so you invoke this one as `/cgp:cgp`. A copy in +`~/.claude/skills/cgp`, or `.claude/skills/cgp` in a project, is invoked as `/cgp` instead. + +### Codex + +Codex reads the same marketplace. Run these commands in a terminal: + +```sh +codex plugin marketplace add contextgeneric/cgp-skills +codex plugin add cgp@cgp-skills +``` + +Codex then lists the skill as `cgp:cgp`. Its built-in `$skill-installer` can also install +`https://github.com/contextgeneric/cgp-skills/tree/main/cgp` when you ask it to. A copy goes in +`~/.agents/skills/cgp`, or `.agents/skills/cgp` in a project, where Codex lists it as `cgp`. + +### Cursor + +Cursor reads skills from folders, so copy the skill into `~/.cursor/skills/cgp`. Cursor syncs this +folder to its Cloud Agents when you turn on *Sync Skills for Cloud Agents*. For a single project, +copy the skill into `.cursor/skills/cgp` and commit it. Cursor's automations also load skills from +that project folder. The installers in [Any other agent](#any-other-agent) can place the skill for +you with `-a cursor` or `--agent cursor`. + +### GitHub Copilot and VS Code + +The GitHub CLI installs the skill for Copilot: + +```sh +gh skill install contextgeneric/cgp-skills cgp --agent github-copilot --scope user +``` + +Without `--scope user`, it installs into the current project. To copy the skill instead, use +`~/.copilot/skills/cgp`, or `.github/skills/cgp` in a project. + +### Gemini CLI + +Gemini CLI installs a skill from a directory in a Git repository: + +```sh +gemini skills install https://github.com/contextgeneric/cgp-skills.git --path cgp +``` + +This command uses the repository's default branch, `main`. To copy the skill instead, use +`~/.gemini/skills/cgp`, or `.gemini/skills/cgp` in a project. + +### OpenCode + +OpenCode reads skills from folders. Copy the skill into `~/.config/opencode/skills/cgp`, or +`.opencode/skills/cgp` in a project. + +### Pi + +Pi installs the repository as a package: + +```sh +pi install git:github.com/contextgeneric/cgp-skills +``` + +Add `-l` to install it for the current project only. Pi also reads skills copied into +`~/.agents/skills/cgp`, or `.agents/skills/cgp` in a project. + +### Any other agent + +If your agent supports skills, the `skills` tool or the GitHub CLI can usually install this one for +you. To use the `skills` tool, run it through `npx`: + +```sh +npx skills add contextgeneric/cgp-skills --skill cgp +``` + +This installs into the current project unless you add `-g`; use `-a` to name the agent. The tool +sends anonymous usage data unless you set `DISABLE_TELEMETRY=1`. + +You can also use the GitHub CLI with `gh skill install contextgeneric/cgp-skills cgp`, choosing the +agent with `--agent`. If neither installer recognizes your agent, copy the skill into +`~/.agents/skills/cgp`, a folder that many agents read. + +## Copying the skill by hand + +Every agent listed above can load a copy of the skill. Clone the repository, then copy the `cgp/` +directory to the path listed for your agent. For example, these commands install it for your use in +every Claude Code project: + +```sh +git clone --depth 1 https://github.com/contextgeneric/cgp-skills.git +mkdir -p ~/.claude/skills +cp -R cgp-skills/cgp ~/.claude/skills/cgp +``` + +Keep `SKILL.md` and its `references/` directory together, because the skill links between them. +Copy the directory rather than linking to the clone: Codex finds the plugin manifest beside a linked +skill and names it `cgp:cgp`, while a copy is named `cgp` everywhere. Remove an older copy before +copying a new one, since `cp -R` puts the new directory inside an existing one. + +## Installing it for a team + +To give everyone on a project the same skill, copy it into the project's skills folder and commit +it. Codex, Cursor, and Pi read `.agents/skills/cgp`, while Claude Code reads `.claude/skills/cgp`. +Every collaborator and cloud agent that checks out the repository then gets the same copy, and +updates to the skill become commits like any other change. + +## Checking that it loaded + +Start a new session after installing, since most agents read their skills when a session begins. +Then ask the agent which skills it has, or open your agent's list of skills. It should name `cgp`, +or `cgp:cgp` for a plugin. A question about CGP code, such as what a `delegate_components!` entry +does, should then lead the agent to load the skill. The skill tells the agent to compare your +project's `cgp` version with the releases it describes, and to tell you when a newer `cgp` or a +newer skill is available. + +The skill teaches the agent, but it does not make the agent's code correct. Review what the agent +writes with it as you would any other change. + +## Updating the skill + +Fixes and better explanations reach `main` between `cgp` releases, so update the skill from time to +time and whenever your project moves to a newer `cgp`. To help you keep up with release changes, +the skill tells the agent to compare your project's `cgp` version with the releases it describes. +If your version is newer, the agent checks `main` and tells you when a newer skill is available. + +Use the update command for your installation method: + +- **Claude Code:** run `claude plugin marketplace update cgp-skills`, then + `claude plugin update cgp@cgp-skills`, and start a new session. To have it update by itself, open + `/plugin`, select `cgp-skills` in the **Marketplaces** tab, and choose **Enable auto-update**. + This setting is off for marketplaces outside Anthropic's own. +- **Codex:** run `codex plugin marketplace upgrade cgp-skills`, then + `codex plugin add cgp@cgp-skills`. +- **Gemini CLI:** it has no update command, so run `gemini skills uninstall cgp`, then install the + skill again. +- **Pi:** run `pi update --extensions`. A plain `pi update` updates only Pi itself. +- **`npx skills` and the GitHub CLI:** run `npx skills update cgp`, adding `-g` for an install in + every project, or `gh skill update cgp`. +- **A copy:** remove the old directory, then copy `cgp/` again from a fresh clone. + +## Agents without skill support + +If your agent cannot load skills, attach the skill's main file, +[SKILL.md](https://raw.githubusercontent.com/contextgeneric/cgp-skills/main/cgp/SKILL.md), to the +conversation. It introduces the core model and names the reference file for each kind of task. +As the agent needs those files, you can attach them from the +[references directory](https://github.com/contextgeneric/cgp-skills/tree/main/cgp/references). +You can also read the [skill's pages](/docs/ai/skills/cgp/SKILL) in your browser. They show the same +files as they stood when this site was last built. + +--- + +*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/ai/skills/references/_category_.json b/docs/ai/skills/references/_category_.json deleted file mode 100644 index 517c7c33..00000000 --- a/docs/ai/skills/references/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "References", - "link": { - "type": "generated-index" - } -} 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/comparisons/_category_.json b/docs/comparisons/_category_.json new file mode 100644 index 00000000..d4f22011 --- /dev/null +++ b/docs/comparisons/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Comparisons", + "position": 8, + "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..ba1a9f09 --- /dev/null +++ b/docs/comparisons/algebraic-effects.md @@ -0,0 +1,400 @@ +--- +sidebar_label: 'Algebraic effects' +sidebar_position: 6 +description: 'Compare Context-Generic Programming providers with algebraic effect handlers: shared operation interfaces, static selection, and the continuation boundary.' +--- + +# Algebraic effects and handlers + +[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 + +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**, 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](/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 | + +## The idea, briefly + +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 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. + +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: + +- **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 + +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 + +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` + +fun add-twice() : ask int + ask() + ask() + +fun main() : console () + with fun ask() 21 // install a handler that supplies 21 + println( add-twice() ) // 42 +``` + +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 + +fun choice-all(action : () -> a) : e list + with handler + return(x) [x] + ctl choice() resume(False) ++ resume(True) + action() +``` + +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 + +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 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. + +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 { + 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 +``` + +`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 + +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 represents an operation with a consumer trait and its implementation with a provider. +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 + +A component declares an operation independently of its implementation. A context then selects a +provider through wiring: + +```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` 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. + +### Context fields supply an environment value + +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] +pub fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") +} +``` + +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 constructs a value + +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)] +#[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 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; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + + @ErrorRaiserComponent.String: RaiseFrom, + } +} +``` + +`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. + +### Dependency checks verify the selected providers + +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! { + App { + LoaderComponent, + } +} +``` + +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 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; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} +``` + +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 related theoretical view: coeffects + +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 + +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/tooling/cargo-cgp/check) leads with the root cause for the classes it recognizes, +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. + +## 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 + +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 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. + +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. + +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 + +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 + +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` 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..077c8c6b --- /dev/null +++ b/docs/comparisons/capabilities.md @@ -0,0 +1,379 @@ +--- +sidebar_label: 'Capabilities' +sidebar_position: 11 +description: 'Distinguish capability models and compare their guarantees with Context-Generic Programming dependency checks and context fields.' +--- + +# Capabilities + +[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 + +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 capability-oriented code | In CGP | +| --- | --- | +| 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 | +| 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 + +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 + +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" + +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 + +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 { + // 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) +} + +// 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 +``` + +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. + +### 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 + +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 + +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") +``` + +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 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. + +### Providers declare requirements on a context + +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)] +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 } } +``` + +`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](/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 +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 + +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; + +#[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 } } +``` + +`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 + +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 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/tooling/cargo-cgp/check) leads with the root +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 + +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 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 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 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. + +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 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 + +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 + +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. + +- [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..0adc57c2 --- /dev/null +++ b/docs/comparisons/dependency-injection.md @@ -0,0 +1,290 @@ +--- +sidebar_label: 'Dependency injection' +sidebar_position: 8 +description: 'Compare Context-Generic Programming with Spring, Guice, Dagger, and plain Rust injection: dependency declarations, wiring, validation, and runtime values.' +--- + +# Dependency injection + +[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 + +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 | +| --- | --- | +| 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](/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 | + +## The idea, briefly + +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 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 +public class UserService { + // business logic lives here +} + +@Configuration +public class AppConfig { + @Bean + public StorageClient storageClient() { + return new S3StorageClient(/* ... */); + } +} +``` + +### Constructor, setter, and field injection + +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 +public class ProfilePictureService { + private final StorageClient storage; + private final UserRepository users; + + public ProfilePictureService(StorageClient storage, UserRepository users) { + this.storage = storage; + this.users = users; + } +} +``` + +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 modules explicitly bind interfaces to implementations. This module selects a storage client: + +```java +public class StorageModule extends AbstractModule { + @Override + protected void configure() { + bind(StorageClient.class).to(S3StorageClient.class); + } +} +``` + +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 traits and generics already support dependency injection. A service can receive any storage +value implementing its required interface: + +```rust +trait StorageClient { + fn fetch(&self, object_id: &str) -> Vec; +} + +struct ProfilePictureService { + storage: S, +} +``` + +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 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](/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 + +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)] +#[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)]` 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 selects implementations for an application + +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)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + GCloudApp { + StorageObjectFetcherComponent: FetchGCloudObject, + } +} +``` + +`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 validates the declared dependencies + +[`check_components!`](/docs/reference/macros/check_components) verifies that the selected provider's +transitive requirements are satisfied for a context: + +```rust +check_components! { + App { + StorageObjectFetcherComponent, + } +} +``` + +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 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/tooling/cargo-cgp/check) leads with the root cause for the classes it recognizes, +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. + +## Where a DI framework is the better choice + +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 + +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. + +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. + +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. + +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 + +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` 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. +- [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..eea18eeb --- /dev/null +++ b/docs/comparisons/dynamic-dispatch.md @@ -0,0 +1,323 @@ +--- +sidebar_label: 'Dynamic dispatch' +sidebar_position: 9 +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 + +[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 + +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 object-oriented code | In CGP | +| --- | --- | +| 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](/docs/reference/glossary#aggregate-provider) or namespace | +| Checking that a receiver supports an operation | Trait bounds and `check_components!` | + +## The idea, briefly + +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 + +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 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 + +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 + +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. + +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 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. + +### Provider code calls methods on a generic receiver + +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] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} +``` + +`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] +pub fn greet_implicitly(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") +} +``` + +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](/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. + +### 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](/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. + +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! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +// expands to the type-level table entry: +// impl DelegateComponent for Rectangle { +// type Delegate = RectangleArea; +// } +``` + +`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. + +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. + +### Delegation preserves the original context + +An [aggregate provider](/docs/concepts/aggregate-providers) groups wiring entries for reuse. +A context can delegate several components to the aggregate: + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} + +delegate_components! { + Rectangle { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents, + } +} +``` + +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 share bindings and leave paths for contexts 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. +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 + } +} +``` + +`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! { + new QuietDefaults: AppDefaults { + @app.GreeterComponent: GreetQuietly, + } +} + +delegate_components! { + AppB { + namespace QuietDefaults; + } +} +``` + +`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 +Rust's [coherence](/docs/reference/glossary#coherence) rules. + +## What each approach costs + +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/tooling/cargo-cgp/check) leads with the root cause for the classes it recognizes, +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. + +## Where runtime dispatch is the better choice + +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. + +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. + +## What to expect that differs + +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. + +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 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. + +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 + +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): + 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` 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. +- [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. +- [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. + +--- + +*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..4ddecd1e --- /dev/null +++ b/docs/comparisons/implicit-parameters.md @@ -0,0 +1,325 @@ +--- +sidebar_label: 'Implicit parameters' +sidebar_position: 5 +description: 'Compare Context-Generic Programming context fields and wiring with Scala contextual parameters, Haskell implicit parameters, and type-class selection.' +--- + +# Implicit parameters + +[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 + +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 | +| 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](/docs/reference/glossary#abstract-type) determined by the context | + +## The idea, briefly + +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 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) + +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 +``` + +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. +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]: + 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'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 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 #-} +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 `?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 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](/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. + +## How CGP expresses it + +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 read named context fields + +An `#[implicit]` parameter names a field that the implementation reads from its context: + +```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, +} +``` + +`rectangle_area()` obtains `width` and `height` from `self`, so callers omit both arguments. +`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 +[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 + throwError :: e -> m a +``` + +```rust +#[cgp_type] +#[prefix(@cgp.core.error in DefaultNamespace)] +pub trait HasErrorType { + type Error: Debug; +} +``` + +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](/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. + +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 make instance selection explicit + +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)] +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, + } +} +``` + +`AppA` encodes `Vec` as hexadecimal text; `AppB` copies its bytes. Both are environmental +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 +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 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/tooling/cargo-cgp/check) leads with the root cause for the classes it +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 + +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 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. + +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 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. + +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 + +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 + +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` 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 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. + +--- + +*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..7eb720f4 --- /dev/null +++ b/docs/comparisons/index.md @@ -0,0 +1,60 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Compare Context-Generic Programming with familiar programming models through vocabulary, examples, trade-offs, and limits.' +--- + +# Comparisons + +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 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 + +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 | +| --- | --- | +| 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 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. + +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 + +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. + +--- + +*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..7edffc5b --- /dev/null +++ b/docs/comparisons/ml-modules.md @@ -0,0 +1,351 @@ +--- +sidebar_label: 'ML modules' +sidebar_position: 4 +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 + +[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. This page assumes familiarity with +OCaml or Standard ML 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](/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: + +| In ML | In CGP | +| --- | --- | +| 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 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 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 + type t + val compare : t -> t -> int +end + +module StringCompare = struct + type t = string + let compare = String.compare +end +``` + +`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 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 + (* ... a set implementation using O.compare ... *) +end + +module StringSet = Make (StringCompare) +``` + +`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](/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 +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 + +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 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 + 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` 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). + +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. + +### 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 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 + +A component and its providers separate the interface from its named implementations: + +```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 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](/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](/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. + +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 lets generic code use a type that the context supplies: + +```rust +#[cgp_type] +#[prefix(@cgp.core.error in DefaultNamespace)] +pub trait HasErrorType { + type Error: Debug; +} +``` + +`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 composes behavior from another provider supplied as a type parameter: + +```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` 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!` records the assembly choices + +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; + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + ErrorTypeProviderComponent: UseType, + // ... further components, in any order + } +} +``` + +`App` is an **[environmental context](/docs/reference/glossary#environmental-context)** representing the application. Its `storage_client` and `bucket_id` fields supply +the runtime data used by `FetchS3Object`, 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 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/tooling/cargo-cgp/check) helps explain +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 +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 + +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 + +**Wiring order does not determine execution order.** Component entries select providers. Runtime +initialization and execution remain ordinary Rust code. + +**Type selection and representation hiding are separate.** An abstract-type component supplies an +associated type; Rust privacy determines which representation details clients can access. + +**Alternative implementations exist in both systems.** ML names structures, modular implicits uses +scope and type-directed resolution, and CGP records choices on a context. + +**Consumer traits remain ordinary Rust traits.** Code can implement them directly when provider +wiring would add no useful flexibility. + +## Where to go next + +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 + +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` 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* (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. + +--- + +*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..5f427a19 --- /dev/null +++ b/docs/comparisons/policy-based-design.md @@ -0,0 +1,426 @@ +--- +sidebar_label: 'Policy-based design' +sidebar_position: 2 +description: 'Compare Context-Generic Programming providers and wiring with C++ policy classes, host templates, CRTP, and concepts.' +--- + +# C++ policy-based design + +[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 + +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** 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](/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 | + +## The idea, briefly + +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 + +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 { + this->write(this->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(); +} +``` + +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 + +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. + +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 gives a base access to its derived object + +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 +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()"); } }; +``` + +`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. + +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. + +### 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 +concept Hashable = requires(T a) { + { std::hash{}(a) } -> std::convertible_to; +}; + +template +void f(T) {} +``` + +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 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 + +The greeting can declare its message and output interfaces separately, then implement each choice +as a provider: + +```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()); +} +``` + +`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; +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 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. + +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 + +A higher-order provider keeps policy choices local to a parameterized implementation. The greeting +can use the familiar `HelloWorld` shape: + +```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! +``` + +`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] +#[use_provider(W: Writer)] +#[use_provider(M: MessageProvider)] +pub fn hello(&self) { + W::write(self, M::message(self)) +} + +>::hello(&App); // Hello, World! +``` + +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. + +### Providers access the context without an inheritance cast + +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)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +`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](/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 +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 + +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/tooling/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 + +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](/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. + +## What to expect that differs + +**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. + +**The context owns runtime state.** A provider implements operations over that state; it does not +contribute base-class fields to the context. + +**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. + +**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 + +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 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` 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 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. + +--- + +*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..3e532d00 --- /dev/null +++ b/docs/comparisons/reflection.md @@ -0,0 +1,359 @@ +--- +sidebar_label: 'Reflection' +sidebar_position: 10 +description: "Compare Context-Generic Programming type-level shapes with runtime reflection, Zig comptime, and Rust compile-time reflection." +--- + +# Reflection and compile-time introspection + +[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 + +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: + +| 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](/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!` | +| Checking that an operation supports a field type | Trait bounds, verified when used or asserted with `check_components!` | + +## The idea, briefly + +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. +- **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 also processes shapes at compile time. Its shape is a type, rather than a compile-time value. + +### 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 +([`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 +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 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"); + +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("}"); +} +``` + +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 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. + +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)] +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 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://goals.rust-lang.org/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 +fragments form a field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde/tree/main) +'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). + +### 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: + +```rust +#[derive(HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +// generated: +// impl HasFields for Config { +// type Fields = Product![ +// Field, +// Field, +// ]; +// } +``` + +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. + +### Writing fields through trait recursion {#serializing-through-the-trait-system} + +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)] +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 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 { + 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() + } +} +``` + +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! { + App { + open ValueWriterComponent; + + @ValueWriterComponent.[String, u16]: WriteWithDebug, + @ValueWriterComponent.Config: WriteFields, + } +} + +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 +[`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`. + +### Against facet and the reflection MVP + +These approaches differ in how they represent and process a type's structure: + +| Approach | What the type's shape becomes | What processes it | +| --- | --- | --- | +| 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 | + +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. 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 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} + +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. + +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 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 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/tooling/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool 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 + +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 +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 + +CGP's structural interface differs from a reflection API in several ways: + +- **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 + +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 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), + [`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` 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://goals.rust-lang.org/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`, `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. + +--- + +*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..b67979be --- /dev/null +++ b/docs/comparisons/row-polymorphism.md @@ -0,0 +1,344 @@ +--- +sidebar_label: 'Row polymorphism' +sidebar_position: 7 +description: "Compare Context-Generic Programming field access, record building, and variant operations with PureScript rows and OCaml polymorphic variants." +--- + +# Row polymorphism, structural typing, and extensible data types + +[Context-Generic Programming](/docs/) gives Rust structs and enums selected forms of structural reuse +through derived field lists and trait bounds. 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 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 +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 | +| 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) | +| 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 + +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 + +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, with duplicates", 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` +``` + +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 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. 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: + +```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](/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)). + +### 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](/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} + +`#[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)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +// generated: +// type Fields = Product![ +// Field, +// Field, +// ]; +``` + +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] +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` +``` + +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. + +### 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 +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() + .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 +``` + +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. + +### 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. + +### 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 +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)] +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 +``` + +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. + +### Trait implementations supply the evidence {#providers-are-the-theorys-computational-evidence} + +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 + +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)). + +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)). +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)). + +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" +([the `purescript-eff` README](https://github.com/purescript-deprecated/purescript-eff#readme)), +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/tooling/cargo-cgp/check) leads with the root cause for the classes it +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 +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. + +## Where a row system is the better choice + +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 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 + +CGP expresses structural requirements within Rust's existing type system: + +- **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 + +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 compared with 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`. + +- [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), [the `purescript-eff` README](https://github.com/purescript-deprecated/purescript-eff#readme), 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..a4636019 --- /dev/null +++ b/docs/comparisons/rust-language-proposals.md @@ -0,0 +1,398 @@ +--- +sidebar_label: "Rust's own proposals" +sidebar_position: 1 +description: 'Compare Context-Generic Programming with Rust proposals for specialization, named implementations, dictionary passing, and contexts and capabilities.' +--- + +# Rust's own proposals + +[Context-Generic Programming](/docs/) offers explicit implementation selection and access to +context values. 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 those choices with specialization, named impls, dictionary passing, and +contexts and capabilities, including what each language proposal can express beyond CGP. + +## In your terms + +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: + +| 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](/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 + +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)). + +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`: + +```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 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`. + +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 + +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 { + clone: fn(&Self) -> Self, +} + +const CLONE_U32: Clone = Clone { clone: |x: &u32| *x }; +``` + +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: + +```rust +impl Name = Trait for T { /* ... */ } + +function:: + OtherTraitImpl>(/* ... */) +``` + +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 + +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> +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 proposal's distinctive feature is a *context-dependent trait impl*, which is valid only while a +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)). + +### Cairo: a Rust-like language that shipped named impls + +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 +fn largest_list>(l1: Array, l2: Array) -> Array { /* ... */ } + +fn smallest_element, +Copy, +Drop>(list: @Array) -> T { /* ... */ } +``` + +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. + +## How CGP expresses it + +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. + +### 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 +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` 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). + +### 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 +applications can choose 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, + } +} +``` + +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 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 +`impl TDrop: Drop` written 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 + } +} +``` + +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 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)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +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)] +pub struct App { + pub name: String, +} + +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} + +let app = App { name: "World".to_owned() }; +app.greet(); // "Hello, World!" +``` + +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 + +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. + +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 +([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 +([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/tooling/cargo-cgp/check) leads with the root +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 + +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 +through explicit wiring. + +## What to expect that differs + +CGP's explicit context introduces limits that the proposals address differently: + +- **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 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 + +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 `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 + 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` 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..d46614b6 --- /dev/null +++ b/docs/comparisons/type-classes.md @@ -0,0 +1,385 @@ +--- +sidebar_label: 'Type classes' +sidebar_position: 3 +description: 'Compare Context-Generic Programming provider selection with type classes, coherence, and overlapping instances in Haskell, Agda, and Lean.' +--- + +# Type classes + +[Context-Generic Programming](/docs/) lets each context select named implementations 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 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 + +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: + +| In a type-class language | In CGP | +| --- | --- | +| 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 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 | + +## The idea, briefly + +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 +import Prelude hiding (Show, show) + +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 +``` + +The import hides the Prelude's `Show` so the snippet can define its own class. 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 +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 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 permits some overlapping instances when one is more specific than another. Per-instance pragmas +control which overlaps are allowed: + +```haskell +{-# LANGUAGE FlexibleInstances #-} +import Prelude hiding (Show, show) +import Data.List (intercalate) + +class Show a where + show :: a -> String + +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 +``` + +The snippet declares a local `Show` class so its instances do not collide with the Prelude's. 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 + +`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)): + +```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. 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 with a backtracking, tabled search that respects 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" +``` + +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 + +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 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:** 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:** 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. + +### Components define interfaces; providers name implementations {#a-component-is-a-class-a-provider-is-a-first-class-instance} + +A component declares the interface callers use and generates a provider trait for implementations: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +`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)] +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 } } +``` + +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. + +### Providers can accept overlapping sets of types {#overlapping-providers-need-no-specificity-rule} + +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)] +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() + } +} +``` + +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). + +### Selecting a provider per context and value type {#incoherent-choices-made-explicit-and-local} + +Separate application contexts can select different providers for the same value type: + +```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, + } +} +``` + +`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 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 + +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/tooling/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool 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 +already provides that guarantee. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) +page starts from this simpler case. + +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 + +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 + +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 + 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` 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/_category_.json b/docs/concepts/_category_.json new file mode 100644 index 00000000..d2f73f5f --- /dev/null +++ b/docs/concepts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Concepts", + "position": 5, + "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..e7eb3535 --- /dev/null +++ b/docs/concepts/abstract-types.md @@ -0,0 +1,208 @@ +--- +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.' +--- + +# Abstract types + +[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. + +This page starts from Rust's associated types, shows how wiring selects one and how providers share +it, and ends with what an abstract type does not hide. + +## Rust already has this + +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 { + type Scalar: Copy; +} + +impl HasScalarType for HighPrecision { + type Scalar = f64; +} + +impl HasScalarType for Embedded { + type Scalar = f32; +} +``` + +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. + +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, whereas an associated type gives all providers working with `HighPrecision` the +same choice. + +## Choosing the type by wiring + +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] +pub trait HasScalarType { + type Scalar: Copy; +} +``` + +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! { + HighPrecision { + ScalarTypeProviderComponent: UseType, + } +} + +delegate_components! { + Embedded { + ScalarTypeProviderComponent: UseType, + } +} +``` + +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 compute the type from further type information, though a fixed choice needs +nothing more than `UseType`. + +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 + +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)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCalculateShapeArea { + fn shape_area(&self, shape: &Shape) -> Scalar; +} +``` + +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. + +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. + +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 + +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 +must expose enough information to name it, as `CanCalculateShapeArea` does above. +[Impl-side dependencies](./impl-side-dependencies.md) explains that distinction. + +## 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)] +#[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}")) + } +} +``` + +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. +[Modular error handling](./modular-error-handling.md) develops this example further. + +## The provider and the import attribute {#two-things-called-usetype} + +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 + +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. + +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. + +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 +that the required type is available and satisfies its bounds. + +## Where to go next + +These pages explain related dependencies and the constructs used here: + +- [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. +- [Comparison: ML modules](/docs/comparisons/ml-modules): Abstract-type components beside a signature's abstract `type t`, and the sealing CGP does not provide. +- [Comparison: Implicit parameters](/docs/comparisons/implicit-parameters): An abstract type as a functional dependency, a type the context determines. + +--- + +*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 new file mode 100644 index 00000000..a4fd424a --- /dev/null +++ b/docs/concepts/aggregate-providers.md @@ -0,0 +1,170 @@ +--- +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.' +--- + +# Aggregate providers + +[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. + +This page defines a bundle, traces a call through it, explains why a bundle is checked through a +context that uses it, and compares it with a namespace. + +## A table whose target is not a context + +`delegate_components!` can give a wiring table to a provider type. The `new` keyword declares that +type alongside its table: + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} +``` + +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: + +```rust +delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: GeometryComponents, + } +} +``` + +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` to share +those choices, and editing the bundle then changes both contexts together. + +## The context stays the context + +Delegation through a bundle preserves the original context. The compiler resolves +`rectangle.area()` through this chain: + +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 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. + +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 + +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. + +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. + +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 + +A check on `Rectangle` follows the bundle's delegation and checks the providers against +`Rectangle`'s fields and traits: + +```rust +check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } +} +``` + +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: + +```rust +check_components! { + #[check_providers( + RectangleArea, + GeometryComponents, + )] + Rectangle { + AreaCalculatorComponent, + } +} +``` + +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 + +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. + +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. + +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 + +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. + +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, and +reuse that is only anticipated may not be enough to justify 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 + +These pages explain related wiring choices and checks: + +- [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. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): Delegation through a bundle, with `self` still bound to the context. + +--- + +*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 new file mode 100644 index 00000000..1be62894 --- /dev/null +++ b/docs/concepts/check-traits.md @@ -0,0 +1,245 @@ +--- +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.' +--- + +# Checking your wiring + +[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. + +This page follows one broken context from the unchecked error, through an explicit check, to the +toolchain's output, then covers checks on provider layers and what a check does not prove. + +## A context can be wrong and still compile + +Consider a provider that reads stored objects from the folder in a `local_dir` field. A context's +wiring can still select that provider when the context has only a `bucket_id` field, as this +example shows. The fragment imports CGP's prelude and defines both the `StorageObjectFetcher` +component and the local provider: + +```rust +use cgp::prelude::*; + +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } +} + +#[derive(HasField)] +pub struct BrokenApp { + pub bucket_id: String, +} + +delegate_components! { + BrokenApp { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +This table establishes which provider `BrokenApp` selects without proving that it can use that +provider. That proof would need the `local_dir` field read by `FetchLocalObject`'s implicit +argument, and because this fragment never asks for `CanFetchStorageObject` on `BrokenApp`, the +missing field has not yet caused a compilation failure. + +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 + +An unchecked wiring error appears when code first requires the trait. A call to +`app.fetch_storage_object(object_id)` on a `BrokenApp` value produces an error like this abbreviated +diagnostic: + +```text +error[E0599]: the method `fetch_storage_object` exists for struct `BrokenApp`, + but its trait bounds were not satisfied + | + | pub struct BrokenApp { + | -------------------- method `fetch_storage_object` not found for this struct + | because it doesn't satisfy `BrokenApp: CanFetchStorageObject` + | or `BrokenApp: StorageObjectFetcher` + | +note: trait bound `BrokenApp: StorageObjectFetcher` was not satisfied +``` + +The diagnostic stops at the unsatisfied trait implementations: `BrokenApp` lacks +`CanFetchStorageObject` and `StorageObjectFetcher`. It leaves the missing `local_dir` +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 + +A check trait forces the compiler to verify a bound where you write its implementation. The basic +technique uses an ordinary Rust [supertrait](/docs/reference/glossary#supertrait) and an empty +implementation. Here it checks a working `App`, whose `local_dir` field satisfies the provider: + +```rust +trait CanUseApp: CanFetchStorageObject {} +impl CanUseApp for App {} +``` + +For Rust to accept the empty implementation, it must establish `App: CanFetchStorageObject` at that +line. Putting it beside the wiring moves any failure there, but the requirement still goes through +the consumer trait, so its diagnostic can remain as vague as the method-call error. + +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! { + BrokenApp { + StorageObjectFetcherComponent, + } +} +``` + +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` + is not satisfied + | +help: the trait `HasField>>>>` + is not implemented for `BrokenApp` + but trait `HasField>>>>` + is implemented for it + | +note: required for `FetchLocalObject` to implement + `IsProviderFor` +``` + +Following this checking path exposes `FetchLocalObject`'s requirement for a `HasField` +implementation. The cause is closer to the surface, but the field tags still appear as nested +character types, leaving `local_dir` and `bucket_id` difficult to recognize. The headline also +refers to the generated `CanUseComponent` bound rather than the public trait. + +## Reading it through the toolchain + +[`cargo cgp check`](/docs/tooling/cargo-cgp/check) rewrites recognized CGP diagnostics +with readable field names and dependency chains. For this missing-field case, its abbreviated output +identifies both the unavailable trait and its cause: + +```text +error[E0277]: [CGP-E001] missing field `local_dir` on `BrokenApp` + | + = note: root cause: [CGP-E110] missing field `local_dir` on `BrokenApp` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanFetchStorageObject` for context `BrokenApp` + └─ [CGP-E102] provider trait impl `StorageObjectFetcher` with context `BrokenApp` + for provider `FetchLocalObject` + └─ [CGP-E110] missing field `local_dir` on `BrokenApp` +``` + +Here the dependency chain connects the application's need for `CanFetchStorageObject` to the +provider it selected and then to the missing `local_dir` field, so the reader sees 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. +`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/tooling/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 + +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! { + #[check_providers( + RectangleArea, + ScaledArea, + )] + App { + AreaCalculatorComponent, + } +} +``` + +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 + +Placing checks beside each context's wiring catches missing entries and dependencies before a caller +happens to need them, and for basic `Component: Provider` entries the checks can even 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 +`#[check_params(...)]` attribute supplies parameter sets to check. Keeping the assertion beside the +entry helps prevent the two from drifting apart. + +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. + +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 + +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 provider reads the right file; that +behavior still needs tests. + +## Where to go next + +These pages explain the dependencies being checked and the available check forms: + +- [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. +- [Comparison: Dependency injection](/docs/comparisons/dependency-injection): `check_components!` beside a container's startup validation and Dagger's build-time check. + +--- + +*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 new file mode 100644 index 00000000..3cd37e01 --- /dev/null +++ b/docs/concepts/coherence.md @@ -0,0 +1,268 @@ +--- +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, 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 its own provider type, from which a context selects one through wiring. + +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 + +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)` supplies the value, while the compiler finds the `Display` implementation +for `i32`. The caller never names or passes that implementation, so ordinary Rust already offers a +form of dependency injection. + +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); + +impl Display for Pair { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "({}, {})", self.0, self.1) + } +} +``` + +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 its callers keep their existing bounds, provided the concrete types still satisfy +the full chain. + +## That only works because every lookup finds the same answer + +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 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 { + 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() } +} +``` + +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 would have no way to choose between them, so the +compiler rejects the pair. + +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 +// for types defined outside of the crate +impl Display for Vec { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { /* ... */ } +} +``` + +A local type among a trait's parameters can allow further implementations, in cases the [Rust +Reference](https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules) specifies. +Together, the orphan and overlap rules keep trait resolution consistent as crates are combined into +a program. + +## What the guarantee costs + +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. Even an author who knows which behavior each type should +get has no way to record those choices in the trait. + +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. In exchange, callers must use the wrapper, and operations on the underlying value may need +forwarding methods or trait implementations. + +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 + +The interface callers use can stay `CanEncode`, which CGP calls the **consumer trait**: + +```rust +use cgp::prelude::*; + +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self) -> Vec; +} +``` + +The `#[cgp_component]` macro also generates a **provider trait**, `Encoder`. Because the +value's type moves into the `Context` parameter, the implementing type is free for a provider +struct, and a separate struct for each implementation lets the original `Display` and `AsRef<[u8]>` +bounds describe two providers. The byte-based provider here encodes as hexadecimal, so the two +outputs differ visibly: + +```rust +#[cgp_impl(new EncodeAsText)] +#[uses(Display)] +impl Encoder { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +#[cgp_impl(new EncodeAsHex)] +#[uses(AsRef<[u8]>)] +impl Encoder { + fn encode(&self) -> Vec { + self.as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } +} +``` + +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. + +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. + +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 +let value = String::from("hi"); + +assert_eq!(>::encode(&value), b"hi"); +assert_eq!(>::encode(&value), b"6869"); +``` + +The provider struct also gives its crate a local implementing type, so the crate can supply a +provider even when both the trait and the 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. + +## Selecting one provider for each type {#coherence-comes-back-one-type-at-a-time} + +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: + +```rust +delegate_components! { String { EncoderComponent: EncodeAsText } } +delegate_components! { Vec { EncoderComponent: EncodeAsHex } } +``` + +Rust's rule still holds, but the choice now lives in the wiring: coherence is scoped to each +provider type, and each value type names one of them. + +![Diagram: both blanket impls match String, so Rust rejects the second with E0119. 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()` +encodes as `b"6869"`. Callers can use the `CanEncode` consumer trait and leave provider selection +to the 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. + +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. + +## What it costs + +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 has to be read and maintained, since every wired type needs an entry naming +its provider. Shared bundles and namespaces can reduce that repetition, but tracing a choice then +means following it through their 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/tooling/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. + +These choices also apply only 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 + +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. +- [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. +- [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. + +--- + +*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 new file mode 100644 index 00000000..cbb48793 --- /dev/null +++ b/docs/concepts/consumer-and-provider-traits.md @@ -0,0 +1,361 @@ +--- +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.' +--- + +# Consumer and provider traits + +[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. + +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 lets different types expose the same method with different behavior. +For example, a production application may fetch stored objects from Amazon S3, while a test +application reads them from a local folder. Each type can implement `CanFetchStorageObject`, +giving callers a shared interface: + +```rust +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, +} + +pub struct TestApp { + pub local_dir: String, +} + +impl CanFetchStorageObject for App { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + // fetch `object_id` from `self.bucket_id` through `self.storage_client` + } +} + +impl CanFetchStorageObject for TestApp { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(std::fs::read(format!("{}/{object_id}", self.local_dir))?) + } +} +``` + +Here, `App` and `TestApp` are the contexts on which `fetch_storage_object` operates. Each represents +an application and carries the data its implementation needs: an S3 client and a bucket for `App`, +and a folder for `TestApp`. The S3 request is omitted, while the test implementation reads the +object from a file in its folder. To keep the example short, the method is synchronous, although a +real storage client would be async, as +[Swap a Storage Backend per Application](/docs/tutorials/storage-backend) shows. + +To share each behavior with other application types, it might seem natural to write a +[blanket implementation](/docs/reference/glossary#blanket-implementation). The S3 implementation +could work for any type that has an S3 client, expressed as a `HasS3Client` bound, and the local +implementation for any type that names a folder, through `HasLocalDir`. Offering both, however, +creates a conflict: + +```rust +impl CanFetchStorageObject for T { /* ... */ } +impl CanFetchStorageObject for T { /* ... */ } // error[E0119] +``` + +A type could satisfy both bounds, which would leave Rust with two implementations of +`CanFetchStorageObject` for that type, so the compiler 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 + +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, +which the call trace explains later: + +```rust +// what callers use +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +// what implementations target +pub trait StorageObjectFetcher { + fn fetch_storage_object( + context: &Context, + object_id: &str, + ) -> anyhow::Result>; +} +``` + +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 a call through the consumer trait goes through the context's wiring, which 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: + +```rust +pub struct FetchS3Object; +pub struct FetchLocalObject; + +impl StorageObjectFetcher for FetchS3Object { + /* ... */ +} + +impl StorageObjectFetcher for FetchLocalObject { + /* ... */ +} +``` + +Even if a context satisfies both `HasS3Client` and `HasLocalDir`, 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. + +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 + +The structs `FetchS3Object` and `FetchLocalObject` serve only as names for implementations. They are +zero-sized, and CGP neither constructs values of them nor stores application data in them. Instead, +that data stays in the context, while explicit method arguments supply inputs such as the object's +ID. + +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 + +With the behaviors defined, each application needs to choose which provider supplies its +`fetch_storage_object` method. Wiring records that choice in a table of types that the compiler +resolves: + +```rust +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +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 StorageObjectFetcherComponent to FetchS3Object, and TestApp maps it to FetchLocalObject. 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 `StorageObjectFetcherComponent`, a marker generated alongside the two +traits. Those traits, the marker, and the forwarding implementations form the **component**. The +entry for this key selects `FetchS3Object` on `App` and `FetchLocalObject` on `TestApp`. + +When a caller writes `app.fetch_storage_object("alice.png")`, the compiler follows `App`'s selection +to `FetchS3Object` and checks whether that provider can work with `App`. Because this is static +dispatch, the running program needs neither a wiring table nor a provider lookup. + +To see how method syntax reaches that selection, consider the two generated blanket +implementations. The consumer implementation supplies `CanFetchStorageObject` whenever the context +implements `StorageObjectFetcher` for itself: + +```rust +impl CanFetchStorageObject for Context +where + Context: StorageObjectFetcher, +{ + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Context::fetch_storage_object(self, object_id) + } +} +``` + +Satisfying `Context: StorageObjectFetcher` leads 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 StorageObjectFetcher for Provider +where + Provider: DelegateComponent + + IsProviderFor, + Provider::Delegate: StorageObjectFetcher, +{ + fn fetch_storage_object( + context: &Context, + object_id: &str, + ) -> anyhow::Result> { + Provider::Delegate::fetch_storage_object(context, object_id) + } +} +``` + +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 +`FetchS3Object`. As long as `FetchS3Object` implements `StorageObjectFetcher`, the delegation +gives `App` its own `StorageObjectFetcher` implementation, which in turn supplies +`CanFetchStorageObject` 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 `StorageObjectFetcher` 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/tooling/cargo-cgp/expand). + +## Writing it + +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 storage example, that gives: + +```rust +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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // fetch `object_id` from `bucket_id` through `storage_client` + } +} + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } +} + +#[derive(HasField)] +pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, +} + +#[derive(HasField)] +pub struct TestApp { + pub local_dir: String, +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +Each `#[implicit]` argument reads a same-named field exposed by the context's `HasField` derive. +The macro turns it into a local binding and removes it from the public signature, so callers still +write `app.fetch_storage_object(object_id)`. The S3 request is still a placeholder, while the local +provider reads the object from a file in the test application's folder. + +The fields differ between providers: `FetchS3Object` needs `storage_client` and `bucket_id`, while +`FetchLocalObject` needs `local_dir`. Because these are +[impl-side dependencies](./impl-side-dependencies.md), neither requirement appears in +`CanFetchStorageObject`. A caller can therefore use the selected behavior with that trait bound +alone: + +```rust +pub fn fetch_profile_picture( + app: &impl CanFetchStorageObject, + object_id: &str, +) -> anyhow::Result> { + app.fetch_storage_object(object_id) +} +``` + +The same `fetch_profile_picture` function accepts `App` as well as `TestApp`. Its bound names only +`CanFetchStorageObject`, so each application's wiring supplies the behavior without the function +knowing the provider or its fields. + +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 + +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. + +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/tooling/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. + +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 `fetch_profile_picture` keeps the same interface. + +## Where to go next + +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 + 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. +- [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. + +--- + +*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 new file mode 100644 index 00000000..eccfaf26 --- /dev/null +++ b/docs/concepts/dispatching.md @@ -0,0 +1,162 @@ +--- +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.' +--- + +# Dispatching + +[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 +the computations that build a record or handle the current variant. This page covers both +directions, matching variants and building records, then the shortcut that forwards a trait from an +enum to its payloads. + +## Two directions, one idea + +The data traits describe how to extract a variant or set a field, but to do useful work with those +operations, a dispatcher also needs handlers: one can process an extracted payload, while another +can produce a value for a field. + +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. + +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 + +A matcher selects the handler for an enum's current variant. For a `Shape` enum deriving `CgpData` +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 { + open ComputerComponent; + + @ComputerComponent. Code.Shape: MatchWithValueHandlers, + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, + } +} +``` + +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`. + +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. + +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. + +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 + +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. + +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. + +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 +must respect any dependencies on fields produced by earlier steps. + +## The shortcut for the common case + +`#[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] +pub trait CanDescribe { + fn describe(&self) -> String; +} +``` + +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 +point when forwarding to payload methods is all the operation needs. + +## What it costs + +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. + +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. + +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 +written providers need to contribute parts of an operation. + +## Where to go next + +These pages explain the data operations and computation interfaces behind dispatch: + +- [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. + +--- + +*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 new file mode 100644 index 00000000..88249f60 --- /dev/null +++ b/docs/concepts/extensible-records.md @@ -0,0 +1,178 @@ +--- +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.' +--- + +# Extensible records + +[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. + +This page starts from a struct literal, shows the field list a derive exposes, and follows a +builder that merges records into a target the compiler checks. + +## What a closed struct cannot do + +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 { + database: connect_to_database()?, + http_client: build_http_client()?, + metrics: start_metrics()?, + // …and every future subsystem edits this same expression +}; +``` + +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. + +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 + +[`#[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)] +pub struct DatabaseClient { + pub url: String, + pub pool_size: u32, +} +``` + +The generated `HasFields::Fields` associated type describes the struct as a product of named fields: + +```rust +Product![Field, Field] +``` + +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. + +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. + +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 + +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() + .build_from(database) + .build_from(http) + .finalize_build(); +``` + +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. + +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 +incomplete: + +```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(); +``` + +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. + +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 + +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. + +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 +form for assembling a target from provider outputs. + +## What it costs + +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. + +Because the compiler checks only names and types, 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. + +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. + +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 +applications reuse independently written subsystem providers. + +## Where to go next + +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. +- [Comparison: Row polymorphism](/docs/comparisons/row-polymorphism): Records as rows, with containment, concatenation, and presence flags. +- [Comparison: Reflection](/docs/comparisons/reflection): A derived shape beside runtime and compile-time reflection descriptors. + +--- + +*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 new file mode 100644 index 00000000..3db5cafa --- /dev/null +++ b/docs/concepts/extensible-variants.md @@ -0,0 +1,192 @@ +--- +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.' +--- + +# Extensible variants + +[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 +apart and proves that it has handled every possibility. This page follows that difference from the +variant list a derive exposes, through extraction that proves coverage, to handlers shared across +enums and casts between them. + +## The problem a `match` builds in + +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. + +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's generic dispatcher separates those helpers from the enum-specific connection. 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 + +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) exposes an enum's structure and +provides generic construction and extraction operations: + +```rust +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +For `Shape`, the generated `HasFields::Fields` associated type is a sum of named payloads: + +```rust +Sum![Field, Field] +``` + +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. + +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. + +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 + +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. + +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. + +To finish extraction, the remainder must be uninhabited, and the compiler checks coverage through +this requirement: 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 + +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] +pub fn field_to_string(Field { value, .. }: Field) -> String +where + Value: Display, +{ + value.to_string() +} + +delegate_components! { + App { + ComputerComponent: MatchWithFieldHandlers, + } +} +``` + +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 +current variant to its handler. [Dispatching](./dispatching.md) explains how the context selects them. + +## Converting enums that share variants {#enums-that-share-variants-convert-for-free} + +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: + +```rust +let wide: ExtendedReading = narrow.upcast(PhantomData::); +``` + +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::); +``` + +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 +complete result type. + +## What it costs + +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. + +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 +read than an ordinary non-exhaustive `match` error. + +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 + +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. +- [Comparison: Row polymorphism](/docs/comparisons/row-polymorphism): Variants as row-typed sums, with injection, branching, and the expression problem. + +--- + +*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 new file mode 100644 index 00000000..3a616d75 --- /dev/null +++ b/docs/concepts/handlers.md @@ -0,0 +1,213 @@ +--- +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.' +--- + +# Handlers + +[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 +its work calls for. + +This page explains the handler interface and its forms, how promotion lets one provider serve +several of them, and how wiring builds pipelines and selects computations by tag. + +## Computation as something a context decides + +An application-specific component gives a name to an operation, such as `fetch_storage_object` or +`get_user`. A handler gives it a uniform computation interface instead, allowing generic combinators +to connect it to other computations. + +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 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. + +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 + +The main input-taking components vary by execution and error handling. Their consumer traits give +callers the corresponding methods: + +| 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` | + +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 +whether the computation consumes or borrows its argument. + +[`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 simplest suitable provider {#write-the-weakest-one-the-rest-come-free} + +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: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +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] +fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) +} +``` + +`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. + +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 +provider needs explicit adapters when another interface is required. + +## A pipeline is a wiring entry + +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! { + App { + ComputerComponent: PipeHandlers< + Product![ + Multiply, + Add, + Multiply, + ] + >, + } +} +``` + +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`. + +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. + +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 + +Different `Code` tags let the same context select different computations for the same input type: + +```rust +delegate_components! { + App { + open ComputerComponent; + + @ComputerComponent.Doubled.i64: ComputeDoubled, + @ComputerComponent.Negated.i64: ComputeNegated, + } +} +``` + +`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. + +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 + +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, though the extra syntax +remains. + +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. + +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 +[Recovering `Send` bounds](./send-bounds.md). + +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 traits from a context without handler wiring. + +## Where to go next + +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. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): The handler family beside effect handlers, and the continuation CGP never captures. + +--- + +*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 new file mode 100644 index 00000000..9378a14b --- /dev/null +++ b/docs/concepts/higher-order-providers.md @@ -0,0 +1,217 @@ +--- +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.' +--- + +# Higher-order providers + +[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. + +This page builds a scaling wrapper, shows the bound that names its inner provider, and covers +compositions named before any context uses them, the `UseContext` default, and what deeper +compositions cost. + +## Choosing is not the only thing you can do with a provider + +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)] +#[use_provider(Inner: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale: f64) -> f64 { + let base = Inner::area(self); + base * scale * scale + } +} +``` + +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: + +```rust +delegate_components! { ScaledRectangle { AreaCalculatorComponent: ScaledArea } } +delegate_components! { ScaledCircle { AreaCalculatorComponent: ScaledArea } } +``` + +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. + +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 + +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)] +impl AreaCalculator +where + Inner: AreaCalculator, +{ + fn area(&self, #[implicit] scale: f64) -> f64 { + Inner::area(self) * scale * scale + } +} +``` + +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. + +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 + +A type alias can name a provider composition before any context uses it: + +```rust +pub type ScaledScaledRectangleArea = ScaledArea>; +``` + +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. + +Naming the composition does not prove that a context can use it, and neither does a wiring entry +alone. That proof comes only at a use or an explicit check, and 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 + +[`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. + +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); + +#[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() + } +} +``` + +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! { + App { + open ShapeAreaCalculatorComponent; + + @ShapeAreaCalculatorComponent.Rectangle: RectangleArea, + @ShapeAreaCalculatorComponent. Vec: SumAreas, + } +} +``` + +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. + +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. + +To give the parameter its `UseContext` default, declare the provider struct explicitly, as above. +The `#[cgp_impl(SumAreas)]` block then implements that existing struct, because the `new` +form would declare a provider without the default. + +## Not every generic provider is one of these + +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)] +impl NameGetter +where + Self: HasField, +{ + fn name(&self) -> &str { + self.get_field(PhantomData::) + } +} +``` + +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 + +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. + +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 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. + +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 + +These pages explain related forms of composition and their checks: + +- [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. +- [Comparison: ML modules](/docs/comparisons/ml-modules): Higher-order providers as functors, with 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. + +--- + +*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 new file mode 100644 index 00000000..a4904e29 --- /dev/null +++ b/docs/concepts/impl-side-dependencies.md @@ -0,0 +1,314 @@ +--- +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.' +--- + +# Impl-side dependencies + +[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, +including why types used in public signatures must remain available through the interface. + +## What a `where` clause costs the callers above it + +For example, a generic greeting function can obtain a name through a `HasName` bound on the context: + +```rust +pub trait HasName { + fn name(&self) -> &str; +} + +pub fn greet(context: &Context) -> String +where + Context: HasName, +{ + format!("Hello, {}!", context.name()) +} +``` + +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 +where + Context: HasName, +{ + format!("{} {}", greet(context), greet(context)) +} +``` + +`greet_twice` needs `HasName` only because it calls `greet`; 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 trait instead lets the caller request the greeting operation itself, and its [blanket +implementation](/docs/reference/glossary#blanket-implementation) can supply that operation for +contexts that provide a name: + +```rust +pub trait CanGreet { + fn greet(&self) -> String; +} + +impl CanGreet for Context +where + Context: HasName, +{ + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} +``` + +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 +where + Context: CanGreet, +{ + format!("{} {}", context.greet(), context.greet()) +} +``` + +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 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. + +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 + +For object storage, the useful requirements depend on where the objects live. An S3 provider needs +a client and a bucket, while a local provider needs a folder. Each provider can request its own +getter trait without adding that requirement to the shared interface: + +```rust +use cgp::prelude::*; + +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchS3Object)] +#[uses(HasS3Bucket)] +impl StorageObjectFetcher { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + // fetch `object_id` from `self.bucket_id()` via `self.storage_client()` + } +} + +#[cgp_impl(new FetchLocalObject)] +#[uses(HasLocalDir)] +impl StorageObjectFetcher { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(std::fs::read(format!("{}/{object_id}", self.local_dir()))?) + } +} +``` + +Each `#[uses]` attribute adds a context bound to its provider's implementation. The bound +`HasS3Bucket` supplies `storage_client() -> &aws_sdk_s3::Client` and `bucket_id() -> &str`, while +`HasLocalDir` supplies `local_dir() -> &str`. The S3 request is omitted here, while the local body +reads the object from the folder that its getter returns. + +Those getter requirements stay with the providers, so a caller can use either behavior through +`CanFetchStorageObject` alone: + +```rust +pub fn load_picture(context: &Context) -> anyhow::Result> +where + Context: CanFetchStorageObject, +{ + context.fetch_storage_object("alice.png") +} +``` + +A production `App` can select `FetchS3Object`, while a `TestApp` selects `FetchLocalObject`. Each +context represents an application and supplies the dependencies of the provider it chose, so +`load_picture` accepts both with the same bound. Because the test context selects the local +provider, it needs only the folder and no S3 client. + +## Traits, values, and types {#the-three-things-an-implementation-can-ask-for} + +The storage providers ask the context for behavior through getter traits, but other implementations +may need a field value or a type choice instead. 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. A type used in a public signature also needs to be available through + the interface. + +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 { + format!("Hello, {name}!") + } +} +``` + +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. + +## Keeping type choices on the context {#type-dependencies-and-why-they-need-no-parameter} + +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> +where + E: From + From, + R: Runtime, + S: Store, +{ + /* job execution omitted */ +} +``` + +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. + +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)] +#[use_type(HasErrorType.Error)] +pub trait CanRunJob { + fn run_job(&self) -> Result<(), Error>; +} +``` + +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. + +An operation that forwards to `run_job` can share that associated error: + +```rust +#[cgp_fn] +#[uses(CanRunJob)] +#[use_type(HasErrorType.Error)] +pub fn run_jobs(&self) -> Result<(), Error> { + self.run_job()?; + self.run_job() +} +``` + +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. + +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 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. + +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. + +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/tooling/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. + +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 + +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. +- [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. +- [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". + +--- + +*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 new file mode 100644 index 00000000..a6cf2292 --- /dev/null +++ b/docs/concepts/implicit-arguments.md @@ -0,0 +1,182 @@ +--- +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.' +--- + +# Implicit arguments + +[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 + +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, with +`cgp::prelude::*` and `HasField` from `cgp::core::field::traits` imported: + +```rust +#[cgp_impl(new GreetByName)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) -> String { + let name = self.get_field(PhantomData::); + format!("Hello, {name}!") + } +} +``` + +`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. + +The explicit form states the requirement and the read separately. When a provider only needs the +value locally, an implicit argument can express both at once. + +## The same provider with an implicit argument + +An **implicit argument** names a field and declares the type the method body needs: + +```rust +#[cgp_impl(new GreetByName)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +`#[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 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 +`HasField` bound and tagged access. + +## A trait from a function alone + +[`#[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] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +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 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, + // Cloned from the context's String field. + #[implicit] name: String, + // Borrows any field implementing `AsRef`, such as a String field. + #[implicit] title: &str, + // Borrows the Vec field directly. + #[implicit] tags: &Vec, +) -> String { + format!("{title} {name} {tags:?}") +} +``` + +An owned argument calls `.clone()` on the field, leaving the stored value in the context. A `&str` +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 +access, and the other supported forms. + +## When a getter trait is useful + +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)] +impl RequestAuthenticator +where + Request: HasAuthHeader, +{ + fn authenticate(&self, request: &Request) -> bool { + request.auth_header().starts_with("Bearer ") + } +} +``` + +This fragment assumes `RequestAuthenticator` and `HasAuthHeader` are defined elsewhere. +`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](/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. + +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. + +## What it costs + +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. + +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. + +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 + +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. + +--- + +*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 new file mode 100644 index 00000000..f8b077be --- /dev/null +++ b/docs/concepts/index.md @@ -0,0 +1,97 @@ +--- +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.' +--- + +# Concepts + +[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, and familiarity with Rust +traits and generic bounds is enough to start. + +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 + +Choose an entry point for the question you want answered: + +- **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. + +If you would like more background on traits or generic bounds first, the +[tutorials](/docs/tutorials/hello) show them in working programs, and these explanations will still +be here when you return. + +## The ideas, grouped + +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 + +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. +- [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 + +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. +- [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 + +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. +- [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 + +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. +- [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. + +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 +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 new file mode 100644 index 00000000..24fd3209 --- /dev/null +++ b/docs/concepts/modular-error-handling.md @@ -0,0 +1,266 @@ +--- +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.' +--- + +# Modular error handling + +[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 +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 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 +place, reusable code asks the context to convert a source error into the shared type, and other code +can later ask it to attach detail, such as the path of a configuration file. + +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. + +The context selects providers for these components through wiring, which 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 + +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 +use cgp::prelude::*; +use core::num::ParseIntError; + +#[cgp_fn(CanParsePort)] +#[uses(CanRaiseError, CanRaiseError)] +#[use_type(HasErrorType.Error)] +pub 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) +} +``` + +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. + +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 + +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, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +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. + +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 + +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 { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + } +} +``` + +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. + +The parser itself has not changed: it raises the same source values through the same operations, +while 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 + +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: + +```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 + +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, and it then 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)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseHttpError { + fn raise_http_error(code: Code, detail: Detail) -> Error; +} +``` + +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 log in first") +``` + +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 + +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. + +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. + +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 + +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`](/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. + +--- + +*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 new file mode 100644 index 00000000..591ccbbe --- /dev/null +++ b/docs/concepts/modularity-hierarchy.md @@ -0,0 +1,398 @@ +--- +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 + +[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 +visible. The decision guide that follows compares those choices with ordinary Rust alternatives. + +## The tiers at a glance + +The tiers differ in where a program can select an implementation: + +| 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](/docs/reference/glossary#higher-order-provider) | The enclosing provider depends on the inner provider interface | + +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 + +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 +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +impl> CanEncode for Value { + fn encode(&self) -> Vec { + self.as_ref().to_vec() + } +} +``` + +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. + +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 + +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 { + 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() + } +} +``` + +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. + +## Tier 3: reusable providers, one selected per wired type + +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)] +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() + } +} +``` + +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! { + u32 { + SelfEncoderComponent: EncodeSelfAsText, + } +} +``` + +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. + +### Value contexts and application contexts + +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 +adding reusable behavior to a value while retaining a self-targeted interface. + +In the **environmental-context** arrangement, `Self` carries an application's dependencies and +implementation choices. An operation such as fetching a stored object belongs to that context: + +```rust +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchS3Object)] +impl StorageObjectFetcher { /* fetch the object from Amazon S3 */ } + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { /* read the object from a test's folder */ } + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +The omitted S3 body would need a client and a bucket, while the local body would need the path of +its folder. `App` and `TestApp` supply the appropriate dependencies. Their separate wiring lets +callers use the same consumer trait in either environment. + +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 +provider should implement and reuse together. + +## Tier 4: one provider per target type per context + +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)] +pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; +} +``` + +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! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeAsText, + } +} + +delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeAsHex, + } +} +``` + +`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. + +Making the value a parameter 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 + +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); + +#[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() + } +} +``` + +`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! { + App { + open EncoderComponent; + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVecWith, + @EncoderComponent.Vec>: EncodeVecWith, + } +} +``` + +`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. + +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 + +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. + +When providers are useful, identify what the context represents and whether the operation targets +another type. These arrangements answer different needs: + +| 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 | + +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 fetching a stored object. 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. + +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 + +Choose the tool that supplies the variation you actually need. These alternatives remain useful +alongside CGP: + +| 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 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, while the [trait +object](/docs/reference/glossary#trait-object) still performs its own runtime dispatch. + +## Where provider wiring does not help + +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. + +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. + +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 + +One context does not demonstrate the benefit of selecting different providers across contexts. +It may still have needs that provider-based code addresses: + +- **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. + +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. + +## Representing configuration choices + +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. + +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 +define its own context and backend representation. It can reuse the providers whose requirements +that context satisfies without changing the upstream enum. + +## What it costs + +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 +checked near the wiring. `cargo cgp check` leads with the root cause for the classes it recognizes, +and the tool does not yet reshape every class. The +[cargo-cgp documentation](/docs/tooling/cargo-cgp/) explains the checking workflow. + +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](/docs/ai/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 + +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. + +--- + +*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 new file mode 100644 index 00000000..6c9b6c56 --- /dev/null +++ b/docs/concepts/monadic-handlers.md @@ -0,0 +1,141 @@ +--- +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.' +--- + +# Monadic handlers + +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +monadic handlers make the rule that joins them a choice too. They 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. This page shows where direct composition stops, how a +monad marker sets the continuation rule, and how the resulting pipeline is wired. + +## When direct composition does not fit + +When computers compose directly, one step passes its whole output to the next, which 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] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} +``` + +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. + +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 + +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 +`cgp::extra::monad::monadic::err`: + +```rust +PipeMonadic +``` + +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 + +Choose the marker according to which result should end the pipeline: + +| 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 | + +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. + +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. + +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 + +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! { + App { + ComputerComponent: PipeMonadic, + } +} +``` + +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. + +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 + +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. + +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. + +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 + +These pages cover the computations, applications, and traits behind the pipeline: + +- [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. + +--- + +*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 new file mode 100644 index 00000000..f4328931 --- /dev/null +++ b/docs/concepts/namespaces.md @@ -0,0 +1,216 @@ +--- +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.' +--- + +# Namespaces + +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +namespaces keep the table that selects them short. A namespace gives shared wiring a name that +contexts can inherit. It organizes 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. + +This page starts from repeated wiring, follows a lookup along its path, shows why a bound entry +cannot be overridden, and ends with presets and per-type dispatch. + +## Repeated wiring obscures the differences + +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! { + App { + GreeterComponent: GreetHello, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } +} + +delegate_components! { + TestApp { + GreeterComponent: GreetQuietly, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } +} +``` + +Only the greeter changes, yet the farewell and announcer entries must be kept in agreement, and 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 + +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 {} } + +#[cgp_component(Greeter)] +#[prefix(@app.GreeterComponent in AppNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + +`AppNamespace` routes requests for the greeter through `@app.GreeterComponent`. A context joins the +namespace and supplies the provider at that path: + +```rust +delegate_components! { + App { + namespace AppNamespace; + + @app.GreeterComponent: GreetHello, + } +} +``` + +The context entry completes the route declared by `AppNamespace`, and Rust resolves both parts at +compile time. This works only because the destination was left unbound. Had the namespace already +bound it, a local entry would overlap the inherited one, since joining a namespace gives local +entries no priority. + +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 + +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! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } +} +``` + +`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 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 + +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! { + new AppDefaults { + GreeterComponent: GreetHello, + } +} + +// error[E0119]: conflicting implementations of trait +// `DelegateComponent` for type `TestApp` +delegate_components! { + TestApp { + namespace AppDefaults; + + GreeterComponent: GreetQuietly, + } +} +``` + +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: + +```rust +cgp_namespace! { new ProductionDefaults: AppDefaults { @app.GreeterComponent: GreetHello } } +cgp_namespace! { new TestDefaults: AppDefaults { @app.GreeterComponent: GreetQuietly } } +``` + +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 + +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 +namespace prefix: + +```rust +delegate_components! { + App { + open EncoderComponent; + + @EncoderComponent.String: EncodeAsText, + } +} +``` + +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 + +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. + +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. + +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 +structure. An [aggregate provider](/docs/reference/glossary#aggregate-provider) offers a simpler way to share a named group of implementations. + +## Where to go next + +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. + +--- + +*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 new file mode 100644 index 00000000..f7d5637d --- /dev/null +++ b/docs/concepts/send-bounds.md @@ -0,0 +1,157 @@ +--- +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.' +--- + +# Recovering `Send` bounds + +[Context-Generic Programming](/docs/) (CGP) leaves `Send` out of the futures its async trait methods +return, so generic code that needs a sendable future has to recover that bound. CGP's +`#[async_trait]` returns an unboxed future without promising `Send`, and 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. + +This page shows what the async rewrite promises, why spawning needs more, and how a companion trait +with concrete forwarding implementations supplies the guarantee. + +## What the async trait promises + +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)] +#[async_trait] +pub trait CanHandleApi { + type Response; + + async fn handle_api(&self, _api: PhantomData) -> Self::Response; +} +``` + +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. + +Leaving `Send` out of the signature permits implementations whose futures cannot move between +threads. Other implementations may return sendable futures, but generic callers have to allow for +either case. An explicit `+ Send` in the opaque return type would make the stronger promise +available to them. + +## Why spawning needs a stronger bound + +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. + +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: + +```rust +// Not available on stable Rust: +fn spawn_handler(app: App) +where + App: CanHandleApi + Send + 'static, +{ +} +``` + +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. + +## A companion trait with a sendable future + +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 +where + Self::Response: Send, +{ + fn handle_api_send(&self, api: PhantomData) + -> impl Future + Send; +} +``` + +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 + App: CanHandleApiSend, + App::Response: Send, +``` + +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. + +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 + +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: + +```rust +impl CanHandleApiSend for MockApp { + async fn handle_api_send(&self, api: PhantomData) -> u64 { + self.handle_api(api).await + } +} +``` + +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 + +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. + +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` +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 + +These pages explain the async components and the wiring checked by a concrete forwarding impl: + +- [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. + +--- + +*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 new file mode 100644 index 00000000..3f6157b6 --- /dev/null +++ b/docs/concepts/type-level-dsls.md @@ -0,0 +1,171 @@ +--- +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.' +--- + +# Type-level DSLs + +[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 +providers for the program's parts. This page builds a small arithmetic language, shows what the +compiler resolves and what still runs, and covers extending the language and adding a surface +syntax. + +## A program represented as a type + +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; +pub struct Add(pub PhantomData<(Left, Right)>); +pub struct Multiply(pub PhantomData<(Left, Right)>); +``` + +Nesting the markers represents a compound expression: + +```rust +type Program = Multiply, Literal<3>>, Literal<4>>; +``` + +The nesting describes `(2 + 3) * 4`, but the markers themselves do not evaluate it. Instead, 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. + +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 + +A provider implements one syntax form and asks the context to interpret its subexpressions. +This addition provider assumes the `CanCompute` consumer trait, the `Computer` provider trait, +and its `ComputerComponent` key are imported from `cgp::extra::handler`: + +```rust +#[cgp_impl(new EvalAdd)] +#[uses(CanCompute, CanCompute)] +impl Computer, ()> { + type Output = u64; + + fn compute(&self, _code: PhantomData>, _input: ()) -> u64 { + self.compute(PhantomData::, ()) + self.compute(PhantomData::, ()) + } +} +``` + +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 +of `ComputerComponent`: + +```rust +delegate_components! { + Interpreter { + open ComputerComponent; + + @ComputerComponent.Literal.(): EvalLiteral, + @ComputerComponent.Add.(): EvalAdd, + @ComputerComponent.Multiply.(): EvalMultiply, + } +} +``` + +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 +``` + +## What the compiler resolves + +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. + +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 + +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. + +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). + +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 + +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. + +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 + +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. + +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. + +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 + +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. + +--- + +*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/contribute.md b/docs/contribute.md index cb8ed21d..db11d0d7 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -1,48 +1,71 @@ --- -sidebar_position: 9 +title: 'Contribute to Context-Generic Programming' +sidebar_label: 'Contribute' +sidebar_position: 13 +description: 'The ways to help Context-Generic Programming, from asking a question or reporting a problem to publishing components, changing CGP itself, and sponsoring its author.' --- -# Contribute to CGP +# Contribute -We welcome contributors who are passionate about promoting CGP within the Rust ecosystem. Whether you're a beginner or an experienced Rust developer, there are numerous ways you can contribute to the project. +[Context-Generic Programming](/docs/) (CGP) lets you write several implementations of a Rust trait +and choose, for each type, which one applies. This page lists the ways you can help it, from the +smallest commitment to the largest, so you can stop at the first one that fits the time you have. +Each route helps on its own, and none of them requires the ones after it. -In this page, we'll explore different ways you can get involved and help grow the CGP community. Your contributions, regardless of your level of expertise, are valuable and appreciated! +## Join the discussion -## Participate in Discussions +Ask questions about CGP, and suggest what the documentation should cover next. The +[Community](/docs/resources/community) page lists the discussion channels and what each one suits. +Even a question helps, because one that a page should have answered shows which page needs work. -Join the conversation on platforms like [**Discord**](https://discord.gg/Hgk3rCw6pQ), [**GitHub**](https://github.com/orgs/contextgeneric/discussions) or [**Reddit**](https://www.reddit.com/r/cgp/). Whether you have questions about CGP or ideas for new topics or content, these forums are great places to share your thoughts and engage with the community. +## Report a problem -## Read The Documentation +If a page on this site confuses you, or says something the code contradicts, report it in [GitHub +Discussions](https://github.com/orgs/contextgeneric/discussions) or as an issue on the +[website's repository](https://github.com/contextgeneric/contextgeneric.dev/issues). -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. +The pages are written from the CGP knowledge base, a public record of CGP written for agents. Its +checks can miss an error or an inconsistency between two documents, so a problem you find there +saves the project a review it would otherwise have to do itself. File it on the knowledge base's +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues); +[Report problems in the knowledge base](/docs/ai/knowledge-base/contributing-with-an-agent#report-problems-in-the-knowledge-base) +says what to include. -## Publish Your own CGP Components +## Write about CGP and share it -The modularity provided by CGP can benefit everyone, even for those who do _not_ care about modularity. An ideal future for CGP is to have a community that publishes large amount of reusable components, that can be used by anyone to build modular applications with minimal application-specific code. +A blog post, a tutorial, or a talk about what you built with CGP, or how you learned it, helps other +readers even where this site already covers the topic, because a second explanation can reach a +reader the first one did not. You can also follow CGP on Bluesky, linked from the +[Community](/docs/resources/community) page, and share what you find useful there. -When that happens, it would become possible for CGP to be used by anyone, without having to write their own context-generic code. Instead, the majority of the users will only need to define the wirings of existing components that have been published by the community. +## Publish reusable components -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. +CGP aims at an ecosystem of published components and providers, in which most users write only the +wiring that selects them and little context-generic code of their own. A developer who wants +interchangeable implementations could then use them without first learning to write providers. That +ecosystem does not exist yet. If you write context-generic code, publishing your components and +providers as crates is the most direct way to help start it. -## Spread on Social Media +## Change CGP itself -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. - -## Write About It - -If you find CGP interesting, consider writing your own blog posts or tutorials to share your learning journey. Sharing your insights can help others learn CGP in different ways, and even if the topic is -already covered on the official site, your perspective might make it clearer to others. +To change the library, the [cargo-cgp](/docs/tooling/cargo-cgp) toolchain, the agent skill, or the +documentation, start from +[Contributing to CGP with an Agent](/docs/ai/knowledge-base/contributing-with-an-agent). It gives the +contribution policy, how to set up the repositories, and the rules each repository follows, whether +or not you work with a coding agent. ## Sponsor Me -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). +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 a sponsorship page on [Github Sponsor](https://github.com/sponsors/soareschen/). -*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. +## Acknowledgement -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. +CGP is created by [Soares Chen](https://maybevoid.com/), with inspiration drawn from various programming languages and paradigms, particularly Haskell typeclasses. -# Acknowledgement +The development of CGP would not have been possible without the strong support of my employer, [Informal Systems](https://informal.systems/). CGP was initially introduced and refined as part of the Hermes SDK project, which leverages CGP to build a highly modular relayer for inter-blockchain communication. -CGP is created by [Soares Chen](https://maybevoid.com/), with inspiration drawn from various programming languages and paradigms, particularly Haskell typeclasses. +--- -The development of CGP would not have been possible without the strong support of my employer, [Informal Systems](https://informal.systems/). CGP was initially introduced and refined as part of the [Hermes SDK](https://github.com/informalsystems/hermes-sdk/) project, which leverages CGP to build a highly modular relayer for inter-blockchain communication. +*An AI agent rewrote this page, apart from the sponsorship section and the acknowledgement, which are +the author's own. 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..4cfad932 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,76 +1,70 @@ --- +title: 'Introduction: pluggable trait implementations' +sidebar_label: 'Introduction' sidebar_position: 1 +description: 'Learn what Context-Generic Programming is, get to know its core terms, and find the documentation you need.' --- - # 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. - -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: - -```rust -#[cgp_component(HashProvider)] -pub trait Hash { ... } -``` - -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`: - -```rust -#[cgp_impl(HashWithDisplay)] -impl HashProvider -where - Self: Display, -{ ... } -``` - -You can then apply and reuse this implementation on any type by using the `delegate_components!` macro: - -```rust -pub struct MyData { ... } -impl Display for MyData { ... } - -delegate_components! { - MyData { - HashProviderComponent: HashWithDisplay, - } -} -``` - -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. - ---- - -# Current Status - -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. - -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. - -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. +Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait +implementations at compile-time. In plain Rust, a type has at most one implementation of each +trait. With CGP, you can instead write several implementations of the same trait and decide, for +each type that uses it, which one applies. + +None of this needs a new language or a new compiler. CGP is a library on stable Rust whose macros +expand to ordinary traits and implementations, and the compiler resolves every choice into a direct +call. You can bring it into an existing project one trait at a time. + +Four terms name the parts of that choice, and the rest of the documentation uses them throughout: + +- **[Context](/docs/reference/glossary#context):** a type, such as an application type, that + holds the data its implementations need and chooses which implementations it uses. +- **[Component](/docs/reference/glossary#component):** an interface whose implementation a context + chooses. +- **[Provider](/docs/reference/glossary#provider):** a named implementation of a component. +- **[Wiring](/docs/reference/glossary#wiring):** the table on a context that selects a provider for + each component, resolved at compile time. + +## Start here + +To start writing code, follow these pages from installation through wiring and checking your own +components: + +1. [Quickstart](/docs/quickstart): install CGP and run a first program in a few minutes. +2. [Hello World](/docs/tutorials/hello): understand a program like the Quickstart's, then see the + same function work on a second context. +3. [Swap a Storage Backend per Application](/docs/tutorials/storage-backend): build a small + application, then give its tests their own storage backend with a component and two providers. +4. [Area calculation](/docs/tutorials/area-calculation): turn ordinary Rust functions into + components and providers, then learn to check their wiring and understand errors. + +## Find what you need + +If you came with a particular question, find it below beside the page that answers it: + +- **What can CGP do, feature by feature?** The [Overview](/docs/overview). +- **Why does CGP work this way?** [Bypassing coherence](/docs/concepts/coherence) and + [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits), then the rest of the + [Concepts](/docs/concepts). +- **Does CGP fit my project?** [Modularity Hierarchy](/docs/concepts/modularity-hierarchy), and the + [costs and maturity](/#costs) on the front page. +- **How does it compare with what I know?** The [Comparisons](/docs/comparisons), from dependency + injection and type classes to ML modules and dynamic dispatch. +- **What does a construct do, or a term mean?** The [Reference](/docs/reference) and the + [Glossary](/docs/reference/glossary). +- **How do I read a CGP compile error?** [cargo-cgp](/docs/tooling/cargo-cgp), CGP's error toolchain. +- **What has been built with it?** The [Projects](/docs/projects). +- **How do I use CGP with a coding agent?** The [AI section](/docs/ai), with CGP's agent skill. +- **Where can I watch a talk about CGP?** The [Videos](/docs/resources/videos) page in Resources. +- **Where can I ask a question or follow CGP's news?** The [Community](/docs/resources/community) + page in Resources. +- **How can I help CGP?** [Contribute](/docs/contribute). + +For releases, design discussions, and talks, visit the [blog](/blog). Its older posts describe the +library as it was when they were published, so for CGP as it is today, rely on the pages above. --- -# 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. +*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 fa64f6b1..027aea16 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,89 +1,321 @@ --- -sidebar_position: 2 +title: 'Overview of the features, with examples' +sidebar_label: 'Overview' +sidebar_position: 3 +description: 'Explore Context-Generic Programming through Rust examples, from choosing implementations to checking wiring and abstracting over dependencies.' --- # 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/). +When deployments and tests need different implementations of the same interface, sharing code can +become difficult. [Context-Generic Programming](/docs/) (CGP) is a language extension for Rust, with +pluggable trait implementations at compile-time. The examples below show how those choices work, how +the compiler checks them, and where the approach has limits. + +If you are new to CGP, you can begin with its simplest form under +[*Still Ordinary Rust*](#still-ordinary-rust), or run a program with the +[Quickstart](/docs/quickstart). + +The examples follow an application that fetches users' profile pictures from object storage, as in +the [`cgp` README](https://github.com/contextgeneric/cgp/blob/main/README.md). Each is a fragment of +a program that compiles against `cgp` 0.8.0. To focus on how the code fits together, the fragments +omit imports, supporting definitions, and requests to the storage services. They also omit the +context checks explained under [*Type-Safe Wiring*](#type-safe-wiring). To keep the fragments +short, the methods are synchronous, although a real storage client would be async, as +[Swap a Storage Backend per Application](/docs/tutorials/storage-backend) shows. + +## Key features + +### One Interface, Many Implementations + +Suppose one deployment stores its pictures in Amazon S3, another uses Google Cloud Storage, and +tests read from a local folder. In plain Rust, each application type can implement a fetching trait +itself, but then the S3 code belongs to that one type. To share that code, you might try writing a +blanket implementation for every type with an S3 client and another for every type with a Google +Cloud client. Rust rejects that pair, because one type could have both clients. + +CGP avoids the conflict by giving each implementation a type of its own, called a **provider**. +Because the providers are different types, their implementations never overlap. Here is the +interface, defined as a CGP **component**, and the provider that fetches from S3: + +```rust +#[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // Fetch the object from Amazon S3. + } +} +``` + +The `#[cgp_component]` attribute keeps `CanFetchStorageObject` as the trait that callers use, and it +generates `StorageObjectFetcher`, the trait that each provider implements. The `#[implicit]` +arguments read the client and the bucket from the fields of whichever type uses the provider, so a +caller passes only the object's ID. + +Two more providers follow the same pattern: `FetchGCloudObject` reads a Google Cloud `Storage` +client from the same `storage_client` field, and `FetchLocalObject` reads files from a `local_dir` +field for tests. Each application type, which CGP calls a **context**, then chooses one provider in +its **wiring**: + +```rust +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + GCloudApp { + StorageObjectFetcherComponent: FetchGCloudObject, + } +} + +delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +Code that calls `fetch_storage_object` stays the same in all three contexts. Rust's coherence rules +still apply to everything the macros generate. CGP only arranges the implementations so that they no +longer conflict. +[Bypassing coherence](/docs/concepts/coherence) explains the rules, and +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) shows how a call reaches +the chosen provider. + +### Zero-Cost Abstraction + +Choosing a provider adds no runtime overhead because the compiler resolves the wiring into a direct +call. For `App`, the wiring above amounts to this implementation, which you could also write by +hand: + +```rust +impl CanFetchStorageObject for App { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + >::fetch_storage_object(self, object_id) + } +} +``` + +Here, `StorageObjectFetcher` is the provider trait with `App` as its context parameter. +That parameter lets one provider serve many contexts. The call names the provider directly, +without a runtime registry, reflection, or a virtual method table, and the provider itself is never +instantiated: it exists only as a type. + +The work inside the provider, such as the request to S3, still has its usual runtime cost. +Generic code can also increase compile time and code size. To inspect the generated code, use +[`cargo cgp expand`](/docs/tooling/cargo-cgp/expand). For a comparison with `dyn Trait`, see +[Dynamic dispatch](/docs/comparisons/dynamic-dispatch). + +### Type-Safe Wiring + +A provider needs more than a place in the wiring table: its context must supply the fields and +traits it uses. The compiler checks those requirements when you use the component or check its +wiring explicitly. For example, `FetchS3Object` needs a `bucket_id` field. This context lacks that +field, so `check_components!` produces a compile error: + +```rust +#[derive(HasField)] +pub struct App { + pub storage_client: aws_sdk_s3::Client, +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +check_components! { + App { + StorageObjectFetcherComponent, + } +} +``` + +[cargo-cgp](/docs/tooling/cargo-cgp), CGP's error toolchain, reports the missing field first, followed by +the chain of requirements that led to it. Here is its report, without the source excerpt that points +at the check: + +```text +error[E0277]: [CGP-E001] missing field `bucket_id` on `App` + = note: root cause: [CGP-E110] missing field `bucket_id` on `App` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanFetchStorageObject` for context `App` + └─ [CGP-E102] provider trait impl `StorageObjectFetcher` with context `App` for provider `FetchS3Object` + └─ [CGP-E110] missing field `bucket_id` on `App` + = help: add the field `bucket_id` to `App` +``` + +Because wiring alone does not check those requirements, check each context where you assemble it. +For a simple context, +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) wires each +entry and checks it in the same step. Even then, the check establishes that the components fit +together, not that the application is correct. + +Without cargo-cgp, this error takes more effort to read: the raw compiler message is longer and +represents the field's name as a nested type. `cargo cgp check` leads with the root +cause for the classes it recognizes, and the tool does not yet reshape every class. +[Check traits](/docs/concepts/check-traits) explains the checks, the +[checking tutorial](/docs/tutorials/area-calculation/checking) walks through a mis-wiring, and +[Dependency injection](/docs/comparisons/dependency-injection) compares wiring with a container. + +### Abstract Over Every Dependency + +So far the component has returned `anyhow::Result`, which ties every implementation to one error +type. To let each context choose its own error type, the component can declare that dependency +without naming a concrete type. Here the same component uses the context's +error type instead of `anyhow::Error`, and a provider declares the conversion it needs with +`#[uses]`, without adding it to the interface: + +```rust +#[cgp_component(StorageObjectFetcher)] +#[use_type(HasErrorType.Error)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> Result, Error>; +} + +#[cgp_impl(new FetchLocalObject)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> Result, Error> { + std::fs::read(format!("{local_dir}/{object_id}")).map_err(Self::raise_error) + } +} +``` + +This definition of `CanFetchStorageObject` replaces the earlier one. Its `#[use_type]` attribute +lets the trait and the provider write `Error` for whatever error type the context chooses. The +provider's `#[uses]` attribute requires a conversion from a file error into that type. The call to +`Self::raise_error` performs that conversion. + +The S3 and Google Cloud providers change in the same way: each returns `Error` and declares, with +`#[uses]`, the conversion it needs from its client's error. A context then chooses its error type in +a single wiring entry, such as `ErrorTypeProviderComponent: UseType`, next to the +providers that convert each source error into it. Another context can choose an error enum of its +own without touching this code, as long as it supplies those conversions as well. + +The same arrangement works for other dependencies, such as an async runtime, and it lets a core +library stay `no_std` as long as the providers chosen for it are `no_std` too. A provider that reads +files, like this one, still needs `std`. +[Modular error handling](/docs/concepts/modular-error-handling) explains how a context chooses its +error type, and [Impl-side dependencies](/docs/concepts/impl-side-dependencies) explains how a +provider keeps its needs out of the interface. + +### Still Ordinary Rust + +CGP is a library on stable Rust, and you can use it without defining providers or wiring at all. +Its simplest form is a function whose `#[implicit]` arguments come from the context's fields: + +```rust +#[cgp_fn] +pub fn get_user( + &self, + #[implicit] database: &PgPool, + user_id: &UserId, +) -> anyhow::Result { + // Query `database` for the user row. +} +``` + +`#[cgp_fn]` turns the function into a trait with a +[blanket implementation](/docs/reference/glossary#blanket-implementation), so any context with a +`PgPool` field named `database` gains `get_user`, with no wiring at all. The rest of CGP stays close +to ordinary Rust too. Providers use familiar `impl` syntax, and the trait that callers use remains +an ordinary trait, so the hand-written implementation under *Zero-Cost Abstraction* is a valid way +to implement it directly. This is why you can adopt CGP one component at a time. The price is +learning the provider model and maintaining the wiring. +[Implicit arguments](/docs/concepts/implicit-arguments) explains the field reads, and +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) helps you judge how much of CGP a +problem needs. + +## Beyond choosing implementations + +Once you are comfortable choosing implementations, you can use the same mechanisms to share types, +work over the shape of data, compose computations and providers, and reuse wiring. These features +are optional, and the linked pages explain each one with examples: + +- **Abstract types:** a context chooses types as well as implementations. When several traits import + the context's error type, they all agree on it, so a function that uses them needs no bound to + equate their errors, and the error type stops being a parameter that every layer has to carry. + [Abstract types](/docs/concepts/abstract-types) explains how. +- **Extensible records and variants:** a derive exposes a struct's fields or an enum's variants to + the trait system, so generic code can build a record from separate pieces, or call a trait on an + enum through whichever variant it holds without writing a `match`. + [Extensible records](/docs/concepts/extensible-records), + [Extensible variants](/docs/concepts/extensible-variants), and + [Dispatching](/docs/concepts/dispatching) cover the patterns. +- **Composable handlers:** components for synchronous or async computations that may be fallible + or infallible. Their providers form pipelines that a context selects in its wiring. + [Handlers](/docs/concepts/handlers) covers the family. +- **Namespaces:** a wiring table that several contexts share, so each context lists only the entries + where it differs. [Namespaces](/docs/concepts/namespaces) explains them, along with the lighter + `open` statement for choosing a provider per type. +- **Higher-order providers:** a provider that takes another provider as a parameter, such as a + wrapper that scales whatever area its inner provider computes. + [Higher-order providers](/docs/concepts/higher-order-providers) shows how they compose. + +## The problems it solves + +CGP helps most when a program already needs several implementations or repeats dependencies +through its signatures. If those problems sound familiar, these concept pages explain how CGP +addresses them: + +| Problem | Explained in | +| --- | --- | +| Rust rejects two implementations of a trait for the same type | [Bypassing coherence](/docs/concepts/coherence) | +| A trait for a type you do not own needs a newtype | [Bypassing coherence](/docs/concepts/coherence) | +| Tests need a different implementation from production | [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) | +| Feature flags already select between backends | [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) | +| Changing the error type or runtime touches every layer | [Modular error handling](/docs/concepts/modular-error-handling) | +| A trait has grown until no implementation needs all of it | [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) | +| An implementation's dependencies leak into the public interface | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | +| Generic parameters and their bounds repeat through every layer | [Abstract types](/docs/concepts/abstract-types) | +| Generic code needs to work over any struct or enum | [Extensible records](/docs/concepts/extensible-records) | +| A wiring error buries its cause in generated types | [Check traits](/docs/concepts/check-traits) | + +## When a plain trait is enough + +For a trait with only one implementation, a plain trait is the right tool. CGP adds declarations +and wiring, and its macros and type checking add compile-time work. Its raw compiler errors can +also be long, as [*Type-Safe Wiring*](#type-safe-wiring) shows. + +Learning the provider model and wiring patterns takes time too. If you work with an assistant, +[CGP's agent skill](/docs/ai/skills/) helps it with the vocabulary, diagnostics, and wiring, +although you still need to review what it writes. The [front page's costs](/#costs) describe the +project's maturity, and [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) explains when +a plain trait is enough and when providers start to help. + +## Where to go next + +To try these patterns in your own code or learn how they work, continue with these pages: + +- **Run code:** the [Quickstart](/docs/quickstart), then the + [Hello World tutorial](/docs/tutorials/hello), or build this page's storage example step by step + in [Swap a Storage Backend per Application](/docs/tutorials/storage-backend). +- **Understand the mechanism:** the [Concepts](/docs/concepts), starting with + [Bypassing coherence](/docs/concepts/coherence). +- **Compare with what you know:** the [Comparisons](/docs/comparisons). +- **Look up a construct:** the [Reference](/docs/reference). -# Key Features - -This section highlights some of the key advantages that Context-Generic Programming (CGP) offers. - -## Modular Component System - -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: - -- **Provider traits**, which define the implementation of a component interface. -- **Consumer traits**, which specify how a component interface is consumed. - -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. - -## Highly Expressive Macros - -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. - -Additionally, CGP offers powerful _macros_ for defining component interfaces and simplifies the process of wiring component implementations for use with a specific context. - -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. - -## Type-Safe Composition - -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. - -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. - -## No-Std Friendly - -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. - -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. - -## Zero-Cost Abstraction - -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. - - -# Problems Solved - -Here are some common problems in Rust that CGP helps to address. - -## Error Handling - -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. - -For more detailed information on error handling, refer to the [error handling chapter](https://patterns.contextgeneric.dev/error-handling.html) in our book - -## Async Runtime - -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. - -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. - -## Overlapping Implementations - -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. - -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. - -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. - -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. - -## Dynamic Dispatch - -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`. - -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. - -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. - -## Monolithic Traits - -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. - -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. - -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. +--- -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. +*An AI agent wrote this page using the CGP knowledge base, and its examples were verified by +compiling them. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/_category_.json b/docs/projects/_category_.json new file mode 100644 index 00000000..e1a52bef --- /dev/null +++ b/docs/projects/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Projects", + "position": 9, + "link": { + "type": "doc", + "id": "projects/index" + } +} 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..63e5ba9b --- /dev/null +++ b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md @@ -0,0 +1,121 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait implementations +chosen at compile time, 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-E020] the wiring for the consumer trait `CanCompute` on context `contexts::add_mult::Interpreter` never resolves, because the lookup leads back to itself + = help: wire a provider in place of `EvalAdd`, which provides `Computer<_, Plus<…>>` for `…` by requiring `CanCompute<_, …>` on `…` again +``` + +The same error follows for `Plus` and `Times`, and two raw overflow errors for the dispatcher +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 block elides the +paths in that help line. + +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..7ac12478 --- /dev/null +++ b/docs/projects/cgp-examples/expression/architecture/index.md @@ -0,0 +1,99 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), 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..a2774463 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md @@ -0,0 +1,197 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations, with one provider wired for both binary operators at compile time. 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. + +::: + +## 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 +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. +- [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. + +--- + +*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..81d1b788 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -0,0 +1,201 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), +which enables pluggable trait implementations, chosen per operation and input at compile time. 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. + +::: + +## 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 +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/tooling/cargo-cgp/check). The check names the missing entry, with both parts of +its key: + +```text +error[E0277]: [CGP-E001] missing wiring for `@ComputerRefComponent.ToLisp.Plus<…>` on `…` + = note: root cause: [CGP-E113] missing wiring for `@ComputerRefComponent.ToLisp.Plus<…>` on `…` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanComputeRef>` for context `…` + └─ [CGP-E103] redirect lookup to `@ComputerRefComponent` in `…` + = help: wire `@ComputerRefComponent.ToLisp.Plus<…>` to a provider in the wiring of `…` +``` + +Evaluating a `Plus` still has its entry, so only conversion is broken. A second error, `E0271`, +points at the `ToLisp` wrapper's call to the dispatcher, where the missing entry leaves the output +types unresolved. The block elides the module paths and the last hop of the chain, which ends at the +same missing entry. `cargo cgp check` leads with the root cause for the classes it recognizes, and +the tool 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. +- [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. + +--- + +*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..1da9aa5f --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md @@ -0,0 +1,198 @@ +--- +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 [Context-Generic Programming](/docs/) +(CGP), which enables pluggable trait implementations that a new language reuses at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check), and the check reports that conversion was never +wired: + +```text +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 +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 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. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#extending-mathexpr): the post + that introduced this extension. 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/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md new file mode 100644 index 00000000..86404d1d --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -0,0 +1,340 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations, one per operator, resolved at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check). The check names the missing entry: + +```text +error[E0277]: [CGP-E001] missing wiring for `@ComputerComponent.Eval.Times<…>` on `…` + = note: root cause: [CGP-E113] missing wiring for `@ComputerComponent.Eval.Times<…>` on `…` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCompute>` for context `…` + └─ [CGP-E103] redirect lookup to `@ComputerComponent` in `…` + = help: wire `@ComputerComponent.Eval.Times<…>` to a provider in the wiring of `…` +``` + +A second, longer error, `[CGP-E002]`, points at the wrapper's call to `MatchWithValueHandlers`, +because the dispatcher's chain cannot provide a `Times` operand either. The first error is the one +to read, and the block elides the module paths, which name the context's module. Removing the entry +leaves `EvalMultiply` unused, so the output carries a warning about that import. `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 + +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. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#evaluator-computer): 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/expression/examples/index.md b/docs/projects/cgp-examples/expression/examples/index.md new file mode 100644 index 00000000..5e67c465 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/index.md @@ -0,0 +1,58 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), which enables pluggable trait implementations: 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..d5737258 --- /dev/null +++ b/docs/projects/cgp-examples/expression/index.md @@ -0,0 +1,118 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), 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..a15f3160 --- /dev/null +++ b/docs/projects/cgp-examples/index.md @@ -0,0 +1,62 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), 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. The code these pages +show 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. +- [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. + +--- + +*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..13685e84 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/_category_.json @@ -0,0 +1,6 @@ +{ + "label": "Stages", + "position": 1, + "collapsed": false, + "description": "One social-media backend wired four ways with Context-Generic Programming, from one trait per domain to namespace defaults." +} 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..5467a01e --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -0,0 +1,200 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations, one per domain, chosen at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check). The whole user manager fails: + +```text +error[E0277]: [CGP-E001] missing wiring for `UsernameCensorComponent` on `…ProductionApp` + = note: root cause: [CGP-E113] missing wiring for `UsernameCensorComponent` on `…ProductionApp` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanManageUser` for context `…ProductionApp` + └─ [CGP-E102] provider trait impl `UserManager` with context `…` for provider `PostgresUserManager` + └─ [CGP-E101] consumer trait impl `CanCensorUsername` for context `…ProductionApp` + = help: wire `UsernameCensorComponent` to a provider in the wiring of `…ProductionApp` +``` + +The chain names the manager, the provider behind it, and the censor that provider's `create_user` +needs, so the whole manager goes with the censor. 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. The block elides the module paths. 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 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. +- [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. + +--- + +*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..c44d911b --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -0,0 +1,197 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations that a namespace can supply as defaults at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check), and the entry is rejected: + +```text +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 +lookup, and Rust rejects the two as conflicting implementations, which is `E0119` underneath the +tool's message. The block elides the module names the tool qualifies the context and the component +with. 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 +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. +- [CGP v0.8.0](/blog/v0.8.0-release#default-implementations): the release post that develops this + application stage by stage. + +--- + +*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..ef1a3054 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -0,0 +1,212 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations, one per operation, chosen at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check). This time only the operation that uses the censor fails: + +```text +error[E0277]: [CGP-E001] missing wiring for `UsernameCensorComponent` on `…ProductionApp` + = note: root cause: [CGP-E113] missing wiring for `UsernameCensorComponent` on `…ProductionApp` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCreateUser` for context `…ProductionApp` + └─ [CGP-E102] provider trait impl `UserCreator` with context `…` for provider `…FilterCensoredUsername<…>` + └─ [CGP-E101] consumer trait impl `CanCensorUsername` for context `…ProductionApp` + = help: wire `UsernameCensorComponent` to a provider in the wiring of `…ProductionApp` +``` + +The chain runs from the creator, through the bundle and the wrapper that filters it, to the censor +only `create_user` needs. Getting and updating users still check, because their providers need only +the database. The block elides the module paths and the bundle hop above the wrapper. 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 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. +- [CGP v0.8.0](/blog/v0.8.0-release#fine-grained-traits): the release post that develops this + application stage by stage. + +--- + +*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..5de693b5 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -0,0 +1,198 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), which enables pluggable trait +implementations, with the choices grouped under paths and resolved at compile time. 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check). The two +creators fail, each with the filter its wrapper uses: + +```text +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` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCreateUser` for context `TestApp` + … + = help: wire `@app.extra.content_filter.…UsernameCensorComponent` to a provider in the wiring of `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` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCreatePost` for context `TestApp` + … + = help: wire `@app.extra.content_filter.…SpamMessageDetectorComponent` to a provider in the wiring of `TestApp` +``` + +Each root cause names the full path the namespace routed the lookup to, which says where the entry +belongs, and each chain lists every lookup on the way there: from the creator, through the redirect +to `@app.core`, `PostgresCoreComponents`, and the bundle behind it. The block elides those hops and +the module names the tool adds to each path. 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 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. +- [CGP v0.8.0](/blog/v0.8.0-release#introducing-cgp-namespaces-and-paths): the release post that + develops this application stage by stage. + +--- + +*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..337e71f9 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/index.md @@ -0,0 +1,83 @@ +--- +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 an application built with [Context-Generic Programming](/docs/) (CGP) 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); CGP is 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/tooling/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. +- [CGP v0.8.0](/blog/v0.8.0-release): the release post that develops this application stage by + stage, and introduces 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/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..e92db843 --- /dev/null +++ b/docs/projects/cgp-serde/architecture/component-design.md @@ -0,0 +1,162 @@ +--- +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 +[Context-Generic Programming (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) | +| [`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 | + +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..629d4eb0 --- /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 [Context-Generic Programming (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 example, 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..5747ebde --- /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 +[Context-Generic Programming (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`. + +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 + +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::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`. +- **`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..c73fad3f --- /dev/null +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -0,0 +1,114 @@ +--- +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 [Context-Generic Programming (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. +[`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: + +```rust +@ValueSerializerComponent.Payload: + SerializeRecordFields, + +@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 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 +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 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 or none. The +[comparison with Serde](../serde-comparison.md) lists what Serde's derive does that cgp-serde's +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..d6f56fa7 --- /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 [Context-Generic Programming (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..be4f2d4c --- /dev/null +++ b/docs/projects/cgp-serde/architecture/reentrant-providers.md @@ -0,0 +1,169 @@ +--- +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 [Context-Generic Programming (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, +[`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. + +## 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..73416dc6 --- /dev/null +++ b/docs/projects/cgp-serde/architecture/serde-bridge.md @@ -0,0 +1,130 @@ +--- +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 [Context-Generic Programming (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 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 +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..a8c272b3 --- /dev/null +++ b/docs/projects/cgp-serde/examples/basic.md @@ -0,0 +1,287 @@ +--- +sidebar_label: 'basic' +sidebar_position: 1 +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 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 [Context-Generic Programming (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. + +::: + +## 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): + +```sh +cargo run -p cgp-serde-examples --example basic +``` + +It prints the JSON the struct serializes to, and the value read back from it: + +```text +serialized: {"quantity":42,"message":"hello","data":"010203"} +deserialized: Payload { quantity: 42, message: "hello", data: [1, 2, 3] } +``` + +`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-examples/examples/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 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 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; + +delegate_components! { + App { + open { + ValueSerializerComponent, + ValueDeserializerComponent, + TryComputerComponent, + }; + + ErrorTypeProviderComponent: + UseAnyhowError, + + ErrorRaiserComponent: + RaiseAnyhowError, + + @ValueSerializerComponent.u64: + UseSerde, + + @ValueSerializerComponent.String: + SerializeString, + + @ValueSerializerComponent.Vec: + SerializeHex, + + @ValueSerializerComponent.Payload: + SerializeRecordFields, + + @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. +- [`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 +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 + +`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. +[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 example calls both through `try_compute`: + +```rust +let serialized = context + .try_compute(PhantomData::, &payload()) + .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 example 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 example's 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 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 +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. +- [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. + +--- + +*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/events.md b/docs/projects/cgp-serde/examples/events.md new file mode 100644 index 00000000..3d14defc --- /dev/null +++ b/docs/projects/cgp-serde/examples/events.md @@ -0,0 +1,217 @@ +--- +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 [Context-Generic Programming (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`. +`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 + +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.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.Nil: SerializeUnit, + @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 `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`, +[`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 the server's `@ValueDeserializerComponent.Nil: SerializeUnit` entry, remove +`(Life<'de>, Nil)` from its check, and run [`cargo cgp check`](/docs/tooling/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] 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 +struct has a `Nil` 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 new file mode 100644 index 00000000..2c00aadb --- /dev/null +++ b/docs/projects/cgp-serde/examples/index.md @@ -0,0 +1,60 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +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 + +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 +[Context-Generic Programming (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. + +:::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 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 + +- [`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. +- [`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 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 + +- [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..b5128997 --- /dev/null +++ b/docs/projects/cgp-serde/examples/messages.md @@ -0,0 +1,317 @@ +--- +sidebar_label: 'messages' +sidebar_position: 2 +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 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 +[Context-Generic Programming (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. + +::: + +## 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 +example: + +```sh +cargo run -p cgp-serde-examples --example messages +``` + +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 +{ + "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: + +```json +{ + "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 data names no encoding + +The archive is three nested structs, from +[`messages.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-examples/examples/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 their existing `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, + ]: + SerializeRecordFields, + } +} +``` + +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. +[`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 +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 example hands each context and the archive to `serde_json`, through a helper +that accepts any context able to serialize the archive: + +```rust +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 +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/tooling/cargo-cgp/check). The check on `AppB` fails, and the tool names the +missing entry as the root cause: + +```text +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 +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. + +## The pattern + +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 +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. +- [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. + +--- + +*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..9f3e2500 --- /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 context, write a provider, use a format, and debug the wiring in cgp-serde, a serialization library built with Context-Generic Programming (CGP)." + } +} 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..db96f13e --- /dev/null +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -0,0 +1,270 @@ +--- +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 +[Context-Generic Programming (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/tooling/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 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 +[`SerializeRecordFields`](../reference/providers/serialize_record_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: SerializeRecordFields, + } +} + +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] 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-E103] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E102] provider trait impl `ValueSerializer` with context `App` for provider `SerializeRecordFields` + └─ [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-E103] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E113] missing wiring for `@ValueSerializerComponent.Vec` on `App` + = help: wire `@ValueSerializerComponent.Vec` to a provider in the wiring of `App` +``` + +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 + +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] 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`, +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 example, with the allocator entry removed, the check on the borrowed types reports: + +```text +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 +[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-E003] missing wiring for `ErrorTypeProviderComponent` and `ErrorRaiserComponent` on `Ctx` + = note: root causes: + - [CGP-E113] missing wiring for `ErrorTypeProviderComponent` on `Ctx` + - [CGP-E113] missing wiring for `ErrorRaiserComponent` on `Ctx` + = help: wire `ErrorTypeProviderComponent` and `ErrorRaiserComponent` to providers in the wiring of `Ctx` +``` + +The root causes and the help line name the same two entries, which [wiring a +context](./wiring-a-context.md#4-wire-an-error-type-when-the-json-providers-are-used) adds. + +## 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-E020] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves, because the lookup leads back to itself +``` + +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 +[`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: SerializeRecordFields, + } +} +``` + +```text +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 +`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/tooling/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..33490980 --- /dev/null +++ b/docs/projects/cgp-serde/guides/formats.md @@ -0,0 +1,101 @@ +--- +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 [Context-Generic Programming (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..8471154b --- /dev/null +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -0,0 +1,232 @@ +--- +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 [Context-Generic Programming (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, + ]: + SerializeRecordFields, + } +} +``` + +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 [`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: + `@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]: + SerializeRecordFields, + } +} + +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..dabde0cf --- /dev/null +++ b/docs/projects/cgp-serde/guides/writing-a-provider.md @@ -0,0 +1,161 @@ +--- +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 [Context-Generic Programming (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..deb552de --- /dev/null +++ b/docs/projects/cgp-serde/index.md @@ -0,0 +1,179 @@ +--- +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 [Context-Generic Programming (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, 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 + +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/tooling/cargo-cgp/check) + names the missing entry: `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. +- **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 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. +- [`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 +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 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, add its crates from crates.io beside `cgp`: `cgp-serde` for +the components and core providers, then `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, or +`cgp-serde-typed-arena` for the providers your wiring names, and a Serde format such as +`serde_json` to write the output: + +```toml +[dependencies] +cgp = "0.8.0" +cgp-serde = "0.3.0" +cgp-serde-extra = "0.3.0" +serde_json = "1" +``` + +## 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. +- [cgp-serde's release notes](/docs/release-notes/cgp-serde): what each official release changed, and the + steps to upgrade from the one before. + +--- + +*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..a1b77e2c --- /dev/null +++ b/docs/projects/cgp-serde/limitations.md @@ -0,0 +1,101 @@ +--- +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 the wiring of +[Context-Generic Programming (CGP)](/docs/) 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 CGP components. 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 and simple enums + +The providers that walk a type generically handle structs with named fields, enums whose variants +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 +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/tooling/cargo-cgp/check) gets to the cause faster: +`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 + +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..416e105d --- /dev/null +++ b/docs/projects/cgp-serde/reference/components/can_alloc.md @@ -0,0 +1,86 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..b103a236 --- /dev/null +++ b/docs/projects/cgp-serde/reference/index.md @@ -0,0 +1,108 @@ +--- +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 +[Context-Generic Programming (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::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 | +|---|---|---|---|---| +| [`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 | +| [`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 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` | +| [`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..4d2842ba --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md @@ -0,0 +1,99 @@ +--- +title: 'AllocateWithArena — allocate into an arena held by the context in cgp-serde' +sidebar_label: 'AllocateWithArena' +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.' +--- + +# `AllocateWithArena` + +Allocate a value into the arena the context supplies. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 example: + +```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..18911169 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md @@ -0,0 +1,88 @@ +--- +title: 'DeserializeAndAllocate — read a reference into an allocator in cgp-serde' +sidebar_label: 'DeserializeAndAllocate' +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.' +--- + +# `DeserializeAndAllocate` + +Read a borrowed `&'a Value` by reading an owned `Value` and allocating it through the context. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 example: + +```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..acf1fdbb --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_default.md @@ -0,0 +1,92 @@ +--- +title: 'DeserializeDefault — read a null value as the default in cgp-serde' +sidebar_label: 'DeserializeDefault' +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.' +--- + +# `DeserializeDefault` + +Read a null input as the type's `Default`, and pass any other input to an inner provider. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..e6a46c09 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_extend.md @@ -0,0 +1,88 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 example 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..e63c3862 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md @@ -0,0 +1,116 @@ +--- +title: 'DeserializeFromJsonReader — read JSON from any serde_json reader in cgp-serde' +sidebar_label: 'DeserializeFromJsonReader' +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.' +--- + +# `DeserializeFromJsonReader` + +Read a value from any `serde_json` reader through the context, and reject anything after it. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..6c244915 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md @@ -0,0 +1,103 @@ +--- +title: 'DeserializeFromJsonString — read JSON from a string in cgp-serde' +sidebar_label: 'DeserializeFromJsonString' +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.' +--- + +# `DeserializeFromJsonString` + +Read a value from a string by wrapping it in a `serde_json` reader and handing it to an inner +provider. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 example 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..949ad28d --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md @@ -0,0 +1,117 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 + +```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 example'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 + +[`SerializeRecordFields`](./serialize_record_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_variant_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md new file mode 100644 index 00000000..b93d758f --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md @@ -0,0 +1,122 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 one unnamed +payload or no fields. + +## 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, `Nil` for a +variant with no fields. + +## 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.Nil: SerializeUnit, + @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 `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 `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: + +```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, which is `Nil` for a +variant with no fields. + +## 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 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 + +- [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/deserialize_with_from_str.md b/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md new file mode 100644 index 00000000..66087f96 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md @@ -0,0 +1,87 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..212586aa --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_base64.md @@ -0,0 +1,87 @@ +--- +title: 'SerializeBase64 — encode bytes as base64 in cgp-serde' +sidebar_label: 'SerializeBase64' +sidebar_position: 19 +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..de56a9cf --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_bytes.md @@ -0,0 +1,98 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..e5dad5a1 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_deref.md @@ -0,0 +1,84 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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_from.md b/docs/projects/cgp-serde/reference/providers/serialize_from.md new file mode 100644 index 00000000..69a5f129 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_from.md @@ -0,0 +1,98 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..f256f2b2 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_hex.md @@ -0,0 +1,98 @@ +--- +title: 'SerializeHex — encode bytes as hex in cgp-serde' +sidebar_label: 'SerializeHex' +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.' +--- + +# `SerializeHex` + +Write bytes as a lowercase hexadecimal string, and read a hex string back. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..1047d67f --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_iterator.md @@ -0,0 +1,95 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 + +- [`SerializeRecordFields`](./serialize_record_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_record_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md new file mode 100644 index 00000000..9f8b8bf3 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md @@ -0,0 +1,108 @@ +--- +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.' +--- + +# `SerializeRecordFields` + +Write a struct as a map from each field's name to its value, asking the context to write each value. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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. + +## Definition + +```rust +pub struct SerializeRecordFields; + +#[cgp_impl(SerializeRecordFields)] +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: SerializeRecordFields, +``` + +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 `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 + +- [`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_rfc3339_date.md b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md new file mode 100644 index 00000000..0f33b4e7 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md @@ -0,0 +1,81 @@ +--- +title: 'SerializeRfc3339Date — encode a date as an RFC 3339 string in cgp-serde' +sidebar_label: 'SerializeRfc3339Date' +sidebar_position: 20 +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..1be7f408 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_string.md @@ -0,0 +1,93 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..c3297fee --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md @@ -0,0 +1,92 @@ +--- +title: 'SerializeTimestamp — encode a date as a Unix timestamp in cgp-serde' +sidebar_label: 'SerializeTimestamp' +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.' +--- + +# `SerializeTimestamp` + +Write a `DateTime` as a Unix timestamp in whole seconds, and read one back. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..fe7c5b46 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md @@ -0,0 +1,114 @@ +--- +title: 'SerializeToJsonString — write JSON as an operation on the context in cgp-serde' +sidebar_label: 'SerializeToJsonString' +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.' +--- + +# `SerializeToJsonString` + +Write a value as a compact JSON string, as a fallible operation the context runs. + +## Overview + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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_unit.md b/docs/projects/cgp-serde/reference/providers/serialize_unit.md new file mode 100644 index 00000000..c64de6df --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_unit.md @@ -0,0 +1,105 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 not in `cgp::prelude`, so a table that names it imports it from `cgp::core::field::types`. + +## 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 new file mode 100644 index 00000000..9205678b --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md @@ -0,0 +1,142 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 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 + +```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, `Nil` for a variant with no fields. + +## 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.Nil: SerializeUnit, + @ValueSerializerComponent.Circle: SerializeRecordFields, + @ValueSerializerComponent.Shape: SerializeVariantFields, + } +} +``` + +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}}` 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: +structs are written as maps without a declared length, which RON shows in map syntax and postcard +rejects. + +## Context dependencies + +`CanSerializeValue

`](../../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 + +An async computer provider, wired into a context and awaited through the consumer trait: + +```rust +use core::marker::PhantomData; +use cgp::extra::handler::{AsyncComputer, AsyncComputerComponent}; +use cgp::prelude::*; +use cgp::extra::handler::CanComputeAsync; + +#[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 +} +``` + +`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.** 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 `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 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`, 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`. + +--- + +*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 new file mode 100644 index 00000000..6af52b30 --- /dev/null +++ b/docs/reference/components/handler/async_computer_ref.md @@ -0,0 +1,150 @@ +--- +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 +--- + +# `AsyncComputerRef` + +The async, by-reference member of the handler family: an [`AsyncComputer`](./async_computer.md) that +borrows its input. + +## Overview + +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. + +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 + +`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, 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]`](../../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`, `AsyncComputerRefComponent`, and the consumer trait `CanComputeAsyncRef` are +not in the prelude, and 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 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 provider that counts the words of a borrowed string, wired into a context and awaited: + +```rust +use core::marker::PhantomData; +use cgp::extra::handler::{AsyncComputerRef, AsyncComputerRefComponent, CanComputeAsyncRef}; +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 { + AsyncComputerRefComponent: CountWords, + } +} + +check_components! { + App { + AsyncComputerRefComponent: ((), String), + } +} + +pub async fn run(app: &App, text: &String) -> usize { + app.compute_async_ref(PhantomData::<()>, text).await +} +``` + +`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 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 +[`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) — `PromoteRef` and the promotion bundles. + +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) +- `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`. + +--- + +*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 new file mode 100644 index 00000000..cdaa6912 --- /dev/null +++ b/docs/reference/components/handler/computer.md @@ -0,0 +1,230 @@ +--- +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 synchronous, infallible member of the handler family, and the simplest provider to write. + +## Overview + +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 +phantom `Code` tag naming which computation is wanted, and an `Input`, with no failure path. + +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 + +`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]`](../../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`, `ComputerComponent`, and the consumer trait `CanCompute` are all imported from +`cgp::extra::handler`, since the prelude leaves out the handler family. 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. 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`): + +```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 directly and, through promotion, as +a fallible computer: + +```rust +use core::marker::PhantomData; +use cgp::extra::handler::{CanCompute, CanTryCompute, PromoteComputer}; +use cgp::extra::handler::{Computer, ComputerComponent, TryComputer, TryComputerComponent}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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)); +} +``` + +`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 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. 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, so in a module that imports both +`CanCompute` and `Computer`, `App::compute(&App, PhantomData::<()>, 21)` has two candidates: + +```text +error[E0034]: multiple applicable items in scope + --> src/main.rs:25:18 + | +25 | 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 `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 consumer and provider traits are both in scope. + +## 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 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 members. +- [`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`, 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`. + +--- + +*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 new file mode 100644 index 00000000..758ddd14 --- /dev/null +++ b/docs/reference/components/handler/computer_ref.md @@ -0,0 +1,176 @@ +--- +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 +--- + +# `ComputerRef` + +The by-reference member of the handler family: a [`Computer`](./computer.md) that borrows its input. + +## Overview + +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 +returns the `Output` directly with no failure path. + +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 + +`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]`](../../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 + +`ComputerRefComponent`, the provider trait `ComputerRef`, and the 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 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 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::extra::handler::{Computer, ComputerComponent, ComputerRefComponent}; +use cgp::prelude::*; +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, + } +} + +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); +} +``` + +`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 [`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> Computer` +``` + +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. + +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) +- `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`. + +--- + +*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 new file mode 100644 index 00000000..e14f8c6b --- /dev/null +++ b/docs/reference/components/handler/handler.md @@ -0,0 +1,212 @@ +--- +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 +--- + +# `Handler` + +The general computation component: asynchronous and fallible. + +## Overview + +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. + +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 + +`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, 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]`](../../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`, `HandlerComponent`, and the consumer trait `CanHandle` are 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 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`. + +## Examples + +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::extra::handler::{Computer, ComputerComponent, Handler, HandlerComponent}; +use cgp::prelude::*; +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 + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteAsync>, + } +} + +check_components! { + App { + HandlerComponent: ((), u64), + } +} + +pub async fn run_with( + context: &Context, + input: u64, +) -> Result +where + 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 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 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` +``` + +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 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 `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 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 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`. + +--- + +*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 new file mode 100644 index 00000000..c61002c6 --- /dev/null +++ b/docs/reference/components/handler/handler_ref.md @@ -0,0 +1,178 @@ +--- +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. + +## Overview + +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 +that reads its argument rather than consuming it, such as a request handler that inspects a borrowed +request. + +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 + +`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, 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]`](../../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 + +`HandlerRefComponent`, the provider trait `HandlerRef`, and the consumer trait `CanHandleRef` are +not in the prelude, 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 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 + +An async, fallible provider over a borrowed request, wired into a context and awaited: + +```rust +use core::marker::PhantomData; +use cgp::extra::handler::{CanHandleRef, HandlerRef, HandlerRefComponent}; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; + +#[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()) + ); +} +``` + +`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.** 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 member 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 `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 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`. + +--- + +*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 new file mode 100644 index 00000000..03e8b510 --- /dev/null +++ b/docs/reference/components/handler/index.md @@ -0,0 +1,76 @@ +--- +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 + +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 +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 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 of the family is imported from `cgp::extra::handler`: the consumer traits +(`CanCompute`, `CanTryCompute`, `CanHandle`, `CanProduce`, and their siblings), the provider traits, +their wiring keys, the promotion bundles, and the one-step promotion providers. The prelude carries +only the macros that define handlers, `#[cgp_computer]`, `#[cgp_producer]`, and +`#[cgp_auto_dispatch]`. A provider written with `#[cgp_impl]` on `Computer` also needs +`ComputerComponent` in scope, because the macro names the key the trait belongs to, unless its header +names the trait by path, as `impl cgp::extra::handler::Computer`; see +[Importing the component key](../../macros/cgp_impl.md#importing-the-component-key). + +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 +[`#[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). + +--- + +*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 new file mode 100644 index 00000000..9305cef6 --- /dev/null +++ b/docs/reference/components/handler/producer.md @@ -0,0 +1,192 @@ +--- +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 +--- + +# `Producer` + +The input-free member of the handler family: a synchronous, infallible source of a value. + +## Overview + +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 +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. + +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 + +`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]`](../../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`, `ProducerComponent`, and the 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 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 + +A producer wired into a context and invoked directly: + +```rust +use core::marker::PhantomData; +use cgp::extra::handler::{Producer, ProducerComponent}; +use cgp::prelude::*; +use cgp::extra::handler::CanProduce; + +#[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, + } +} + +check_components! { + App { + ProducerComponent: (), + } +} + +pub fn demo() { + assert_eq!(App.produce(PhantomData::<()>), 42); +} +``` + +`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, 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. 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. +- [`#[cgp_producer]`](../../macros/cgp_producer.md) — builds a `Producer` provider from a zero-argument + function. +- [`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: + +- [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) +- `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`. + +--- + +*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 new file mode 100644 index 00000000..5534bec1 --- /dev/null +++ b/docs/reference/components/handler/try_computer.md @@ -0,0 +1,200 @@ +--- +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 +--- + +# `TryComputer` + +The fallible synchronous member of the handler family: a computer that can return an error. + +## Overview + +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 +[**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 + +`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]`](../../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`, `TryComputerComponent`, and the 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 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 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 parse error into the +context's error: + +```rust +use core::marker::PhantomData; +use core::num::ParseIntError; +use cgp::extra::handler::{TryComputer, TryComputerComponent}; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::extra::handler::CanTryCompute; + +#[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) + } +} + +#[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` 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: 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 `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 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: + +- [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) +- `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`. + +--- + +*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 new file mode 100644 index 00000000..42e4e081 --- /dev/null +++ b/docs/reference/components/handler/try_computer_ref.md @@ -0,0 +1,179 @@ +--- +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. + +## Overview + +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 +differs from `TryComputer` on the input axis alone. + +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 + +`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]`](../../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 + +`TryComputerRefComponent`, the provider trait `TryComputerRef`, and the consumer trait +`CanTryComputeRef` are not in the prelude, 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 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 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::extra::handler::{CanTryComputeRef, TryComputerRef, TryComputerRefComponent}; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; + +#[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()); +} +``` + +`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 [`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 `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: + +- [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) +- `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`. + +--- + +*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 new file mode 100644 index 00000000..21651e3d --- /dev/null +++ b/docs/reference/components/has_error_type.md @@ -0,0 +1,196 @@ +--- +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 +--- + +# `HasErrorType` + +Give a context one shared, abstract `Error` type, so fallible generic code never names a concrete error. + +## Overview + +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 +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. + +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](/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. + +## 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](/docs/reference/glossary#component-marker), and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. +- [`#[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 + +`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`. `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}; +use cgp::prelude::*; + +pub fn parse_port>( + _context: &Context, + raw: &str, +) -> Result> { + raw.parse().map_err(|_| format!("bad port: {raw}")) +} + +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 + +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)] +#[use_type(HasErrorType.Error)] +pub trait CanValidate { + fn validate(&self) -> Result<(), Error>; +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} + +check_components! { + App { + ErrorTypeProviderComponent, + } +} +``` + +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](/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 + +**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 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. + +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 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 + 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) +- `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: + [`standalone/error/`](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/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/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md new file mode 100644 index 00000000..52230f70 --- /dev/null +++ b/docs/reference/components/has_runtime.md @@ -0,0 +1,171 @@ +--- +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 generically.' +sidebar_label: 'HasRuntime' +sidebar_position: 6 +--- + +# `HasRuntime` + +Hand out a borrow of the context's runtime value, so effectful code reaches it generically. + +## Overview + +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 +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 +[`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](/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. + +## 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`, 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; +``` + +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 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 + +A context declares its runtime type and the field holding the value, and a provider reaches the runtime +generically: + +```rust +use cgp::core::field::impls::UseField; +use cgp::prelude::*; +use cgp::extra::runtime::{ + HasRuntime, RuntimeGetterComponent, RuntimeOf, RuntimeTypeProviderComponent, +}; + +pub struct TokioRuntime { /* handle, clock, etc. */ } + +#[derive(HasField)] +pub struct App { + pub runtime: TokioRuntime, +} + +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + RuntimeGetterComponent: UseField, + } +} + +check_components! { + App { + RuntimeTypeProviderComponent, + RuntimeGetterComponent, + } +} + +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](/docs/reference/glossary#environmental-context)**, and +the component targets it. + +## 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 +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 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. + +## 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/) + +--- + +*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 new file mode 100644 index 00000000..9bfe9ef2 --- /dev/null +++ b/docs/reference/components/has_runtime_type.md @@ -0,0 +1,143 @@ +--- +title: 'HasRuntimeType — the abstract runtime type' +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 +--- + +# `HasRuntimeType` + +Declare the abstract runtime *type* a context runs against, chosen per context through wiring. + +## Overview + +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. + +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 trait 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](/docs/reference/glossary#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`, 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): + +```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, RuntimeTypeProviderComponent}; + +pub struct TokioRuntime { /* handle, clock, etc. */ } + +pub struct App; + +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + } +} + +check_components! { + App { + RuntimeTypeProviderComponent, + } +} + +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](/docs/reference/glossary#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 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. + +Reach for [`HasRuntime`](./has_runtime.md) instead when a provider actually performs an effect and needs +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. + +## 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 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. + +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/) + +--- + +*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 new file mode 100644 index 00000000..9cefac48 --- /dev/null +++ b/docs/reference/components/has_type.md @@ -0,0 +1,176 @@ +--- +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` + +The tag-indexed abstract-type component: a type per tag that a context resolves through wiring. + +## Overview + +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 +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. + +`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 + +`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`, the provider trait `TypeProvider`, the wiring key `TypeProviderComponent`, and the +`TypeOf` alias all come from `cgp::core::types`; none of them is in the prelude. `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 +reports its own parameter as the abstract type: + +```rust +delegate_components! { + App { + TypeProviderComponent: UseType, + } +} +``` + +**`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. 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::{HasType, TypeOf, TypeProviderComponent}; +use cgp::prelude::*; + +pub struct ScalarTag; + +pub struct App; + +delegate_components! { + App { + TypeProviderComponent: UseType, + } +} + +check_components! { + App { + TypeProviderComponent: ScalarTag, + } +} + +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](/docs/reference/glossary#environmental-context)** here, a type standing for +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 + +**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. 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) — 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 + 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 defines named abstract-type components: + [`cgp_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_type/) + +--- + +*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 new file mode 100644 index 00000000..a73f3d0f --- /dev/null +++ b/docs/reference/components/index.md @@ -0,0 +1,76 @@ +--- +title: 'Component reference' +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 +--- + +# Components + +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 +with the same [`delegate_components!`](../macros/delegate_components.md) table as everything else. + +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 +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 + +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 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 + +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`. 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). + +## 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. + +--- + +*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 new file mode 100644 index 00000000..deba31df --- /dev/null +++ b/docs/reference/components/runner.md @@ -0,0 +1,157 @@ +--- +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 +--- + +# `CanRun` + +Run a task named at the type level to a `Result<(), Error>`, with the behavior chosen through wiring. + +## Overview + +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 +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 +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](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. + +## Usage + +`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>; +``` + +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: + +```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. `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)] +#[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](/docs/reference/glossary#environmental-context)**, and the task is a +type-level `Code` selector the wiring dispatches on. + +## 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 +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/) + +--- + +*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 new file mode 100644 index 00000000..34945c00 --- /dev/null +++ b/docs/reference/components/send_runner.md @@ -0,0 +1,159 @@ +--- +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 +--- + +# `CanSendRun` + +The runner variant whose returned future is `Send`, for work that must cross a thread boundary. + +## Overview + +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. +`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](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. + +## Usage + +`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 +fn send_run(&self, _code: PhantomData) -> impl Future> + Send; +``` + +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: + +```rust +use cgp::extra::run::{CanRun, SendRunner, SendRunnerComponent}; + +#[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. + +`#[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. +`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)] +#[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](/docs/reference/glossary#environmental-context)**, and the task is a +type-level `Code` selector. + +## 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 +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/) + +--- + +*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/_category_.json b/docs/reference/derives/_category_.json new file mode 100644 index 00000000..c0dc9c7d --- /dev/null +++ b/docs/reference/derives/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Derives", + "position": 3, + "link": { + "type": "doc", + "id": "reference/derives/index" + } +} diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md new file mode 100644 index 00000000..7154493c --- /dev/null +++ b/docs/reference/derives/derive_build_field.md @@ -0,0 +1,360 @@ +--- +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)]` + +`#[derive(BuildField)]` generates a struct builder that tracks field presence in its type. + +## Overview + +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. + +`#[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 + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build(); // every field set: closes +``` + +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. + +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 + +Apply `BuildField` to a struct without arguments or 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_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. + +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 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. + +### What it does *not* generate + +`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. + +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 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 an absent field to a value, as shown above. + +**`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() + .build_from(person) // first_name + last_name at once + .build_field(PhantomData::, id) + .finalize_build() +``` + +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`** 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. + +`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 + +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; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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() +} +``` + +The conversion relates `FooBar` and `FooBarBaz` through their field names and types. Neither struct +names the other in its definition. + +The companion's `HasField` implementation allows a field to be read once it has been set: + +```rust +let partial = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()); + +assert_eq!(partial.get_field(PhantomData::), "Alice"); +``` + +Reading `last_name` at this point fails to compile because its field is still absent. + +`into_builder()` and `take_field()` let generic code remove fields from a finished value and rebuild +it: + +```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 use it + +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 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)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +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, +} +``` + +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 { + 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 } + } +} +``` + +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> + 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 + // ... +} +``` + +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 { + type Value = String; + // ... +} +``` + +`BuildField` and `TakeField` are library blanket implementations over `UpdateField`. The derive +generates `UpdateField`, which supports changing a field to a chosen marker. The library supplies +these specific transitions: + +- `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. + +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 + +**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 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 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`. + +**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. + +**`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 +[`#[derive(FromVariant)]`](./derive_from_variant.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(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/builder/has_builder.md) — the builder trait family, including `UpdateField`, `BuildField`, + `TakeField`, and `FinalizeBuild`. +- [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion is + parameterized by. +- [`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. + +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), + [`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) + +--- + +*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 new file mode 100644 index 00000000..e5a399b2 --- /dev/null +++ b/docs/reference/derives/derive_cgp_data.md @@ -0,0 +1,213 @@ +--- +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)]` + +`#[derive(CgpData)]` generates structural access and incremental operations for a struct or enum. + +## Overview + +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, +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 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 + +Apply `CgpData` to a struct or enum without arguments or helper attributes: + +```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_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 + +`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) | + +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 + +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)]`**: 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. + +Use a shape-specific derive when its name documents a constraint on the type. It rejects the wrong +shape at the derive. + +## Examples + +One derive covers both halves of a program that builds records and takes enums apart: + +```rust +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), +} +``` + +`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 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 method runs on, 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 + +`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. + +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 + +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. +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 +`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. + +**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. + +**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. +- [`#[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/builder/has_builder.md) and [`ExtractField`](../traits/variant/extract_field.md) — the two + 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 are explained on these concept pages: + +- [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 + +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) + 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) + +--- + +*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 new file mode 100644 index 00000000..f7553c52 --- /dev/null +++ b/docs/reference/derives/derive_cgp_record.md @@ -0,0 +1,226 @@ +--- +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)]` + +`#[derive(CgpRecord)]` generates field access, a structural representation, and a builder for a struct. + +## Overview + +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 +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. + +`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 with +``expected `struct` ``. + +## Usage + +Apply `CgpRecord` to a struct without arguments or helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(CgpRecord)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +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 +the companion type. + +### What it generates + +The derive combines these outputs, each also available separately: + +| 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 + +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; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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 +} +``` + +`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 + +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 generates field access, representation traits, and a builder for the input struct: + +```rust +#[derive(CgpRecord)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +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). + +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 { + type Fields = Product![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +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 +///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, +} + +impl HasBuilder for Person { + type Builder = __PartialPerson; // the empty builder + // ... +} + +impl FinalizeBuild for __PartialPerson { + // ... only at all-present +} +``` + +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 +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 + +**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::>`. + +**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 has an immediately finalizable builder.** Its companion does not need field-state +parameters. + +**`CgpRecord` rejects enums.** Use [`CgpVariant`](./derive_cgp_variant.md) or +[`CgpData`](./derive_cgp_data.md) for an enum. + +**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 + [`#[derive(BuildField)]`](./derive_build_field.md) — the three slices this emits. +- [`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/casting/can_build_from.md) — merging one record into another's builder. + +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) + +--- + +*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 new file mode 100644 index 00000000..16e0b7a1 --- /dev/null +++ b/docs/reference/derives/derive_cgp_variant.md @@ -0,0 +1,271 @@ +--- +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)]` + +`#[derive(CgpVariant)]` generates a structural representation, constructors, and an extractor for an enum. + +## Overview + +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 +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. + +`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 with +``expected `enum` ``. + +## Usage + +Apply `CgpVariant` to an enum without arguments or 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 one unnamed payload or none + +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: + +```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), +} +``` + +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. + +[`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 + +The derive combines these outputs, each also available separately: + +| 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 + +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::{ExtractField, FinalizeExtractResult, HasExtractor}; +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 + } + } +} +``` + +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 + +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: + +- **`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 [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 generates representation traits, constructors, and an extractor for the input enum: + +```rust +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +The representation describes the enum as a sum of named variants: + +```rust +impl HasFields for Shape { + type Fields = Sum![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +The constructor output contains an implementation per variant, as documented for +[`#[derive(FromVariant)]`](./derive_from_variant.md): + +```rust +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Circle) -> Self { + Self::Circle(value) + } +} +``` + +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 +///The partial extractor for [`Shape`]. +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 + // ... +} +``` + +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 +hand-written impl underlines that variant rather than the whole derive. + +## Common Mistakes + +**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. + +**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!`. + +**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 is accepted.** It produces empty companion enums without field-state parameters. + +**`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), + and [`#[derive(ExtractField)]`](./derive_extract_field.md) — the three slices this emits. +- [`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/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. + +The ideas behind it are explained on these concept pages: + +- [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 + +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) + +--- + +*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 new file mode 100644 index 00000000..81d3d17b --- /dev/null +++ b/docs/reference/derives/derive_extract_field.md @@ -0,0 +1,384 @@ +--- +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)]` + +`#[derive(ExtractField)]` generates an enum extractor that tracks remaining variants in its type. + +## Overview + +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 +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::) { + Ok(circle) => /* it was a Circle */, + Err(remainder) => /* it wasn't; `remainder` can no longer be a Circle */, +} +``` + +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. + +[`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 + +Apply `ExtractField` to an enum without arguments or 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. + +The derive comes with the prelude, but the traits it implements do not. Code that calls +`to_extractor`, `extract_field`, or `finalize_extract` imports `HasExtractor`, `ExtractField`, or +`FinalizeExtract` from `cgp::core::field::traits`, and the borrowed extractors need +`HasExtractorRef` or `HasExtractorMut` from the same module. + +### Every variant needs one unnamed payload or none + +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: + +```rust +// rejected: `Circle` has named fields, so it has no single payload type +pub enum Shape { + Circle { radius: f64 }, + Empty, +} + +// accepted: `Circle` carries one payload type, and `Empty` carries `Nil` +pub struct Circle { + pub radius: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Empty, +} +``` + +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 +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 with ``expected `enum` ``. The +struct analogue is +[`#[derive(BuildField)]`](./derive_build_field.md). + +### What it does *not* generate + +`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 + +Choose an extractor according to how the operation needs to access the payload: + +- **`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. + +Each form supports the same `extract_field` chain. `from_extractor` converts an all-present owned +extractor back into the original enum. + +## Examples + +`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::{ExtractField, FinalizeExtractResult, HasExtractor}; +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 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. + +`extractor_ref()` lets the operation read a payload while preserving the original value: + +```rust +let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); +``` + +`extractor_mut()` lets the operation modify a payload in place: + +```rust +if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) +{ + circle.radius = 5.0; +} +``` + +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 + +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 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 + +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)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +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>>), +} +``` + +`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 { + 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> +``` + +`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 { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} + } +} +``` + +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 { + type Value = Circle; + type Remainder = __PartialShape; // Circle ruled out; __F1__ untouched + + fn extract_field(self, _: PhantomData) -> Result>::Remainder> { + match self { + __PartialShape::Circle(value) => Ok(value), + __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), + } + } +} +``` + +Extractions can run in any order because each step changes only its own variant's marker. The other +markers remain generic. The borrowed companion receives equivalent implementations, so borrowed +extraction narrows the remainder in the same way. + +`FinalizeExtract` and its companion `FinalizeExtractResult` are library traits; the derive supplies only the +all-void impl. `finalize_extract_result` calls `FinalizeExtractResult` to collapse a +`Result` into `T`. + +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 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 +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. + +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. + +**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`. + +**The extractor traits are not in the prelude.** Import `FinalizeExtractResult` from +`cgp::core::field::traits` to call `finalize_extract_result`, as you import `HasExtractor`, +`ExtractField`, and `FinalizeExtract` from there to call their methods. + +**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 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. + +**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. +- [`#[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/variant/extract_field.md) — the extractor trait family, including `HasExtractor`, + `FinalizeExtract`, and `FinalizeExtractResult`. +- [`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 lists](../types/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. + +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. +- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles 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) + and [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.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/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md new file mode 100644 index 00000000..e6fb128b --- /dev/null +++ b/docs/reference/derives/derive_from_variant.md @@ -0,0 +1,266 @@ +--- +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)]` + +`#[derive(FromVariant)]` lets generic code construct an enum variant selected by a type-level tag. + +## Overview + +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 +tag: + +```rust +Shape::from_variant(PhantomData::, circle) +``` + +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. + +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 + +Apply `FromVariant` to an enum without arguments or 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. + +The derive comes with the prelude, but the `FromVariant` trait it implements does not, so code that +calls `from_variant` imports the trait from `cgp::core::field::traits`. + +### Every variant needs one unnamed payload or none + +Every variant must contain exactly one unnamed field, whose type becomes the constructor's payload +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: + +```rust +pub struct Circle { + pub radius: f64, +} + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), +} +``` + +[`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 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 + +`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 + +A function can use `FromVariant` to stay generic over the variant it constructs: + +```rust +use cgp::core::field::traits::FromVariant; +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) +} +``` + +`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 }); +``` + +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. + +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 + +let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); +``` + +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 + +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 `FromVariant` implementation per variant. For this input: + +```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: >::Value) -> Self { + Self::Circle(value) + } +} + +impl FromVariant for Shape { + type Value = Rectangle; + + fn from_variant(_tag: PhantomData, value: >::Value) -> Self { + Self::Rectangle(value) + } +} +``` + +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. + +`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 +underlines that variant rather than the whole `#[derive(FromVariant)]`. + +## Common Mistakes + +**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 +`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. + +**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 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. +- [`#[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/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 lists](../types/index.md) — the `Either`/`Void` chain the constructed variants + correspond to. + +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) + +--- + +*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 new file mode 100644 index 00000000..494d14b6 --- /dev/null +++ b/docs/reference/derives/derive_has_field.md @@ -0,0 +1,356 @@ +--- +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)]` + +`#[derive(HasField)]` generates shared and mutable field accessors keyed by type-level tags. + +## Overview + +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. + +`#[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 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. + +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 + +Apply `HasField` to a struct without arguments or helper attributes: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +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](/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 +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 + +Tuple fields use [`Index`](../types/index_type.md) tags, where `N` is the field's zero-based +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, because `Index<0>` and `Symbol!("0")` are different types. + +### Unit structs + +A unit struct is accepted without generating accessors because it has no fields: + +```rust +#[derive(HasField)] +pub struct App; +``` + +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 + +The generated implementations preserve generic parameters, lifetimes, and the struct's `where` +clause: + +```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 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. + +## Examples + +An implementation declares the field it needs as a bound. Here, `GreetHello` requires a `String` +field named `name`: + +```rust +use cgp::core::field::traits::HasField; +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::)); + } +} +``` + +`Person` supplies the field access and selects `GreetHello` as its implementation: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + 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. + +An [`#[implicit]`](../attributes/implicit.md) argument expresses the field dependency as a function +parameter: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} +``` + +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 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](/docs/reference/glossary#blanket-implementation). + +## When to use it + +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](/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 + 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](/docs/reference/glossary#extensible-record). + +## Under the hood + +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, +} +``` + +Each generated accessor uses the declared field type as `Value` and returns a reference to the field: + +```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` +``` + +`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: + +```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 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. + +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 does not generate field-access implementations.** The derive succeeds, but a later +field read reports an unsatisfied `HasField` bound. + +**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. + +**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.** 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::macro_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. + +## 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 + `FieldGetter`. +- [`Symbol!`](../macros/symbol.md) — the tag for a named 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. +- [`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 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. +- [Extensible records](/docs/concepts/extensible-records) — treating a struct as a product of named fields. + +## 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) + and [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.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/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md new file mode 100644 index 00000000..5ab73c45 --- /dev/null +++ b/docs/reference/derives/derive_has_fields.md @@ -0,0 +1,346 @@ +--- +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)]` + +`#[derive(HasFields)]` generates a structural representation and conversions for a struct or enum. + +## Overview + +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`. +[`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![ + Field, + Field, +]; +``` + +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 supplies conversions to and from the representation. Generic code can decompose a +concrete value, process its structural form, and reconstruct the concrete type. + +## Usage + +Apply `HasFields` to a struct or enum without arguments or helper attributes: + +```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_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 + +Every struct shape is accepted, with its representation determined by its fields: + +- **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. + +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 + +`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 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)] +pub enum Shape { + Empty, + Circle(u32), + Rectangle(u32, u32), + Triangle { base: u32, height: u32 }, +} +``` + +The variants above map to these entries in the sum: + +| Variant | Its entry in the sum | +|---|---| +| `Empty` | `Field` | +| `Circle(u32)` | `Field` | +| `Rectangle(u32, u32)` | `Field, u32>, Field, u32>]>` | +| `Triangle { base, height }` | `Field, Field]>` | + +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. + +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 + +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]`. +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 }; + +let fields = config.to_fields(); // Config -> the product +let config_again = Config::from_fields(fields); // the product -> Config +``` + +`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 }; + +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]`, +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 +that supplies the same traits. + +## When to use it + +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 preserves the type definition and adds implementations of `HasFields`, `HasFieldsRef`, +`ToFields`, `FromFields`, and `ToFieldsRef`. For this named-field struct: + +```rust +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +The shape implementations name the product and its borrowed counterpart: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} + +impl HasFieldsRef for Person { + type FieldsRef<'__a> = Product![ + Field, + Field, + ] + where + Self: '__a; +} +``` + +The conversion implementations move or borrow values between `Person` and that product: + +```rust +impl ToFields for Person { + 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)): ::Fields) -> Self { + Self { name: name.value, age: age.value } + } +} + +impl ToFieldsRef for Person { + fn to_fields_ref<'__a>(&'__a 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 lists](../types/index.md) page covers that shape, and it is the form printed in +an error. + +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 { + type Fields = Either< + Field, + Either, Void>, + >; +} +``` + +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. + +A unit struct uses the empty product `Nil` as its representation: + +```rust +impl HasFields for Unit { + type Fields = Nil; +} +``` + +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)]`. + +## 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 +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.** 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` +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. + +**`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 + 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. +- [`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 + 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. + +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. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the expression problem it + addresses. + +## 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), + [`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) + +--- + +*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/index.md b/docs/reference/derives/index.md new file mode 100644 index 00000000..84440810 --- /dev/null +++ b/docs/reference/derives/index.md @@ -0,0 +1,76 @@ +--- +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 + +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 +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. 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 +[`#[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](/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`. + +## Turning a type into extensible data + +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 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) 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 + +Use an individual derive when generic code needs only construction or extraction. + +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. + +## Restrictions to know before you reach for them + +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. 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. + +--- + +*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 new file mode 100644 index 00000000..2d3a0cb9 --- /dev/null +++ b/docs/reference/errors.md @@ -0,0 +1,786 @@ +--- +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 the compiler reports after macro expansion in code written with +[Context-Generic Programming (CGP)](/docs/), 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. + +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/tooling/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. + +`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. + +## The one distinction that explains everything + +**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**](/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. + +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` … `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, or a provider header's component not imported | [A wiring name that resolves to nothing](#a-wiring-name-that-resolves-to-nothing) | +| `E0107` missing generics for struct `…Component` | A component key with parameters, derived by a provider header | [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) | +| `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` 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 + +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::*; + +#[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. Adding a check at the wiring site +and checking it: + +```text +error[E0277]: [CGP-E001] missing field `name` on `Person` + --> src/main.rs:34:9 + | +34 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ + | + = 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-E104] trait impl `HasName` for `Person` + └─ [CGP-E110] missing field `name` on `Person` + = help: add the field `name: String` to `Person` +``` + +**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 same headline and 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` 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 + | +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. 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 +`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 +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 +`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: + +```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` + └─ [CGP-E117] 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 ``. + +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-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` +``` + +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 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, +`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-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-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 +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, and only some of them reach the cause. + +The tool collapses the whole cascade into one block over a single cause, marking each affected check entry: + +```text +error[E0277]: [CGP-E001] missing field `name` on `App` + | +56 | BazProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^ +57 | BarProviderComponent, + | -------------------- also required here +58 | FooProviderComponent, + | -------------------- also required here + | + = note: root cause: [CGP-E110] 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**, 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: 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 +`#[default_impl]`, namespace entry, or direct wiring puts a provider there: + +```text + = 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-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-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. + +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 the cause does not need hunting 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-E010] conflicting wiring: `Person` wires component `GreeterComponent` twice + | +22 | GreeterComponent: GreetHello, + | ---------------- first implementation here +23 | GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `Person` +``` + +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 +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** 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]`. + +A provider header names a component too, without writing it. `#[cgp_impl]` and `#[cgp_provider]` +derive the key from the provider trait's path, so `impl Greeter` names `GreeterComponent`, and a +provider in another module than its component imports the key beside the trait or names the trait +by its path, as [Importing the component key](./macros/cgp_impl.md#importing-the-component-key) +shows. A missing import +is an `E0425` on the trait's name, which the tool words as `[CGP-E041]` with the import. A trait +imported under another name, or a component whose `name:` renames its key or gives it parameters, +derives a name that is not the component's, which the tool words as `[CGP-E070]`, naming the key in +the attribute, as `#[cgp_impl(new UnitArea: AreaComponent)]`. + +### 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-E012] conflicting wiring: `App` joins both `NamespaceA` and `NamespaceB`, but a target type in `delegate_components!` can join only one namespace + | +15 | namespace NamespaceA; + | ---------- first implementation here +16 | 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-E011] conflicting wiring: `App` wires `@app.GreeterComponent`, which `AppNamespace` already covers + | +29 | namespace AppNamespace; + | ------------ first implementation here +30 | +31 | @app.GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^^^^^ 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, is rewritten the same +way: + +```text +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` ``, +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-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` +``` + +### 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-E022] 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, 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 + +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-E020] the wiring for the consumer trait `CanGreet` on context `Person` never resolves, because the lookup leads back to itself + | +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, 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`, 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 +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]: [CGP-E019] the entry for `GreeterComponent` in the wiring of `App` binds `T`, but its key does not use it + | +21 | GreeterComponent: GreetWith, + | ^ + | + = help: write a concrete type in place of `T` in `GreetWith`, and remove `T` from the entry's generic parameters +``` + +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 + +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` + | +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. 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 + +[`#[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 + | +37 | pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { + | ^^ use of undeclared type `Db` +``` + +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, 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` + | +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 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 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 + | +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` +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`, read as `Option<&PathBuf>`, or a +hand-written getter naming whatever type the field actually has. + +## 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 trait used without `#[uses]`:** + +```text +error[E0599]: [CGP-E030] the trait `GetCount` is used but not declared as a dependency + | +16 | 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-E031] the inner provider `InnerCalculator` is used but not imported + | +11 | 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. + +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 +where the provider trait belongs gives it one generic argument too many, because the macro inserts the +context: + +```text +error[E0107]: [CGP-E032] `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-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`. + +### 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. + +## 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 as `[CGP-E050]`, 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 +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/tooling/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 + +- [`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/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/wiring/can_use_component.md) — what a check asserts. +- [`cargo cgp check`](/docs/tooling/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<…>` list 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. + +--- + +*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/glossary.md b/docs/reference/glossary.md new file mode 100644 index 00000000..94c2cdf1 --- /dev/null +++ b/docs/reference/glossary.md @@ -0,0 +1,596 @@ +--- +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 the documentation of +[Context-Generic Programming (CGP)](/docs/), 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, such as `IsPresent` or +`#[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 does not carry 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; a check trait does that. + +[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/tooling/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 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) · +[`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`. Getters are self-targeted too. + +[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 +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 without a 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. + +[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 + +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, 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. 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) + +### 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) · +[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 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) + +--- + +*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 new file mode 100644 index 00000000..376f7916 --- /dev/null +++ b/docs/reference/index.md @@ -0,0 +1,283 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +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 + +This is the complete reference for every construct of [Context-Generic Programming (CGP)](/docs/): +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. 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 + +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 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 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. + +### 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 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 + +[`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/wiring/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/field-access/has_field.md) trait, whose mutable form is +[`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; +[`#[cgp_getter]`](./macros/cgp_getter.md) makes the getter a full component so the field it reads is +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. + +### 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 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, 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 +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, 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 + +[`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, 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. +[`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. `Computer`, +`TryComputer`, and `Handler` also have by-reference siblings, and `Computer` has async ones: +[`ComputerRef`](./components/handler/computer_ref.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. + +### 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, 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 traits, and the traits are where the operations live. The whole-shape view is +[`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/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 +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/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 + +[`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 +[`#[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 +[`#[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 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, 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. +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), +[`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. + +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. 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) | +| `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) | +| `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`, `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) | + +--- + +*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/_category_.json b/docs/reference/macros/_category_.json new file mode 100644 index 00000000..192379c3 --- /dev/null +++ b/docs/reference/macros/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Macros", + "position": 1, + "link": { + "type": "doc", + "id": "reference/macros/index" + } +} diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md new file mode 100644 index 00000000..eb14f3ba --- /dev/null +++ b/docs/reference/macros/async_trait.md @@ -0,0 +1,295 @@ +--- +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]` + +Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` form that the library's async traits use. + +## Overview + +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: + +```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 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). + +## Usage + +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), the conventional placement is **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>; +} +``` + +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/main/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: + +```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, + } +} + +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 +method. + +## When to use it + +**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. +- **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 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. +- **Use the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an + 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 + +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; +} +``` + +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. + +**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 +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: + +```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. + +## 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 +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 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. + +**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/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. + +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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..330a4003 --- /dev/null +++ b/docs/reference/macros/blanket_trait.md @@ -0,0 +1,330 @@ +--- +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]` + +Generate a blanket impl from a trait with default methods and [supertrait](/docs/reference/glossary#supertrait) dependencies. + +## Overview + +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 +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 +the cascade at one level. + +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 +#[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](/docs/reference/glossary#component-marker), and no wiring: +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). + +## Usage + +`#[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 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 +#[blanket_trait(Ctx)] +pub trait FooBar: Foo + Bar { /* ... */ } +``` + +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 + +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`. 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 use it + +**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 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]`, 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. +- **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: 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 + +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 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: + +```rust +impl<__Context__> FooBar for __Context__ +where + __Context__: Foo + Bar, +{} +``` + +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 +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 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. 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 + +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. + +## 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: + +```text +error: cannot find attribute `blanket_trait` in this scope +``` + +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 +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, +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 +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: + +```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 + +- [`#[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/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. + +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. +- [Modularity Hierarchy](/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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..a76fa1f5 --- /dev/null +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -0,0 +1,376 @@ +--- +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]` + +Generate a handler that dispatches over an extensible-data input from a per-type trait. + +## Overview + +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] +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/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. + +**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 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. + +## Usage + +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] +pub trait HasArea { + fn area(&self) -> f64; +} +``` + +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 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. + +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. 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 use it + +**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. + +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 + [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. +- **A method needs to be generic.** Not supported, and not fixable by rearranging: see the + [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. + +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 + +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 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)] +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 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: + +```rust +impl<__Variants__> HasArea for __Variants__ +where + MatchWithValueHandlersRef: + for<'__a__> Computer<(), (), &'__a__ __Variants__, Output = f64>, + __Variants__: HasExtractor, +{ + fn area(&self) -> f64 { + as Computer<_, _, _>>::compute( + &(), + PhantomData::<()>, + self, + ) + } +} +``` + +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 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. + +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 { + as Computer<_, _, _>>::compute( + &(), + PhantomData::<()>, + (self, (arg_0, arg_1)), + ) +} +``` + +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 + +**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/index.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 +``` + +**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`*. + +**An attribute argument is rejected**, with +`` `#[cgp_auto_dispatch]` takes no arguments ``. The macro has nothing to configure. + +**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 +`__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. [`cargo cgp check`](/docs/tooling/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 +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 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/tooling/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 +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` +``` + +**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 + 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/handler/computer.md) — the component the generated bound is written against. +- [`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. + +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: [`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/) + +--- + +*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 new file mode 100644 index 00000000..0c1a4428 --- /dev/null +++ b/docs/reference/macros/cgp_auto_getter.md @@ -0,0 +1,433 @@ +--- +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]` + +Define a getter as a blanket impl over `HasField`, keyed by the method name. + +## Overview + +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: + +```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. + +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](/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](/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). + +## 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: + +```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_ref()` | +| `&[T]` | any `'static` type implementing `AsRef<[T]>` | `.as_ref()` | +| `Option<&T>` | `Option` | `.as_ref()` | +| `Option<&str>` | `Option` | `.option_as_ref()` | +| [`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, through `HasFieldMut`, and each reference form has a mutable +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*. + +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 +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 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. + +### 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)`. 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. This 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 with +*getter method must contain exactly one `&self` argument*. + +### 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 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 + +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 use it + +**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 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, + 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](/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. + +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. 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 cases above, and +`#[cgp_getter]` only for per-context field choice. + +## Under the hood + +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_ref() + } +} +``` + +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](/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_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: + +```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 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. + +## 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 +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. + +**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**, and neither is `Option<&dyn Trait>`. The macro rejects +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<&[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 +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. + +**`#[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 +must live in a namespace, or dispatch per type, is a [`#[cgp_getter]`](./cgp_getter.md) component. + +## 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/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 + 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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..8c877147 --- /dev/null +++ b/docs/reference/macros/cgp_component.md @@ -0,0 +1,624 @@ +--- +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]` + +Turn a trait into a component: the consumer trait callers use, the provider trait implementations +target, and the key that wires them together. + +## Overview + +`#[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 +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. + +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 fetch its stored objects from Amazon S3 or +from a local folder 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 +implementation no longer target the same trait. + +- 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 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 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 +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 + +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. 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: + +```rust +#[cgp_component { + name: AreaCalculatorComponent, + provider: AreaCalculator, + context: Context, +}] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +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 | +|---|---|---| +| `provider` | The provider trait's name | *required* | +| `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 +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). + +### Where the component key lives + +The macro declares the component key beside the two traits, in the module that defines the +component, so code in other modules imports the key along with them. A wiring table names the key +directly. A provider written with [`#[cgp_impl]`](./cgp_impl.md) names it without writing it, +deriving it from the provider trait's name, so that provider imports the key beside the trait, as +[Importing the component key](./cgp_impl.md#importing-the-component-key) shows. A module that +re-exports a component for other code to use should re-export its key in the same `use`: + +```rust +pub mod shapes { + pub use crate::components::{AreaCalculator, AreaCalculatorComponent, CanCalculateArea}; +} +``` + +A provider elsewhere then writes `use crate::shapes::{AreaCalculator, AreaCalculatorComponent};`. +The generated provider trait's documentation names its key, so hovering the trait in that `use` line +shows which key to import. A key that `name:` renames, such as `name: AreaComponent`, or gives +parameters is not the name a provider header derives, so each provider names it in its attribute, +as `#[cgp_impl(new UnitArea: AreaComponent)]`. + +### 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. `#[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 | +|---|---| +| [`#[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 | + +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 +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +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 without an associated type to import, use `#[extend(...)]` in preference to native +`: 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`. + +The `open` statement of [`delegate_components!`](./delegate_components.md) supersedes +`#[derive_delegate(...)]`, so you mostly read it in existing code rather than write it. + +`#[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 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 + +A component, a provider for it, and a type that wires the two together and checks the wiring: + +```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, + } +} + +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. 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 + +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 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. +- **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. + +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 +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](/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 +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 +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 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 +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. 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 + +From this input: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +the macro emits the items below. The **consumer trait** comes out unchanged: + +```rust +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +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". The supertrait's third argument is a +tuple of the component's extra type parameters, empty here: + +```rust +pub trait AreaCalculator: + IsProviderFor +{ + fn area(context: &Context) -> f64; +} +``` + +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 +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 +pub trait Greeter: IsProviderFor +where + Context: HasName, +{ + fn greet(context: &Context); +} +``` + +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 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. +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. + +This is why an **empty provider impl** is meaningful, and it is how +[`UseDefault`](../providers/use_default.md) works. `UseDefault` is not in the prelude; import it from +`cgp::core::component`: + +```rust +#[cgp_impl(UseDefault)] +impl Greeter for Context {} +``` + +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 +where + Context: AreaCalculator, +{ + fn area(&self) -> f64 { + Context::area(self) + } +} +``` + +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 +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 +placement carries a provider's dependencies along the delegation chain, so they still appear in an +error message. + +The **component marker** is the key wiring uses: + +```rust +pub struct AreaCalculatorComponent; +``` + +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. + +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. 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. 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 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. + +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`. 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 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 | +|---|---|---| +| `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)` | + +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 +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 ( `<` 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. 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, 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 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 +`{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. + +## Common Mistakes + +**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 +``` + +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. + +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. 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 `ref` +binding, a binding with a subpattern, or a destructuring pattern such as `(a, b): (u32, u32)` in a default +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. 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 +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 +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. +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 + +- [`#[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), + [`#[derive_delegate]`](../attributes/derive_delegate.md), and [`#[prefix]`](../attributes/prefix.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. +- [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — when a component is the right tier, + 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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..da3cb88b --- /dev/null +++ b/docs/reference/macros/cgp_computer.md @@ -0,0 +1,369 @@ +--- +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]` + +Define a `Computer` provider from a plain function. + +## Overview + +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. + +`#[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 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 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 + +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`, 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: + +- **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 `()`. 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 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. + +### 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 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: 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 + +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, + } +} + +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. + +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 use it + +**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`. +- **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](/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. +- **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 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. + +## Under the hood + +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] +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) declares `pub struct Add;` and derives the +[`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. + +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. [`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 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. + +## 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 +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. 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, is rejected, since +the macro cannot tell what it names: + +```text +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. + +**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*. + +**`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 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: 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`. + +**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/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. +- [`#[cgp_impl]`](./cgp_impl.md) — for a handler provider that needs its context. +- [`#[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. + +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: [`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) + +--- + +*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 new file mode 100644 index 00000000..e292e518 --- /dev/null +++ b/docs/reference/macros/cgp_fn.md @@ -0,0 +1,389 @@ +--- +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]` + +Define a trait with a single [blanket implementation](/docs/reference/glossary#blanket-implementation), straight from a function. + +## Overview + +`#[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: + +```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()`. 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. + +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 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 +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. + +## 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 +`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. 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: + +```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 + +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, 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 you need 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)]`](../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 +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 +#[cgp_fn] +pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar +where + Scalar: Mul + Copy, +{ + factor * factor +} +``` + +`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(...)]`](../attributes/impl_generics.md). +The parameter goes on the impl alone, so the trait stays unparameterized and callers never mention it: + +```rust +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn describe(&self, #[implicit] name: &Name) -> String { + format!("{name}") +} +``` + +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 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](/docs/reference/glossary#abstract-type) instead. + +### 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 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](/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. +- [`#[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 + 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: 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: + +```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 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. `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 + +**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 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 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 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 +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 +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 trait built on it, declare the parameter and repeat its bounds whether +they touch it or not. + +## Under the hood + +`#[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/field-access/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 + } +} +``` + +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](/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_ref()` instead, which borrows any field implementing `AsRef`, 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 +bound: + +```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, and each lands in a fixed place: + +- `#[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 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 +`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**, so `#[allow(...)]` carries onto the trait and the impl alike. A doc comment on the function +documents the trait's method instead, and the trait gets a generated line naming the operation. + +## 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. + +## Common Mistakes + +**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 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 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 +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 + +- [`#[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` trait method is declared. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the `where`-clause injection + this macro is built on. +- [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — the hierarchy 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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..daf67372 --- /dev/null +++ b/docs/reference/macros/cgp_getter.md @@ -0,0 +1,360 @@ +--- +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]` + +Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name. + +## Overview + +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. + +`#[cgp_getter]` removes that coupling by making the getter a real component. The **context** is the +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 +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]`.** 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 +need neither. The [When to use it](#when-to-use-it) section draws the line. + +## Usage + +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); +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] +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. +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]`: + +```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]`. + +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: + +| 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 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 +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::core::field::impls::UseField; +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()); +} +``` + +`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. `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, + } +} +``` + +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 use it + +**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. +2. **[`#[cgp_auto_getter]`](./cgp_auto_getter.md)** when the accessor has to exist as a *named + 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 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. + +Use something else in these cases. + +- **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 + 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 + +`#[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, 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: + +```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_ref() + } +} +``` + +**`__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_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: + +```rust +impl<__Context__> NameGetter<__Context__> for UseFields +where + __Context__: HasField, +{ + fn name(__context__: &__Context__) -> &str { + __context__.get_field(PhantomData::).as_ref() + } +} +``` + +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_ref() + } +} +``` + +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. + +## 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. + +## 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 +`UseField` therefore reports the provider as not being a provider for the component, +with the tag expanded into its raw list: + +```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. + +**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 +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 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 macro rejects the second. + +## 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/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. +- [`#[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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..fd3ece71 --- /dev/null +++ b/docs/reference/macros/cgp_impl.md @@ -0,0 +1,584 @@ +--- +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]` + +Write a provider using consumer-trait syntax, keeping `self`, `Self`, and the method signatures you +already know. + +## Overview + +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 +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 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 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 +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)] +#[uses(HasDimensions)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.width() * self.height() + } +} +``` + +Write providers this way. The macro performs the rewrite for you and produces the form shown earlier, +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 +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 the parts +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 { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * 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 which component this provider is registered as implementing. Defaults to the provider trait's path with `Component` appended. | + +The default component follows the path you name the trait by. The header `impl AreaCalculator` +registers the provider for `AreaCalculatorComponent`, which must be in scope beside the trait. The +header `impl crate::shapes::AreaCalculator` registers it for +`crate::shapes::AreaCalculatorComponent`, so that module needs no import of the key. +[Importing the component key](#importing-the-component-key) shows what this means for a provider in +another module. + +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`. 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 +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](/docs/concepts/higher-order-providers) 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 + } +} +``` + +### Importing the component key + +A provider in a different module from its component needs the component's key as well as its +provider trait. The header names the key without writing it, so +importing the trait alone is not enough. One `use` line brings in both: + +```rust +mod providers { + use cgp::prelude::*; + + use crate::components::{AreaCalculator, AreaCalculatorComponent}; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } +} +``` + +You need not remember the key's name. Hover over `AreaCalculator` in the `use` line, and the +trait's documentation ends by naming the component key a provider imports beside it. Or skip the +import and name the trait by its path, as `impl crate::components::AreaCalculator`, which derives +`crate::components::AreaCalculatorComponent` for you. A module that re-exports a provider trait for +other code to implement should re-export the key in the same line, +`pub use crate::components::{AreaCalculator, AreaCalculatorComponent};`, so that both forms work +through it as well. The rule is the same for a component from a library: a provider on CGP's own +[`Computer`](../components/handler/computer.md) imports `ComputerComponent` beside it from +`cgp::extra::handler`. + +Without the key's import, the compiler reports the missing key on the trait's name in the header, as +*cannot find type `AreaCalculatorComponent` in this scope*. For a component in your own crate, +`cargo check` suggests the import, which rust-analyzer offers as a quick fix on the module's first +`use` line. For a component from a library, stable Rust suggests no import. +[`cargo cgp check`](/docs/tooling/cargo-cgp/check) names the import for a component of your crate or of a +library: + +```text +error[E0425]: [CGP-E041] the component `AreaCalculatorComponent` is not in scope + --> src/main.rs:16:10 + | +16 | impl AreaCalculator { + | ^^^^^^^^^^^^^^ + | +help: import the component + | +11 + use crate::components::AreaCalculatorComponent; + | +``` + +The fix is a suggestion that an editor running `cargo cgp check` offers on the trait's name, as +[Editor integration](/docs/tooling/cargo-cgp/editor-integration#importing-a-component-key) describes. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. + +A key the header cannot derive goes in the `: ComponentType` part, and that key must be in scope +too. That covers a trait imported under another name, as in +`use crate::components::AreaCalculator as Area;`, and a component whose `name:` renames its key or +gives it parameters, as [`#[cgp_component]`](./cgp_component.md#where-the-component-key-lives) +shows. `cargo cgp check` reports those headers as +[`[CGP-E070]`](/docs/tooling/cargo-cgp/error-codes#cgp-e070) and offers to write the part for you, importing +the key when the module lacks it. + +### Declaring the provider struct separately + +`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 +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. + +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, 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 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 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. 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](/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 +way, `new` cannot express it, and you must declare the struct by hand instead: + +```rust +pub struct ScaledAreaCalculator(PhantomData); +``` + +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 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 + +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. +- [`#[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](/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](/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). + +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 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). 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 + +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. 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, 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)] +#[use_provider(RectangleArea: AreaCalculator)] +impl CanCalculateArea for Rectangle { + fn area(&self) -> f64 { + RectangleArea::area(self) + } +} +``` + +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` +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 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, checks the wiring, and calls +through it: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +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 +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. 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 +[`#[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 does not produce a provider at all. + +Use something else in these cases: + +- **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 + [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion + 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 +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 + +`#[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() + } +} +``` + +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 { + fn foo(__context__: &Context, value: u32) -> String { + value.to_string() + } +} + +impl IsProviderFor for ValueToString {} + +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 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 +`RectangleArea` provider from the [Overview](#overview) expands to: + +```rust +impl<__Context__> AreaCalculator<__Context__> for RectangleArea +where + __Context__: HasDimensions, +{ + fn area(__context__: &__Context__) -> f64 { + __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 +`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 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` +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 + +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 path with `Component` appended to its last segment. Both are Rust +`Type` productions. + +## Common Mistakes + +**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 `::` +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 `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 +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 +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. 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 + +- [`#[cgp_component]`](./cgp_component.md) — defines the component this implements. +- [`#[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. +- [`#[implicit]`](../attributes/implicit.md), [`#[uses]`](../attributes/uses.md), + [`#[use_type]`](../attributes/use_type.md), [`#[use_provider]`](../attributes/use_provider.md), + [`#[default_impl]`](../attributes/default_impl.md) — the companion attributes. + +The ideas behind it: + +- [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. + +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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..51e211b5 --- /dev/null +++ b/docs/reference/macros/cgp_namespace.md @@ -0,0 +1,475 @@ +--- +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!` + +Define a reusable, inheritable wiring table that many contexts can join. + +## Overview + +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 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! { + 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 fill the paths the namespace leaves open, so a +namespace behaves like a base configuration each context completes: most of the wiring for free, and a +handful of choices where they matter. A context cannot replace an entry the namespace binds; see +[Common Mistakes](#common-mistakes). + +That inherit-and-complete behaviour is why **a namespace is how CGP expresses presets.** There is no +separate preset construct: a library publishes a namespace that binds what every application shares and +leaves open what each chooses, and an application joins it and supplies those choices. 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. + +## 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: + +```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 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 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 + +**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. + +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; 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 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 + needs [`#[derive_delegate]`](../attributes/derive_delegate.md) on the component, as it does anywhere. + +### 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, 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: + +```rust +cgp_namespace! { + new ExtendedNamespace: BaseNamespace +} +``` + +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 + +Defining a namespace is only one part of the pattern. A component **registers into** one with the +[`#[prefix(...)]`](../attributes/prefix.md) 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, + } +} +``` + +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 + +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 use it + +**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. + +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; 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 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. + +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 +`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, 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! { + 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__, PathCons>; +} +``` + +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(...)]`](../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: + +```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 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 +[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 + +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 `}` )? + +NamespaceName -> IDENTIFIER GenericArgs? +ParentNamespace -> TypePath GenericArgs? + +NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? +``` + +`NamespaceBody` is [`delegate_components!`](./delegate_components.md)'s `TableBody` production unchanged, +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. 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 +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. + +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, given on +[its page](../attributes/prefix.md#formal-grammar). + +## 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`. 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 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: + +```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, 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, 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 +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*, 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 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. + +**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>, PathCons>: AppNamespace` is not satisfied +``` + +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 + +- [`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/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. + +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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..e21e56d6 --- /dev/null +++ b/docs/reference/macros/cgp_producer.md @@ -0,0 +1,291 @@ +--- +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]` + +Define a `Producer` provider from an input-free function. + +## Overview + +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: + +```rust +#[cgp_producer] +fn magic_number() -> u64 { + 42 +} +``` + +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 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 +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. + +## Usage + +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`, +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 +enforced at expansion time with its own message: + +| 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. | +| 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 +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, + } +} + +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 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. 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! { + App { + ComputerComponent: + PipeHandlers, + } +} +``` + +## When to use it + +**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 + 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](/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. +- **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 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 + +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] +pub fn magic_number() -> u64 { + 42 +} +``` + +it produces the base impl, whose method ignores both of its parameters and 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/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 the other** components: + +```rust +delegate_components! { + MagicNumber { + [ + ComputerComponent, + ComputerRefComponent, + TryComputerComponent, + TryComputerRefComponent, + AsyncComputerComponent, + AsyncComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ]: + PromoteProducer, + } +} +``` + +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 +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, and no `impl Trait` return type), as described in [Usage](#usage). + +## Common Mistakes + +**Each shape restriction has its 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 +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. 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 +the macro: write an impl of `Producer` with [`#[cgp_impl]`](./cgp_impl.md) instead. + +**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: + +```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 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/handler/producer.md) — the base component this implements. +- [Handler combinators](../providers/handler/index.md) — `PromoteProducer`, which this wires, plus + `ReturnInput` and `PipeHandlers`. +- [`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. +- [`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: [`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) + +--- + +*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 new file mode 100644 index 00000000..3d1d43c3 --- /dev/null +++ b/docs/reference/macros/cgp_provider.md @@ -0,0 +1,444 @@ +--- +title: '#[cgp_provider] and #[cgp_new_provider]' +sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' +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.' +--- + +# `#[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. + +## Overview + +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: + +```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 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 +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. + +## 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 +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 path with `Component` appended, so implementing +`AreaCalculator` targets `AreaCalculatorComponent`, which must be in scope beside the trait, and +implementing `crate::shapes::AreaCalculator` targets `crate::shapes::AreaCalculatorComponent`, which +the module need not import. So a provider in another module than its component imports the key with +the trait, as `use crate::shapes::{AreaCalculator, AreaCalculatorComponent};`, or names the trait by +its path, exactly as for [`#[cgp_impl]`](./cgp_impl.md#importing-the-component-key), which also shows +what `cargo cgp check` reports when the import is missing. Pass the component explicitly when the +component's marker does not follow that convention, as when the component renamed it with the +`name:` key: + +```rust +#[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 + } +} +``` + +### The struct `#[cgp_new_provider]` declares + +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. Several parameters share one tuple, and a lifetime is lifted into +[`Life<'a>`](../types/life.md), because `PhantomData` takes a type argument and a lifetime is not +one: + +```rust +// from `... for RectangleArea` +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 +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](/docs/reference/glossary#higher-order-provider) uses so it +can fall back to the context's own wiring. + +## Examples + +A complete provider with its struct declared separately, the case `#[cgp_provider]` handles: + +```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 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)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +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 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 +two instead: in generated code, in a desugaring, and in CGP's own crates. + +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 + 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)]`, 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. + +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. + +## 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` are imported from +`cgp::extra::handler`: + +```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. 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 +**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. + +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 +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. + +**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] +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 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 + +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 + +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 path with `Component` appended to its last +segment; 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. + +## 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: + +```text +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). + +**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 +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 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 +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**, unlike in +[`#[cgp_impl]`](./cgp_impl.md), where the macro qualifies it. 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` works here +because `Self` is the provider. 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/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. +- [`#[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. + +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) + 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) + +--- + +*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 new file mode 100644 index 00000000..cb7c9975 --- /dev/null +++ b/docs/reference/macros/cgp_type.md @@ -0,0 +1,370 @@ +--- +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]` + +Define an abstract-type component, whose concrete type each context chooses for itself. + +## Overview + +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 +`trait HasScalarType { type Scalar; }`, and code written against it says `Self::Scalar` while leaving the +actual type open. + +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]` +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 +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} +``` + +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. + +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. + +## Usage + +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. + +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 that declares +`open LabelTypeProviderComponent;` 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 +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, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + } +} + +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 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 +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 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 { + type Scalar = f64; +} +``` + +## When to use it + +**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 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 +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 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 + 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 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 + 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 + +`#[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 core 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: 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: + +```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 tag-indexed abstract-type component, +and this impl lets any `TypeProvider` back the named component when the context wires +`WithProvider

`, 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. + +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 + +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. + +## 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 each report the same thing: + +```text +error: type trait should contain exactly one associated type item +``` + +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 +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: + +```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 +component name in the `check_components!` block rather than the offending wiring entry: + +```text +error[E0277]: the trait bound `String: Copy` is not satisfied + | + | 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 +headline, so read downward. **Without a check the mistake is silent**, which is the ordinary consequence of +[lazy wiring](./delegate_components.md#common-mistakes) 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 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. +- [`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`. + +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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..c6ca64f4 --- /dev/null +++ b/docs/reference/macros/check_components.md @@ -0,0 +1,435 @@ +--- +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.' +--- + +# `check_components!` + +Assert at compile time that a context can actually use each component it wires. + +## Overview + +**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 +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 trait's method 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 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 +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 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". + +## 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: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +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 + +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 `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, and when the context is not a path at all, such as `&'a Person`, from which no name can be +derived: + +```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 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. 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 + +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_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, + } +} + +check_components! { + Person { + GreeterComponent, + } +} +``` + +The `delegate_components!` block compiles on its own, because wiring is lazy. The `check_components!` block +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/tooling/cargo-cgp/check) reports the same failure +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. + +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 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. + +- **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. A + 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 + context that delegates to it, or with `#[check_providers(...)]` against a real context. The + [Common Mistakes](#common-mistakes) 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 + +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: + +```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/wiring/is_provider_for.md) for +`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. + +`__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: + +```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`, 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__, __Context__, __Params__: ?Sized>: + IsProviderFor<__Component__, __Context__, __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. 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 + +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, 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 +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. + +## Common Mistakes + +**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: + +```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 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 `RectangleArea: IsProviderFor` is not satisfied +``` + +Only a help line hints at the cause, noting that the provider implements the marker for `Rectangle` +but not for `()`. [`cargo cgp check`](/docs/tooling/cargo-cgp/error-codes#cgp-e060) rewords this as `[CGP-E060]` +and names the parameters to check at, when the context passes the check at any. 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: + +```text +error: `#[check_providers(...)]` requires at least one provider type. +``` + +**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: + +```text +error[E0428]: the name `__CheckPerson` is defined multiple times +``` + +Use `#[check_trait(...)]` on one of them. + +**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 + +- [`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/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/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 + 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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..9d1ff56b --- /dev/null +++ b/docs/reference/macros/delegate_and_check_components.md @@ -0,0 +1,453 @@ +--- +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!` + +Wire a context and check that wiring in one macro. + +## Overview + +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. + +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! { + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } +} +``` + +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 run into the confusing errors lazy wiring produces. The +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 + +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)]`, +the one attribute the table accepts: + +```rust +delegate_and_check_components! { + #[check_trait(TestScaledRectangle)] + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } +} +``` + +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 +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! { + MyApp { + #[check_params(Rectangle, Circle)] + AreaCalculatorComponent: ShapeArea, // a provider generic over the shape + } +} +``` + +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 only 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. A +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 + +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] +``` + +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. 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. ` 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 + +**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 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 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 + +The intended use is a straightforward context, wired and proven together: + +```rust +use cgp::core::field::impls::UseField; +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 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 { + PerimeterCalculatorComponent: + RectanglePerimeter, + + #[skip_check] + AreaCalculatorComponent: + ScaledArea, + } +} + +check_components! { + #[check_providers(RectangleArea, ScaledArea)] + ScaledRectangle { + 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, 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 + +**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 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 + 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 [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 +beginner-proof way to guarantee that for simple contexts; the two separate macros are the way that scales. + +## Under the hood + +The macro emits the delegation impls exactly as [`delegate_components!`](./delegate_components.md) would, +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 +delegate_and_check_components! { + #[check_trait(CheckMyContext)] + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } +} +``` + +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 { + type Delegate = UseType; +} +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for MyContext +where + UseType: IsProviderFor, +{} +``` + +and the same pair again for `NameGetterComponent`. Then comes the checking half: a marker trait aliasing +[`CanUseComponent`](../traits/wiring/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. 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 +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 {}`, 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 + +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, 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 + +**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: + +```text +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied +note: required for `RectangleArea` to implement `IsProviderFor` +``` + +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: + +```text +error: Expected at most one `#[check_params]` or `#[skip_check]` attribute +``` + +**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 `RectangleArea: IsProviderFor` is not satisfied +``` + +Only a help line hints at the cause, noting that the provider implements the marker for `Rectangle` but +not for `()`. [`cargo cgp check`](/docs/tooling/cargo-cgp/error-codes#cgp-e060) rewords this as `[CGP-E060]` and names +the parameters to check at, when the context passes the check at any. 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 +*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 + +- [`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/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 + 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) +- 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/) + +--- + +*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 new file mode 100644 index 00000000..d49f07ac --- /dev/null +++ b/docs/reference/macros/delegate_components.md @@ -0,0 +1,839 @@ +--- +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!` + +Build a context's wiring table, naming the provider that implements each of its components. + +## Overview + +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. CGP enables pluggable trait implementations in Rust, and `delegate_components!` is where a +context picks them. + +```rust +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +Think of the result as a **table**: a compact list saying which implementation supplies each +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 +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;` +without fields is a perfectly good context. Sometimes, as above, it is the data type itself. + +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. 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 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 +alongside them. The only ordering rule is that statements come first. + +The simplest table needs none of that: + +```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. 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! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} +``` + +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 +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 + +A leading generic list makes the whole table generic, wiring every instantiation at once: + +```rust +delegate_components! { + MyContext { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +### The operators + +The operator between a key and its value decides what the entry resolves to. The parser accepts any +operator with any key form. The notes below say which pairings are worth writing. + +| 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 | + +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. +This is how one table adopts a single choice from another rather than repeating it: + +```rust +delegate_components! { + new ScaledGeometryComponents { + AreaCalculatorComponent: + ScaledAreaCalculator, // the provider *is* this scaled calculator + PerimeterCalculatorComponent -> + GeometryComponents, // the provider is whatever GeometryComponents wires for perimeter + } +} +``` + +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 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! { + App { + [AreaCalculatorComponent, PerimeterCalculatorComponent] => + @shared, + + @shared: RectangleGeometry, + } +} +``` + +The `open` statement below uses this same mechanism: `open AreaCalculatorComponent;` is +another spelling of `AreaCalculatorComponent => @AreaCalculatorComponent,` and generates the same impl. +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 key forms + +**A single key** is one component name, and may carry generics of its own: +` 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: + +```rust +delegate_components! { + MyComponents { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + ColorComponent: SolidColor, + } +} +``` + +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 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 +[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](/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**: + +- **`[…]` groups alternatives for one segment**, and the path may continue after it. + `@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. + +```rust +delegate_components! { + App { + namespace ExtendedNamespace; + + @app.{ + ErrorRaiserComponent.{&'static str, String}, + ErrorWrapperComponent, + }: RaiseFrom, + } +} +``` + +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 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 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. + +::: + +Nesting a table inside a `UseDelegate` value looks like this: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +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 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! { + new MyComponents { + WidthKey: UseDelegate { + HeightKey: HeightValue, + }>, + } +} +``` + +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 +the check with `E0277`, an unsatisfied `IsProviderFor` on `UseDelegate<…>` that never mentions the +missing attribute. + +### 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. +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: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +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 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 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! { + 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 +to a context wiring its own components directly, and it does not combine with a joined namespace where +the component carries a [`#[prefix(...)]`](../attributes/prefix.md). + +### The namespace statements + +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. 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 + +**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 the order is free: +several statements may appear in any order, and they mix freely with the mappings that follow. + +```rust +delegate_components! { + App { + open AreaCalculatorComponent; + + PerimeterCalculatorComponent -> GeometryComponents, + + [ColorComponent, LabelComponent]: DefaultStyle, + + @AreaCalculatorComponent.{Rectangle, Circle}: + ShapeArea, + + @AreaCalculatorComponent.[Square, Triangle]: + PolygonArea, + } +} +``` + +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 **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 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, 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::*; + +#[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, + } +} + +fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); +} +``` + +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 +#[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! { + Square { + AreaCalculatorComponent, + } +} +``` + +`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 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, the +component carries the type as a parameter, as the generic `CanCalculateArea` under +[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; + +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.{Circle, Ellipse}: CurveArea, + } +} + +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle, Ellipse], + } +} +``` + +## 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 +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 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, + 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 you cannot forget + 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 + 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 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. + +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, the +[`DelegateComponent`](../traits/wiring/delegate_component.md) impl 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. + +The [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl forwards the provider's requirements: + +```rust +impl< + __Context__, + __Params__: ?Sized, +> 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. `__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. + +**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 ScaledGeometryComponents +where + GeometryComponents: 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 `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. + +**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; +} +``` + +`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: + +```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 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. + +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 +`@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 +`delegate_components!` blocks, the inner one carrying `new`. Its per-value entries key on the same +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 +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 + +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 ) `;` + +NamespaceStmt -> `namespace` IDENTIFIER `;` + +ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? + `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` + +Mapping -> NormalMapping + | Key `->` ProviderValue + | Key `=>` PathValue + +NormalMapping -> Key `:` ProviderValue + +Key -> SingleKey | MultiKey | PathKey +SingleKey -> Generics? Type +MultiKey -> `[` ( SingleKey ( `,` SingleKey )* `,`? )? `]` +PathKey -> Generics? `@` PathHead + +PathHead -> KeySegment ( `.` PathHead )? + | `[` ( KeySegment ( `,` KeySegment )* `,`? )? `]` ( `.` PathHead )? + | `{` ( PathHead ( `,` PathHead )* `,`? )? `}` + +KeySegment -> Generics? PathSegment + +PathValue -> `@` PathSegment ( `.` PathSegment )* + +PathSegment -> Type + +ProviderValue -> Type + | IDENTIFIER `<` `new` InnerTable `>` + +InnerTable -> IDENTIFIER BoundFreeGenerics? `{` TableBody `}` +``` + +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 +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 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. 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, 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 +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. The answer is to check the table (see +[`check_components!`](./check_components.md)) and to read failures through +[`cargo cgp check`](/docs/tooling/cargo-cgp/check) in place of `cargo check`. `cargo cgp check` leads with the +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 +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 +`@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 `:` +``` + +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 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/tooling/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/tooling/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 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 +`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 +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). + +## 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, + for the plain entries. +- [`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. +- [`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. + +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) +- 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) + +--- + +*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/enum.md b/docs/reference/macros/enum.md new file mode 100644 index 00000000..fce4f1a4 --- /dev/null +++ b/docs/reference/macros/enum.md @@ -0,0 +1,208 @@ +--- +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 + +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 +[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 check`](/docs/tooling/cargo-cgp/check) and [`cargo cgp expand`](/docs/tooling/cargo-cgp/expand) +print 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. + +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()`. + +## 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::core::field::traits::FromFields; +use cgp::core::field::types::{Either, Field}; +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 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 +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). + +## 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 new file mode 100644 index 00000000..d562eae0 --- /dev/null +++ b/docs/reference/macros/index.md @@ -0,0 +1,77 @@ +--- +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 + +The procedural macros of [Context-Generic Programming (CGP)](/docs/) 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 +the kind of work it does, in roughly the order most CGP code uses them. + +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 + +[`#[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 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 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. +[`#[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. + +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 +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 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 +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. [`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` +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 new file mode 100644 index 00000000..0f3c92ff --- /dev/null +++ b/docs/reference/macros/path.md @@ -0,0 +1,257 @@ +--- +title: 'Path! — type-level paths' +sidebar_label: 'Path!' +sidebar_position: 21 +description: 'A type-level path, used by CGP namespaces and by component lookups that are redirected along one.' +--- + +# `Path!` + +A type-level path, used by namespaces and redirected lookups. + +## Overview + +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. + +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) +``` + +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. 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 +[`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. + +## Usage + +`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) +Path!(@app.error) +Path!(@app.error.ErrorRaiserComponent) +``` + +### How a segment is encoded + +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 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. A name that only looks like one, such as `f` or `u2`, is 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 +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::core::error::ErrorRaiserComponent; +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, 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 + +**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 + 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 list.** The macro expands to `PathCons>`, + and writing it out is longer and identical in meaning. +- **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 + types; `Path!` differs in its segment-classification rule, which exists to serve routing and would be + surprising anywhere else. + +## Under the hood + +`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 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 +PathCons>>>, Nil> +``` + +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 +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` 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. + +## 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 identifier starting with a +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. + +## Common Mistakes + +**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 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 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. + +## 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 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. + +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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..ec074ca3 --- /dev/null +++ b/docs/reference/macros/product.md @@ -0,0 +1,238 @@ +--- +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!` + +A type-level list and its value-level counterpart. + +## Overview + +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 +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 +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/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. + +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); you write `Product!` by hand in a handler +pipeline, listing the steps to run in order. + +## Usage + +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, among other impls: +// impl HasFields for Person { +// type Fields = Product![ +// Field, +// Field, +// ]; +// } +``` + +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. 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! { + 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 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. + +- **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 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. +- **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 + +`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 `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 +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` +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. + +## 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 +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 +``` + +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. + +**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. +- [`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. +- [`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/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. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — the record representation this list + encodes. + +## 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) + +--- + +*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/struct.md b/docs/reference/macros/struct.md new file mode 100644 index 00000000..48f663de --- /dev/null +++ b/docs/reference/macros/struct.md @@ -0,0 +1,264 @@ +--- +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 + +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 +[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 check`](/docs/tooling/cargo-cgp/check) and [`cargo cgp expand`](/docs/tooling/cargo-cgp/expand) 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 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()`. + +## 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::core::field::traits::FromFields; +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), +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! { + 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. + +**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 +`#[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 new file mode 100644 index 00000000..68fcbee7 --- /dev/null +++ b/docs/reference/macros/sum.md @@ -0,0 +1,223 @@ +--- +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!` + +A type-level sum, the dual of `Product!`. + +## Overview + +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. + +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 +Sum![u32, String, bool] +``` + +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 +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. + +## 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: + +```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 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 + +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, among other impls: +// impl HasFields for Shape { +// type Fields = Sum![ +// Field, +// Field, +// Field, +// ]>, +// ]; +// } +``` + +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: + +```rust +type Token = Sum![u32, String, bool]; +``` + +## 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 +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 + 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 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. + +## Under the hood + +`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 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`. + +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 +`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 gives generic variant handling compile-time exhaustiveness +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`. + +## 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. + +## 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 +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. + +**The variant derives need each variant to hold one unnamed field or none.** +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md), `CgpVariant`, `ExtractField`, and `FromVariant` +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, or no fields +``` + +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 + +- [`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. +- [`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/variant/from_variant.md) and [`ExtractField`](../traits/variant/extract_field.md) — constructing and + taking apart a variant generically. +- [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two enums that share variants. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this list + encodes. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..f39a7a84 --- /dev/null +++ b/docs/reference/macros/symbol.md @@ -0,0 +1,266 @@ +--- +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!` + +A [type-level string](/docs/reference/glossary#type-level-string), used as a field-name tag. + +## Overview + +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. + +`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 lets field access take part in trait resolution. A **context** is the type +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. + +**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. 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. + +## Usage + +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 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 +``` + +### 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_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. + +### 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. `Person` is a +value context here, the type whose own field the getter reads: + +```rust +use cgp::core::field::impls::UseField; +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, + } +} +``` + +`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, the shape 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. 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 +diagnostics: + +```rust +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. +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 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. + +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 +needed. + +## Under the hood + +`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/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 +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. `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. Reading +the characters in order is enough to decode it, and [`cargo cgp check`](/docs/tooling/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 does not yet reshape every class. + +## 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 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 + +**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 +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 + +- [`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 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. + +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) +- 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) + +--- + +*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/_category_.json b/docs/reference/providers/_category_.json new file mode 100644 index 00000000..66c02186 --- /dev/null +++ b/docs/reference/providers/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Providers", + "position": 5, + "link": { + "type": "doc", + "id": "reference/providers/index" + } +} diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md new file mode 100644 index 00000000..d596a366 --- /dev/null +++ b/docs/reference/providers/chain_getters.md @@ -0,0 +1,206 @@ +--- +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 +--- + +# `ChainGetters` + +Compose a list of field getters into one, reaching a field several hops inside a nested context. + +## Overview + +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 +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. + +## 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::core::component::WithProvider; +use cgp::core::field::impls::UseField; +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, + ]>, + >, + } +} + +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 +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 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. + +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-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: + +```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-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: + +```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` 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. + +## 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-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. +- [`#[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) + +--- + +*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/_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..254257d7 --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -0,0 +1,212 @@ +--- +title: 'BuildAndMerge — merge a built sub-record' +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 move every one of its fields into the target's builder at once. + +## Overview + +`BuildAndMerge` is the builder step for a group of fields that one provider produces +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. + +## Usage + +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, 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 + +Two subsystems each build their part of an `App`: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +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 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`. 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 + Provider: for<'a> Computer, + Builder: CanBuildFrom, +{ + type Output = Output; + + fn compute(context: &Context, code: PhantomData, builder: Builder) -> Self::Output { + let output = Provider::compute(context, code, &builder); + builder.build_from(output) + } +} +``` + +`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 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 moves the sub-record's + fields into the builder. + +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) + +--- + +*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 new file mode 100644 index 00000000..bb0b6af6 --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -0,0 +1,224 @@ +--- +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 providers that each build part of it, merging every output in by field +name. + +## Overview + +`BuildAndMergeOutputs` assembles a record from providers that each build a +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 +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 sub-record providers: + +```rust +use cgp::extra::dispatch::BuildAndMergeOutputs; + +delegate_components! { + AppBuilder { + ComputerComponent: + BuildAndMergeOutputs, + } +} +``` + +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::extra::handler::{Computer, ComputerComponent}; +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 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 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 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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..66d05022 --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -0,0 +1,187 @@ +--- +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` + +Compute one field's value and set it on a +[partial record](/docs/reference/glossary#partial-record). + +## Overview + +`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, +it carries no runtime value. + +## Usage + +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}; + +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::core::field::traits::HasField; +use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; +use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; +use cgp::prelude::*; + +#[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 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`. 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 + Provider: for<'a> Computer, + Builder: BuildField, +{ + type Output = Output; + + fn compute(context: &Context, code: PhantomData, builder: Builder) -> Self::Output { + let value = Provider::compute(context, code, &builder); + builder.build_field(PhantomData::, value) + } +} +``` + +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 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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..5a09be2d --- /dev/null +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -0,0 +1,228 @@ +--- +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` + +Build a record from a list of steps, starting from an empty builder and finalizing once every field +is set. + +## Overview + +`BuildWithHandlers` assembles a record whose fields come from separate providers. +[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 +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 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}; + +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::extra::handler::{Computer, ComputerComponent}; +use cgp::prelude::*; +use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, 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, + } + } +} + +#[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(), + }, + ); +} +``` + +`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 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`. 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 + Output: HasBuilder, + PipeHandlers: Computer, + Res: FinalizeBuild, +{ + type Output = Output; + + fn compute(context: &Context, code: PhantomData, _input: Input) -> Self::Output { + PipeHandlers::compute(context, code, Output::builder()).finalize_build() + } +} +``` + +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 steps + its list is built from. +- [`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. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..198dd786 --- /dev/null +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -0,0 +1,197 @@ +--- +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` + +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. [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 +[**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 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, +}; + +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 + +Counting the corners of a shape, with the two quadrilaterals handled as one group: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +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 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 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) + } +} +``` + +`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 + +- [`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 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) + +--- + +*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 new file mode 100644 index 00000000..44da7323 --- /dev/null +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -0,0 +1,194 @@ +--- +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` + +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 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 +[**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 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}; + +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::core::field::traits::HasExtractor; +use cgp::extra::handler::{Computer, ComputerComponent}; +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 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 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`. 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)>); + +#[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) + } +} +``` + +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` 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 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), + with the first-argument form in `extract_first_field.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/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md new file mode 100644 index 00000000..18174a70 --- /dev/null +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -0,0 +1,172 @@ +--- +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 provider. + +## Overview + +`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 +[**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 +is written inside an arm: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; + +type CircleArm = ExtractFieldAndHandle>; +``` + +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::extra::handler::{Computer, ComputerComponent}; +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 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`, and its `Computer` impl +reads the `Field`'s `value` and forwards it: + +```rust +pub struct HandleFieldValue(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) + } +} +``` + +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 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 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), + with the first-argument form in `first_field_value.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/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md new file mode 100644 index 00000000..12c679d9 --- /dev/null +++ b/docs/reference/providers/dispatch/index.md @@ -0,0 +1,104 @@ +--- +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 (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 enum or a record generically, where the logic for each variant +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 +[`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. + +None of these names is in the prelude. Every one of them, the value matchers included, 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 from the enum's own + variants, passing each payload bare or tagged with its variant name. + +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 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 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) 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 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-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). + +--- + +*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 new file mode 100644 index 00000000..931a1ce6 --- /dev/null +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -0,0 +1,224 @@ +--- +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 that arrives together with extra arguments, passing the arguments to every handler. + +## Overview + +`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. [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 +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 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, +}; + +delegate_components! { + App { + ComputerComponent: + MatchFirstWithHandlers>, + ExtractFirstFieldAndHandle>, + ]>, + } +} +``` + +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::extra::handler::{Computer, ComputerComponent}; +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 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 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). Both forms are +imported from `cgp::extra::dispatch`. + +## Under the hood + +`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); + +#[cgp_provider] +impl Computer + for MatchFirstWithHandlers +where + Input: HasExtractor, + DispatchMatchers: Computer< + Context, + Code, + (Input::Extractor, Args), + Output = Result, + >, + Remainder: FinalizeExtract, +{ + type Output = Output; + + 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 `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 + 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: + +- [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`, 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). + +--- + +*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 new file mode 100644 index 00000000..bab418ea --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -0,0 +1,206 @@ +--- +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 from its own variants, passing each payload +with its variant name attached. + +## Overview + +`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. [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. + +## Usage + +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, + } +} +``` + +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 cgp::core::field::traits::StaticString; +use cgp::core::field::types::Field; +use cgp::extra::dispatch::MatchWithFieldHandlers; +use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; +use cgp::prelude::*; +use core::fmt::Display; + +#[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"); +} +``` + +[`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'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), 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 + } +} +``` + +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, + Fields: ToFieldHandlers, +{ + type Handlers = Fields::Handlers; +} +``` + +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 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: + +- [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 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). + +--- + +*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 new file mode 100644 index 00000000..343d08a1 --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -0,0 +1,262 @@ +--- +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, with no wildcard arm. + +## Overview + +`MatchWithHandlers` is the matcher for an enum whose variants each have their own handler. +[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 +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) so the handler receives the bare payload: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} +``` + +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 with a [generic parameter +list](../../macros/check_components.md#components-with-generic-parameters) of its own: + +```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 + +A `Shape` enum dispatched to one area provider with an impl per payload type: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +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 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); +} +``` + +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 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` in the context's error type, [`TryPromote`](../handler/try_promote.md) turns the matcher's +`Result` output into a `TryComputer`. + +## Under the hood + +`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); + +#[cgp_provider] +impl Computer + for MatchWithHandlers +where + Input: HasExtractor, + DispatchMatchers: + Computer>, + Remainder: FinalizeExtract, +{ + type Output = Output; + + fn compute(context: &Context, code: PhantomData, input: Input) -> Output { + DispatchMatchers::compute(context, code, input.to_extractor()).finalize_extract_result() + } +} +``` + +`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 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. +- [`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. +- [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). + +--- + +*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 new file mode 100644 index 00000000..0f74c2b9 --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -0,0 +1,278 @@ +--- +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 from its own variants, passing each payload +as a bare value. + +## Overview + +`MatchWithValueHandlers` is the matcher for the common case, where every variant's +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 +[`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 not in the prelude; import it from `cgp::extra::dispatch`. It takes one optional type +parameter, the 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! { + App { + open ComputerComponent; + + @ComputerComponent. Code.[Circle, Rectangle]: ComputeArea, + @ComputerComponent. Code.Shape: MatchWithValueHandlers, + } +} +``` + +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 named provider needs no +per-type entries: `ComputerComponent: MatchWithValueHandlers` sends every payload +straight to `ComputeArea`. + +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 +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::extra::dispatch::MatchWithValueHandlers; +use cgp::extra::handler::{Computer, ComputerComponent}; +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'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), 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<_>: 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 `MatchWithValueHandlersRef` to implement `IsProviderFor` +``` + +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. + +**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 + 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: + +- [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`. + +--- + +*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/_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..323b8043 --- /dev/null +++ b/docs/reference/providers/error/debug_error.md @@ -0,0 +1,197 @@ +--- +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 +--- + +# `DebugError` + +Raise or wrap any `Debug` source by formatting it into a `String` and forwarding to the context's own +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 +[**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 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`; none of them +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; +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, 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` 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. + +## 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/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` 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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..b563c0af --- /dev/null +++ b/docs/reference/providers/error/discard_detail.md @@ -0,0 +1,146 @@ +--- +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 +--- + +# `DiscardDetail` + +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 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 +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`; neither is in the prelude. 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. + +## 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. + +## 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 + } +} +``` + +`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. +- [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — wrap by keeping the detail as a + formatted string instead of discarding it. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement 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) + +--- + +*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 new file mode 100644 index 00000000..52d320d5 --- /dev/null +++ b/docs/reference/providers/error/display_error.md @@ -0,0 +1,196 @@ +--- +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 +--- + +# `DisplayError` + +Raise or wrap any `Display` source by formatting it into a `String` and forwarding to the context's own +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 +[**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. + +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`; none of them +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; +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{DisplayError, RaiseFrom}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DisplayError, + } +} +``` + +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` 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 +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` 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] +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 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` 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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..2e3b6722 --- /dev/null +++ b/docs/reference/providers/error/index.md @@ -0,0 +1,106 @@ +--- +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 +--- + +# 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 + +[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: +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`, +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`, 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 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. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — how the abstract error type, the + raise and wrap components, 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). + +--- + +*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 new file mode 100644 index 00000000..a82c99f4 --- /dev/null +++ b/docs/reference/providers/error/panic_on_error.md @@ -0,0 +1,145 @@ +--- +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 +--- + +# `PanicOnError` + +Abort with the source error's debug output instead of producing an abstract error value. + +## Overview + +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 +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`; neither is in the prelude. 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. 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 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. + +## 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/wiring/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. +- [`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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..4729f7f7 --- /dev/null +++ b/docs/reference/providers/error/raise_from.md @@ -0,0 +1,199 @@ +--- +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 +--- + +# `RaiseFrom` + +Raise a source error by converting it into the context's error type through the standard `From` trait. + +## 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. + +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`; neither is in the prelude. 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. 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 + +One `RaiseFrom` entry raises two different source types, each through its own `From` impl on the +context's `AppError`: + +```rust +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 { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + PortParserComponent: ParsePort, + } +} + +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(_)))); +} +``` + +`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, 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 +[`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` makes one wiring cover many source types. The generated +[`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 + 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. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source 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) + +--- + +*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 new file mode 100644 index 00000000..769d060c --- /dev/null +++ b/docs/reference/providers/error/raise_infallible.md @@ -0,0 +1,156 @@ +--- +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 +--- + +# `RaiseInfallible` + +Absorb `core::convert::Infallible`, the error type that can never be constructed. + +## Overview + +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 +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`; neither is in the prelude. 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. + +## 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. + +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/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. +- [`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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..b3ed1fef --- /dev/null +++ b/docs/reference/providers/error/return_error.md @@ -0,0 +1,170 @@ +--- +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 +--- + +# `ReturnError` + +Raise a source error that already is the context's abstract error, so raising is the identity. + +## Overview + +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 +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`; 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; +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: + +```rust +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`, 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 + +**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). + +## 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/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`. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source type, as the example does. + +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) + +--- + +*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/_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..328ce3d1 --- /dev/null +++ b/docs/reference/providers/handler/compose_handlers.md @@ -0,0 +1,148 @@ +--- +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 +--- + +# `ComposeHandlers` + +Run two handlers back to back, feeding the output of the first as the input of the second. + +## Overview + +[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`, +`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 is not in the prelude. 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 + +Two computers composed and wired as one: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +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 `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 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 + +`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 +#[cgp_provider] +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/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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..ef6672d6 --- /dev/null +++ b/docs/reference/providers/handler/index.md @@ -0,0 +1,117 @@ +--- +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 +--- + +# Handler combinators + +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 + +[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 ride in `PhantomData`. + +Every combinator here, the promotion bundles included, 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: + +- [`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`](../../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`, 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 + +**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 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. + +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 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. + +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. + +## 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. +- [`#[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). + +--- + +*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 new file mode 100644 index 00000000..1e548aeb --- /dev/null +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -0,0 +1,174 @@ +--- +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 +--- + +# `PipeHandlers` + +Compose a type-level list of handlers into a single pipeline, threading each stage's output into the +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 +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 is not in the prelude. It takes one type parameter, a +`Product!` list of handler providers: + +```rust +use cgp::extra::handler::PipeHandlers; + +delegate_components! { + App { + ComputerComponent: PipeHandlers, + } +} +``` + +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 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, where `Multiply` and `Add` read +a factor or an addend from a context field: + +```rust +use cgp::core::field::traits::HasField; +use cgp::core::field::types::Field; +use cgp::extra::handler::{CanCompute, 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 MyContext { + pub foo: u64, + pub bar: u64, + pub baz: u64, +} + +delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } +} + +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 +} +``` + +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; the context then also needs an error type. + +## 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 +plainer choice. + +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 + +`PipeHandlers` carries the list in `PhantomData` and holds no handler impls of its own: + +```rust +pub struct PipeHandlers(pub PhantomData); +``` + +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 +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, 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. + +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) + +--- + +*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 new file mode 100644 index 00000000..88bfff03 --- /dev/null +++ b/docs/reference/providers/handler/promote.md @@ -0,0 +1,160 @@ +--- +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 one step up the family, from a producer to a computer or from infallible to fallible, +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 +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 is not in the prelude. 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, + } +} +``` + +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::extra::handler::{ + Computer, ComputerComponent, Handler, HandlerComponent, Producer, ProducerComponent, + TryComputer, TryComputerComponent, +}; +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 + +**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 + +`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`. + +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. +- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `Promote` into the family + 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), + [`Handler`](../../components/handler/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) + +--- + +*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 new file mode 100644 index 00000000..f03df2cb --- /dev/null +++ b/docs/reference/providers/handler/promote_async.md @@ -0,0 +1,155 @@ +--- +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 +--- + +# `PromoteAsync` + +Lift a synchronous handler into an asynchronous one. + +## Overview + +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`. + +## Usage + +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; + +// Serve an AsyncComputer slot from a synchronous Computer. +delegate_components! { + App { + AsyncComputerComponent: PromoteAsync, + } +} +``` + +## Examples + +A context serves both async members from hand-written synchronous providers: + +```rust +use core::num::ParseIntError; +use cgp::extra::handler::{ + AsyncComputer, AsyncComputerComponent, Computer, ComputerComponent, Handler, HandlerComponent, + TryComputer, TryComputerComponent, +}; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{DebugError, 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 + +**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 + +`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 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 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. + +## Source + +- [`providers/promote_async.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_async.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/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md new file mode 100644 index 00000000..b4c9807a --- /dev/null +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -0,0 +1,143 @@ +--- +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 async members of the handler family from a provider that implements `AsyncComputer`. + +:::info + +### Generated machinery + +**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 + +[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 + +It is not in the prelude; import it from `cgp::extra::handler`. It takes one type parameter, the +base `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: DoubleLater, + HandlerComponent: PromoteAsyncComputer, + } +} +``` + +## Examples + +An async `#[cgp_computer]` function is the base, and the bundle answers `handle` from it: + +```rust +use cgp::extra::handler::{CanComputeAsync, CanHandle, PromoteAsyncComputer}; +use cgp::extra::handler::{AsyncComputer, AsyncComputerComponent, Handler, HandlerComponent}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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 `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`: + +```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 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 + +- [`PromoteComputer`](promote_computer.md) — the synchronous-base counterpart. +- [`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. +- [`AsyncComputer`](../../components/handler/async_computer.md), + [`Handler`](../../components/handler/handler.md) — the base and the family members 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) + +--- + +*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 new file mode 100644 index 00000000..b1a58b88 --- /dev/null +++ b/docs/reference/providers/handler/promote_computer.md @@ -0,0 +1,195 @@ +--- +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 +--- + +# `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 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 + +[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 + +It is not in the prelude; import it from `cgp::extra::handler`. 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, + } +} +``` + +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::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute, PromoteComputer}; +use cgp::extra::handler::{ + AsyncComputer, AsyncComputerComponent, Computer, ComputerComponent, Handler, HandlerComponent, + TryComputer, TryComputerComponent, +}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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 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 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): + +```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. 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 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`, 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 +... + = 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 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 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. + +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) + +--- + +*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 new file mode 100644 index 00000000..b6ef71b4 --- /dev/null +++ b/docs/reference/providers/handler/promote_handler.md @@ -0,0 +1,148 @@ +--- +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 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.** +[`#[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 + +[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 + +It is not in the prelude; import it from `cgp::extra::handler`. It takes one type parameter, the +base provider: + +```rust +delegate_components! { + App { + HandlerComponent: PromoteHandler, + } +} +``` + +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 + +An async `#[cgp_computer]` function returning `Result` answers `handle` through the bundle: + +```rust +use cgp::extra::handler::{CanHandle, PromoteHandler}; +use cgp::extra::handler::{Handler, HandlerComponent}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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 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`: + +```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 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 synchronous bases. +- [`Handler`](../../components/handler/handler.md) — the family member it produces. + +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) + +--- + +*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 new file mode 100644 index 00000000..ae76aae8 --- /dev/null +++ b/docs/reference/providers/handler/promote_producer.md @@ -0,0 +1,168 @@ +--- +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 +--- + +# `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 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 + +[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. + +## Usage + +It is not in the prelude; import it from `cgp::extra::handler`. 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: DefaultPort, + [ComputerComponent, TryComputerComponent]: PromoteProducer, + } +} +``` + +## Examples + +A `#[cgp_producer]` function answers the producer and two input-taking members: + +```rust +use cgp::extra::handler::{CanCompute, CanProduce, CanTryCompute, PromoteProducer}; +use cgp::extra::handler::{ + Computer, ComputerComponent, Producer, ProducerComponent, TryComputer, TryComputerComponent, +}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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 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`: + +```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 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 forwards to. +- [`Producer`](../../components/handler/producer.md), + [`Computer`](../../components/handler/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) + +--- + +*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 new file mode 100644 index 00000000..ac1bf8a8 --- /dev/null +++ b/docs/reference/providers/handler/promote_ref.md @@ -0,0 +1,166 @@ +--- +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 by-value handlers and by-reference handlers, in both directions. + +## Overview + +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 + +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: + +- **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()`. + +```rust +use cgp::extra::handler::PromoteRef; + +delegate_components! { + App { + ComputerRefComponent: PromoteRef, + ComputerComponent: PromoteRef, + } +} +``` + +## Examples + +Both directions on one context, each from a hand-written provider: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent, ComputerRefComponent}; +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; + +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 + +**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 + +`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. 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 — 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. + +## Source + +- [`providers/promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.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/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md new file mode 100644 index 00000000..40ead521 --- /dev/null +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -0,0 +1,169 @@ +--- +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 `Computer` whose output is a `Result`. + +:::info + +### Generated machinery + +**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 entries that serve any base, as +[Common Mistakes](#common-mistakes) sets out. This page explains what the bundle emits. + +::: + +## Overview + +[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). +Like every CGP provider, it carries no runtime value. + +## Usage + +It is not in the prelude; import it from `cgp::extra::handler`. It takes one type parameter, the +base provider, a `Computer` returning `Result`: + +```rust +delegate_components! { + App { + [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::extra::handler::{CanHandle, CanTryCompute, PromoteTryComputer}; +use cgp::extra::handler::{Handler, HandlerComponent, TryComputer, TryComputerComponent}; +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[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 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`: + +```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 + +**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 +... + = 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 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 bases. +- [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/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) + +--- + +*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 new file mode 100644 index 00000000..f070f3c8 --- /dev/null +++ b/docs/reference/providers/handler/return_input.md @@ -0,0 +1,114 @@ +--- +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 +--- + +# `ReturnInput` + +The identity handler: return the input unchanged as the output. + +## Overview + +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 + +Import it from `cgp::extra::handler`; it is not in the prelude. 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` as the middle stage of a pipeline, where it changes nothing: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, PipeHandlers, ReturnInput}; + +#[cgp_computer] +pub fn add_one(value: u64) -> u64 { + value + 1 +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: PipeHandlers, + } +} + +check_components! { + App { + ComputerComponent: ((), u64), + } +} + +pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 7); // 5 -> 6 -> 6 -> 7 +} +``` + +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 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 + +`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. 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 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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..652decb0 --- /dev/null +++ b/docs/reference/providers/handler/try_promote.md @@ -0,0 +1,167 @@ +--- +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 +--- + +# `TryPromote` + +Bridge in both directions between a `Result`-valued output and a fallible handler trait. + +## 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 +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 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; + +delegate_components! { + App { + // 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::extra::handler::{Computer, ComputerComponent, TryComputer, TryComputerComponent}; +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 + +**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 + +`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 + `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. 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), [`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. + +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) + +--- + +*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 new file mode 100644 index 00000000..0947744e --- /dev/null +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -0,0 +1,225 @@ +--- +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 +--- + +# `UseInputDelegate` + +Dispatch a handler to a different inner provider per input type, through a lookup table. + +## Overview + +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 +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 Usage section shows for the +input. + +## Usage + +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; + +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: + +```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::extra::handler::{Computer, ComputerComponent}; +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: 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 +`#[derive_delegate(UseInputDelegate)]` that generates it, so existing wiring does not need to +change. + +## Under the hood + +`UseInputDelegate` carries the table in `PhantomData`: + +```rust +pub struct UseInputDelegate(pub PhantomData); +``` + +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 { + 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. For +`Computer`, `cargo cgp expand` on a component with the same directive shows: + +```rust +impl<__Context__, Code, Input, __Components__, __Delegate__> Computer<__Context__, Code, Input> +for UseInputDelegate<__Components__> +where + __Components__: DelegateComponent<(Input), Delegate = __Delegate__>, + __Delegate__: Computer<__Context__, Code, Input>, +{ + type Output = <__Delegate__ as Computer<__Context__, Code, Input>>::Output; + + fn compute(__context__: &__Context__, _code: PhantomData, input: Input) -> Self::Output { + __Delegate__::compute(__context__, _code, input) + } +} +``` + +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, + 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: + +- [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). + +--- + +*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 new file mode 100644 index 00000000..d2b9b716 --- /dev/null +++ b/docs/reference/providers/index.md @@ -0,0 +1,71 @@ +--- +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 + +[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. + +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 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 +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](../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](../macros/cgp_namespace.md) 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](/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 + +The handler family has its own providers, which build, route, and lift computations rather than wire a +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 +[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. + +--- + +*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/_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..76927d60 --- /dev/null +++ b/docs/reference/providers/monad/bind_err.md @@ -0,0 +1,136 @@ +--- +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 +--- + +# `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 + +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 +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 + +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; + +// 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) +``` + +## Examples + +One `?`-style bind step built by hand, which is what `PipeMonadic` composes for a two-element list +under `ErrMonadic`: + +```rust +use cgp::extra::handler::Computer; +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 +[`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`. 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 + +- [`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/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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..312ae426 --- /dev/null +++ b/docs/reference/providers/monad/bind_ok.md @@ -0,0 +1,143 @@ +--- +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 +--- + +# `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 + +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 +[**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 + +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. + +## 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::extra::handler::Computer; +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 +[`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`. 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 + +- [`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/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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..90bb82c7 --- /dev/null +++ b/docs/reference/providers/monad/index.md @@ -0,0 +1,87 @@ +--- +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 +--- + +# Monad providers + +Turn a list of handlers and a choice of monad into a single handler that short-circuits on the +appropriate branch. + +## Overview + +[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 +[**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: + +- [`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. 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 + +- [`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/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. + +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). + +--- + +*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 new file mode 100644 index 00000000..3edeff34 --- /dev/null +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -0,0 +1,220 @@ +--- +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 +--- + +# `PipeMonadic` + +Compose a list of handlers under a monad into a single handler that short-circuits on the monad's stop +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 +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 + +A pipeline of three fallible computers, wired under `ErrMonadic` and called through the consumer +trait: + +```rust +use cgp::extra::handler::{Computer, ComputerComponent}; +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")); +} +``` + +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 +use cgp::extra::handler::{Computer, TryComputer}; +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::< + OkMonadicTrans, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), + Ok(Ok(())), + ); + + // An outer `Err` stops it too. + assert_eq!( + 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::< + OkMonadic, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::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 +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 `[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 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 + +- 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/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. + +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) + +--- + +*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 new file mode 100644 index 00000000..a7ce23fb --- /dev/null +++ b/docs/reference/providers/redirect_lookup.md @@ -0,0 +1,254 @@ +--- +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 +--- + +# `RedirectLookup` + +Route a component's lookup along a type-level path in a separate table. The mechanism behind namespaces +and `open`. + +:::info + +### Generated machinery + +**You are not expected to write `RedirectLookup` entries.** +[`#[cgp_component]`](../macros/cgp_component.md) generates a `RedirectLookup` impl for every component, +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. + +::: + +## Overview + +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. +`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 + +You do not name `RedirectLookup` directly, so it is not in the prelude; import it from +`cgp::core::component` if you need it. It appears where the namespace and `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; + + @app.GreeterComponent: GreetHello, + } +} +``` + +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 + +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; + + @app.GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, + } +} + +pub fn demo() { + assert_eq!(App.greet(), "hello"); +} +``` + +`#[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 + +**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/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> +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 +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. + +## 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 + component. +- [`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. +- [`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. + +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) + +--- + +*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 new file mode 100644 index 00000000..b5ac5ada --- /dev/null +++ b/docs/reference/providers/use_context.md @@ -0,0 +1,241 @@ +--- +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 +--- + +# `UseContext` + +Satisfy a provider trait by routing back through the context's own consumer-trait implementation. + +## 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 +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 +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. 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 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. + +## Usage + +`UseContext` is imported from `cgp::core::component`. It takes no type parameter and +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 +pub struct EncodeVec(pub PhantomData); +``` + +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 +for a different type. + +## Examples + +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::core::component::UseContext; +use cgp::prelude::*; + +#[cgp_component(Encoder)] +pub trait CanEncode { + 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() + } +} + +pub struct EncodeVec(pub PhantomData); + +#[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() + } +} + +pub struct App; + +delegate_components! { + App { + open EncoderComponent; + + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVec, + } +} + +check_components! { + App { + EncoderComponent: [u32, Vec], + } +} + +pub fn demo() { + assert_eq!(App.encode(&vec![1u32, 2, 3]), b"123"); +} +``` + +`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 +back to, and the inner provider must always be named. + +## 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 +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* trait and the *same* type, 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](/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 +#[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`. 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 a check reports the overflow: + +```text +error[E0275]: overflow evaluating the requirement `App: IsProviderFor` +``` + +[`cargo cgp check`](/docs/tooling/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 +`UseContext` resolves `Encoder`, a different 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. +- [`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/wiring/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) + +--- + +*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 new file mode 100644 index 00000000..b1db6976 --- /dev/null +++ b/docs/reference/providers/use_default.md @@ -0,0 +1,196 @@ +--- +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 +--- + +# `UseDefault` + +Select a component's implementation from the consumer trait's own default method bodies. + +## Overview + +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 +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**](/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 +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 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 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)] +#[extend(HasName)] +pub trait CanGreet { + 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, + } +} + +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 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 + +**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/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. + +## 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` + 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/wiring/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, 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) + +--- + +*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 new file mode 100644 index 00000000..f1675d41 --- /dev/null +++ b/docs/reference/providers/use_delegate.md @@ -0,0 +1,229 @@ +--- +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 +--- + +# `UseDelegate` + +Dispatch a generic-parameter component to a different inner provider per type, through a lookup table. +Superseded by the `open` statement. + +:::info + +### Legacy — read, don't write + +`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 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 +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 +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 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 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], + } +} + +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 +`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. `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: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +## 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 +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 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 + +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 the `CanCalculateArea` component above, with its +`#[derive_delegate(UseDelegate)]` attribute, `cargo cgp expand` shows: + +```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) + } +} +``` + +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 + +- [`#[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/use_input_delegate.md) — the sibling that keys on a handler's `Input` type. +- [`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: + +- [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. + +--- + +*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 new file mode 100644 index 00000000..ad7098cc --- /dev/null +++ b/docs/reference/providers/use_delegated_type.md @@ -0,0 +1,142 @@ +--- +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 +--- + +# `UseDelegatedType` + +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 + +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) +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 +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/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 + +`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::core::types::{HasType, 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) +} +``` + +`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 +[`WithDelegatedType`](with_delegated_type.md). + +## 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/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. +- [`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) + +--- + +*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 new file mode 100644 index 00000000..cda87f98 --- /dev/null +++ b/docs/reference/providers/use_field.md @@ -0,0 +1,241 @@ +--- +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 +--- + +# `UseField` + +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. + +## Overview + +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. + +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/field-access/has_field.md) implementation supports. + +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 +in wiring, never constructed. + +## Usage + +`UseField` is not in the prelude, so import it from `cgp::core::field::impls` 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` 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 + +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::core::field::impls::UseField; +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 demo() { + let person = Person { first_name: "Alice".to_owned() }; + assert_eq!(person.name(), "Alice"); // reads the first_name field +} +``` + +`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). + +## 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 +[`#[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](/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. + +`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 + +`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 { + ::core::convert::AsRef::as_ref( + HasField::get_field(__context__, ::core::marker::PhantomData::<__Tag__>), + ) + } +} + +impl<__Context__, __Tag__> IsProviderFor +for UseField<__Tag__> +where + __Context__: HasField<__Tag__, Value = String>, +{} +``` + +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: + +```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 +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 `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 + +- [`#[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. +- [`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/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. + +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) + +--- + +*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 new file mode 100644 index 00000000..b9856f99 --- /dev/null +++ b/docs/reference/providers/use_field_ref.md @@ -0,0 +1,115 @@ +--- +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 +--- + +# `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 + +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 +*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 `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 +value. + +## Usage + +`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. + +## 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). + +## Under the hood + +`UseFieldRef` implements the provider-side getter +[`FieldGetter`](../traits/field-access/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 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 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 +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. +- [`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. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that defines the getter this is wired to. +- [`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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..b1d10256 --- /dev/null +++ b/docs/reference/providers/use_fields.md @@ -0,0 +1,185 @@ +--- +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 +--- + +# `UseFields` + +Implement a getter component by reading each method's value from the context field named after the +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 +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 +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, 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. + +## Usage + +`UseFields` is not in the prelude; import it from `cgp::core::component`. 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 wraps the read +in `AsRef::as_ref`. + +## Examples + +A getter with two methods, each read from its same-named field, which is the case `UseField` cannot +serve: + +```rust +use cgp::core::component::UseFields; +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 +} +``` + +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 + +**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 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 the `HasFooBar` getter above, `cargo cgp expand` shows this implementation for the +generated `FooBarGetter` provider trait, with the macro's real placeholder identifiers: + +```rust +impl<__Context__> FooBarGetter<__Context__> for UseFields +where + __Context__: HasField, + __Context__: HasField, +{ + fn foo(__context__: &__Context__) -> &str { + ::core::convert::AsRef::as_ref( + HasField::get_field( + __context__, + ::core::marker::PhantomData::, + ), + ) + } + + fn bar(__context__: &__Context__) -> &u8 { + 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 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 +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 + +- [`#[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/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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..f69265d0 --- /dev/null +++ b/docs/reference/providers/use_type.md @@ -0,0 +1,214 @@ +--- +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 +--- + +# `UseType` + +Supply a concrete type as the value of an abstract-type component, binding it purely through wiring. + +:::info + +### Not the same as `#[use_type]` + +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](/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. + +::: + +## Overview + +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 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 +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](/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`, checks the wiring, +and reads the type back in generic code: + +```rust +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + 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`, 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). + +## 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 +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 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: Copy; }`, the macro generates a `UseType` +implementation for the component's own provider trait: + +```rust +impl ScalarTypeProvider<__Context__> for UseType +where + Scalar: Copy, +{ + type Scalar = Scalar; +} +``` + +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, 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 + +- [`#[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. +- [`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. + +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) + +--- + +*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 new file mode 100644 index 00000000..51ed2273 --- /dev/null +++ b/docs/reference/providers/with_context.md @@ -0,0 +1,171 @@ +--- +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`: answer a named type or getter component from the +context's own generic `HasType` or `HasField` entry. + +## Overview + +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. + +`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 not in the prelude; import it from `cgp::core::component`. It takes no type +parameter and appears as the value of a type component's or single-method getter's wiring entry: + +```rust +delegate_components! { + App { + TypeProviderComponent: UseType, + NameTypeProviderComponent: WithContext, + } +} +``` + +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::core::component::WithContext; +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 `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 + +`WithContext` is a type alias: + +```rust +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`: + +```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. + +The ideas behind it: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..889cf211 --- /dev/null +++ b/docs/reference/providers/with_delegated_type.md @@ -0,0 +1,149 @@ +--- +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 +--- + +# `WithDelegatedType` + +Resolve one or more abstract-type components from a shared table, through the `WithProvider` adapter. + +## Overview + +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 +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 + +`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 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 + +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, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + } +} +``` + +`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](/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 + +**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/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. + +## 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/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. + +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) + +--- + +*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 new file mode 100644 index 00000000..d01218ee --- /dev/null +++ b/docs/reference/providers/with_field.md @@ -0,0 +1,154 @@ +--- +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 +--- + +# `WithField` + +Wire a getter component to a named context field, through the `WithProvider` adapter. + +## 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 +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 + +`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/field-access/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, + } +} + +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 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 +`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-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 + +- [`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/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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..713bed02 --- /dev/null +++ b/docs/reference/providers/with_field_ref.md @@ -0,0 +1,164 @@ +--- +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 +--- + +# `WithFieldRef` + +Wire a getter component to a field borrowed through `AsRef`, through the `WithProvider` adapter. + +## 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 +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-access/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 be `'static` (and, for the mutable getter, also +`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, + } +} + +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 +`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 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 +[`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 +[`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 + +`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-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. + +## 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 `AsRef::as_ref`. + +## 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-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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..aa446538 --- /dev/null +++ b/docs/reference/providers/with_provider.md @@ -0,0 +1,219 @@ +--- +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 +--- + +# `WithProvider` + +Adapt a foundational provider, one implementing `TypeProvider` or `FieldGetter`, into a provider of a +specific named component. + +## Overview + +[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 +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 +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` explains why the aliases work. Like every CGP +provider, it carries no runtime value. + +## Usage + +`WithProvider` is not in the prelude; import it from `cgp::core::component`. 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`](with_context.md) | `WithProvider` | `cgp::core::component` | +| [`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: +[`#[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::*; +use cgp::core::field::impls::WithField; + +#[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, + } +} + +pub fn demo() { + let person = Person { first_name: "Ada".to_owned() }; + assert_eq!(person.name(), "Ada"); +} +``` + +`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 use it + +**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. + +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 { + ::core::convert::AsRef::as_ref( + __Provider__::get_field( + __context__, + ::core::marker::PhantomData::, + ), + ) + } +} +``` + +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 +[`WithDelegatedType`](with_delegated_type.md), and each 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-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 + 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. + +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) + +--- + +*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 new file mode 100644 index 00000000..5f1735d7 --- /dev/null +++ b/docs/reference/providers/with_type.md @@ -0,0 +1,120 @@ +--- +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 +--- + +# `WithType` + +Bind an abstract-type component to a concrete type, through the `WithProvider` adapter. + +## Overview + +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 + +`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, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + } +} +``` + +`App` wires `ScalarTypeProviderComponent` to `WithType`, so `App` implements `HasScalarType` with +`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. 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). + +## 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) + +--- + +*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/_category_.json b/docs/reference/traits/_category_.json new file mode 100644 index 00000000..352fb396 --- /dev/null +++ b/docs/reference/traits/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Traits", + "position": 6, + "link": { + "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/builder/build_field.md b/docs/reference/traits/builder/build_field.md new file mode 100644 index 00000000..ddb6f877 --- /dev/null +++ b/docs/reference/traits/builder/build_field.md @@ -0,0 +1,217 @@ +--- +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` + +Setting one currently-absent field of a builder. + +## Overview + +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 +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; + type Output; + + fn build_field(self, _tag: PhantomData, value: Self::Value) -> Self::Output; +} +``` + +`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 not in the prelude**, though its derive is. Import it from `cgp::core::field::traits`. + +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` without an impl of its own. + +## Examples + +A record built one field at a time, in either order, and a wider record built from it plus one +field: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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, + } + ); +} +``` + +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 +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 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. +- **Prefer a struct literal** in concrete code that knows every field. + +## Under the hood + +`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 +impl BuildField for Context +where + Context: UpdateField, +{ + type Value = Context::Value; + + type Output = Context::Output; + + fn build_field(self, tag: PhantomData, value: Self::Value) -> Self::Output { + self.update_field(tag, value).1 + } +} +``` + +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.** 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. + +**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`](../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 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 + +- [`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 + it. +- [`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 + pattern. + +## Source + +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs): + `BuildField` and `FinalizeBuild` + +--- + +*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 new file mode 100644 index 00000000..c41c756e --- /dev/null +++ b/docs/reference/traits/builder/finalize_build.md @@ -0,0 +1,213 @@ +--- +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` + +Turning a fully-built [partial record](/docs/reference/glossary#partial-record) back into the concrete struct. + +## Overview + +`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() + .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 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 +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. `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 not in the prelude.** Import it from `cgp::core::field::traits`. + +`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`. + +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), which emits exactly one +per record. + +## Examples + +A generic finalize over any complete builder, including a fieldless record: + +```rust +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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 {}); +} +``` + +`assemble` names only `FinalizeBuild`, yet it can bind `Target`, because the projection comes from +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 + +**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`](../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. +- **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 + +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, + } + } +} +``` + +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`, 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 +[`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.** 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. + +**It supertraits [`PartialData`](./partial_data.md)**, so naming both in a bound is redundant, and +`Target` is projected from the supertrait. + +**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 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. + +## 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`](../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: + +- [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` + +--- + +*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 new file mode 100644 index 00000000..5a539ba7 --- /dev/null +++ b/docs/reference/traits/builder/has_builder.md @@ -0,0 +1,292 @@ +--- +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` + +Starting an empty builder for a record. + +## Overview + +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 +[`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 +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. **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 does not take a receiver, and it returns that +companion at its all-absent configuration, ready to fill. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +`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 +[`#[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 +about whether you are assembling a record or redistributing one. + +## Examples + +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::core::field::traits::{BuildField, FinalizeBuild, HasBuilder, HasField}; +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(Debug, PartialEq, BuildField)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} + +pub fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) + .build_field(PhantomData::, true) + .finalize_build() +} + +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, + } + ); +} +``` + +Every step changes the partial *type*, and `finalize_build` type-checks only because every marker +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. + +## 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 +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. +- **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, 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 + +`#[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 +///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, +} +``` + +`HasBuilder` fixes the starting configuration to all-absent, where each field is stored as `()`: + +```rust +impl HasBuilder for Person { + type Builder = __PartialPerson; + fn builder() -> Self::Builder { + __PartialPerson { + first_name: (), + last_name: (), + } + } +} +``` + +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 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 +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. 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 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. +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 +[optional-field extensions](../optional/can_finalize_with_default.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. + +## 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, + and reaching it. +- [`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. +- [`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 + pattern. + +## Source + +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs): + `HasBuilder` and `IntoBuilder` + +--- + +*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 new file mode 100644 index 00000000..473c17b0 --- /dev/null +++ b/docs/reference/traits/builder/index.md @@ -0,0 +1,46 @@ +--- +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 + +Assembling a struct one field at a time, with field presence tracked in the type. + +## Overview + +[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. + +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](/docs/reference/glossary#partial-record) and the extensible builder + pattern. + +--- + +*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 new file mode 100644 index 00000000..dcf650dc --- /dev/null +++ b/docs/reference/traits/builder/into_builder.md @@ -0,0 +1,190 @@ +--- +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` + +Turning a complete record into a partial one, with every field present. + +## Overview + +[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: + +| | 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 { + type Builder; + + fn into_builder(self) -> Self::Builder; +} +``` + +`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 not in the prelude.** Import it from `cgp::core::field::traits`. + +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). + +## Examples + +Swapping one field of a complete record, the usual form of a redistribution: + +```rust +use cgp::core::field::traits::{BuildField, FinalizeBuild, IntoBuilder, 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(), + } + ); +} +``` + +`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 is useful only for what happens in between. + +## When to use it + +**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, 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*](/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 + common case without this machinery, and this family is for code that cannot name the type. + +## Under the hood + +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; + fn builder() -> Self::Builder { + __PartialPerson { + first_name: (), + last_name: (), + } + } +} +impl IntoBuilder for Person { + type Builder = __PartialPerson; + fn into_builder(self) -> Self::Builder { + __PartialPerson { + first_name: self.first_name, + last_name: self.last_name, + } + } +} +``` + +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 + +**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 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. + +**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 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 + pattern. + +## Source + +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs): + `IntoBuilder` and `HasBuilder` + +--- + +*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 new file mode 100644 index 00000000..b742916e --- /dev/null +++ b/docs/reference/traits/builder/partial_data.md @@ -0,0 +1,175 @@ +--- +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` + +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. 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. + +::: + +## Overview + +[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. + +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 { + type Target; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +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 +implement it, which is worth knowing because it is the one trait the builder and extractor sides share +directly. + +## Examples + +A generic function naming the destination of a partial value, at two configurations: + +```rust +use cgp::core::field::traits::{BuildField, HasBuilder, PartialData}; +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")); +} +``` + +`Partial::Target` is `Person` for the empty builder and the half-built one alike, since the impl +covers every configuration. + +## When to use it + +**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`](../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 + +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 +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 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 + +**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 lacks a 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`](../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. +- [`#[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: + +- [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` + +--- + +*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 new file mode 100644 index 00000000..d687841a --- /dev/null +++ b/docs/reference/traits/builder/take_field.md @@ -0,0 +1,205 @@ +--- +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` + +Removing one currently-present field from a builder. + +## Overview + +[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 +error** rather than an `Option` you have to handle. + +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 + +`TakeField` is keyed by the field's `Tag`, with two associated types and one method: + +```rust +pub trait TakeField { + type Value; + type Remainder; + + fn take_field(self, _tag: PhantomData) -> (Self::Value, Self::Remainder); +} +``` + +`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 + +**It is not in the prelude**, like the rest of the core builder family. 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` without an impl of its own. + +## Examples + +Taking a field out of a full builder, changing it, and putting it back: + +```rust +use cgp::core::field::traits::{BuildField, FinalizeBuild, IntoBuilder, 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"); +} +``` + +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 + +**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 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. +- **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. + +## Under the hood + +`TakeField` is a library blanket impl over [`UpdateField`](./update_field.md), the mirror image of +[`BuildField`](./build_field.md#under-the-hood): + +```rust +impl TakeField for Context +where + Context: UpdateField, +{ + type Value = Context::Value; + + type Remainder = Context::Output; + + fn take_field(self, tag: PhantomData) -> (Self::Value, Self::Remainder) { + self.update_field(tag, ()) + } +} +``` + +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`. The rest of the core builder +family comes from there too. + +**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. + +**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`](../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 + pattern. + +## Source + +- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs): + `TakeField` + +--- + +*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 new file mode 100644 index 00000000..b0b0a421 --- /dev/null +++ b/docs/reference/traits/builder/update_field.md @@ -0,0 +1,247 @@ +--- +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` + +The primitive that moves one field of a [partial record](/docs/reference/glossary#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 makes build order free and is what the +optional-field layer reaches for when neither direction fits. + +::: + +## Overview + +[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 + +`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 { + 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); +} +``` + +`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`. + +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 not in the prelude.** Import it from `cgp::core::field::traits`. + +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. + +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), one per field. + +## Examples + +The two transitions `BuildField` and `TakeField` pin, written as direct calls with the target marker +named: + +```rust +use cgp::core::field::impls::{IsNothing, IsPresent}; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder, UpdateField}; +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"); +} +``` + +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 + +**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 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. + +## 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. `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__> { + type Value = String; + 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 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 + +**`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`](../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. + +**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 lacks an 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 + +- [`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`](../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. + +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` + +--- + +*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/_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/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md new file mode 100644 index 00000000..4ac07e04 --- /dev/null +++ b/docs/reference/traits/casting/can_build_from.md @@ -0,0 +1,289 @@ +--- +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` + +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`, 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 +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. + +## Definition + +`CanBuildFrom` is parameterized by the source record, with an `Output` type and one method: + +```rust +pub trait CanBuildFrom { + type Output; + + fn build_from(self, source: Source) -> Self::Output; +} +``` + +`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`](../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, and a merge followed by the one field its source did +not carry: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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, +} + +// 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, + 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 +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 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 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.** 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: + +```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) + } +} +``` + +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 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). + +**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, +} + +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.** The trait lacks a borrowing form. + +## 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 + 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. + +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 + +--- + +*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 new file mode 100644 index 00000000..3796b1b0 --- /dev/null +++ b/docs/reference/traits/casting/can_downcast.md @@ -0,0 +1,204 @@ +--- +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` + +Narrowing a wide enum into a smaller one, or handing back what is left. + +## Overview + +[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 +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. + +## Definition + +`CanDowncast` is parameterized by the target enum, with a fallible method and a `Remainder` type: + +```rust +pub trait CanDowncast { + type Remainder; + + fn downcast(self, _tag: PhantomData) -> Result; +} +``` + +`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; +``` + +**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::prelude::*; +use cgp::core::field::impls::CanDowncast; + +#[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), +} + +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); +} +``` + +`.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 + +**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](../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. + +## 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. The impl hands the source's +extractor to the target's variant list: + +```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 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, 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::); +``` + +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. + +## 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 + 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. + +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 + +--- + +*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 new file mode 100644 index 00000000..e64b51bc --- /dev/null +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -0,0 +1,206 @@ +--- +title: 'CanDowncastFields — continue a narrowing' +sidebar_label: 'CanDowncastFields' +sidebar_position: 3 +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` + +Continuing a narrowing chain on a remainder. + +## Overview + +[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. + +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 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 + +`CanDowncastFields` has the same signature as [`CanDowncast`](./can_downcast.md): + +```rust +pub trait CanDowncastFields { + type Remainder; + + fn downcast_fields(self, _tag: PhantomData) -> Result; +} +``` + +`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 it nearly always follows: + +```rust +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use core::marker::PhantomData; +``` + +## Examples + +Trying a value against three candidate targets in turn: + +```rust +use cgp::prelude::*; +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use cgp::core::field::traits::FinalizeExtractResult; + +#[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), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum JustBaz { + Baz(bool), +} + +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 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 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 pays off + when the targets are type parameters or the chain is long. + +## Under the hood + +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. 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, 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. + +**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`](../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. + +## Source + +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs): + `CanDowncastFields` and the `FieldsExtractor` recursion + +--- + +*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 new file mode 100644 index 00000000..fca2eb0a --- /dev/null +++ b/docs/reference/traits/casting/can_upcast.md @@ -0,0 +1,232 @@ +--- +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` + +Widening a narrow enum into a wider one that shares its variants. + +## Overview + +[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 +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 +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 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 + +**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; +``` + +**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 + +A narrow enum widened into a wider one, with each side deriving only what the cast needs: + +```rust +use cgp::prelude::*; +use cgp::core::field::impls::CanUpcast; + +// 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), +} + +// 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), +} + +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())); +} +``` + +Neither enum names the other. They share variant *names*, matched at the type level, and that is the +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 + +**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**. 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**. 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), + } + } +} +``` + +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. + +`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 + +**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, 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::); +``` + +the error names the missing constructor, then the walk that needed it: + +```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.** The trait lacks a 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`](../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. + +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 + +--- + +*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 new file mode 100644 index 00000000..fcf86259 --- /dev/null +++ b/docs/reference/traits/casting/index.md @@ -0,0 +1,41 @@ +--- +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, without a hand-written +conversion. + +## Overview + +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. + +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) 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 + +- [Extensible variants](/docs/concepts/extensible-variants): upcasting and downcasting between enums. +- [Extensible records](/docs/concepts/extensible-records): merging records through a builder. + +--- + +*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/_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-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md new file mode 100644 index 00000000..51191ccb --- /dev/null +++ b/docs/reference/traits/field-access/field_getter.md @@ -0,0 +1,274 @@ +--- +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 form of `HasField`: field access a context chooses by wiring. + +:::info + +### Generated machinery + +**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 + +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 +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`. 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. + +## Definition + +`FieldGetter` mirrors [`HasField`](./has_field.md), with the context as an explicit +type argument instead of `&self`: + +```rust +pub trait FieldGetter { + type Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value; +} +``` + +`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 not in the prelude; import it from `cgp::core::field::traits`. 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: WithField, + } +} +``` + +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 + +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::core::component::WithProvider; +use cgp::core::field::impls::WithField; +use cgp::core::field::traits::{FieldGetter, HasField}; +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"); +} +``` + +`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**, the advanced +case. The simpler forms come first: + +- **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. + +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 + +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<__Context__, __Provider__> NameGetter<__Context__> for WithProvider<__Provider__> +where + __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, +{ + fn name(__context__: &__Context__) -> &String { + __Provider__::get_field( + __context__, + ::core::marker::PhantomData::, + ) + } +} +``` + +`UseField` implements `FieldGetter` for every tag it is asked under, reading its own `Tag` +instead, which is why it serves any getter: + +```rust +impl FieldGetter for UseField +where + Context: HasField, +{ + type Value = Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Value { + context.get_field(PhantomData) + } +} +``` + +`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 + +**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 +``` + +Wrap it, as `WithProvider`. + +**`Self` is the provider, not the context.** The context is the first type parameter, which is the +usual confusion when meeting any provider trait. + +**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. + +**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. +- [`FieldMapper`](./field_mapper.md): the lifetime-safe form, for nested access. +- [`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 split this trait + is the field-access instance of. + +## Source + +- [`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 +- [`impls/use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs): + the `UseField` impls + +--- + +*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 new file mode 100644 index 00000000..fc7b01ef --- /dev/null +++ b/docs/reference/traits/field-access/field_mapper.md @@ -0,0 +1,217 @@ +--- +title: 'FieldMapper — the provider side of MapField' +sidebar_label: 'FieldMapper' +sidebar_position: 6 +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` + +The provider-side mirror of `MapField`. + +:::info + +### Generated machinery + +**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 + +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 +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` | + +## Definition + +`FieldMapper` mirrors [`MapField`](./map_field.md), with the context as an explicit +type argument: + +```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 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`: + +```rust +use cgp::core::field::traits::FieldMapper; +``` + +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 + +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::core::component::{UseContext, WithProvider}; +use cgp::core::field::impls::UseField; +use cgp::core::field::traits::{FieldGetter, FieldMapper, HasField}; +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"); +} +``` + +`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). + +## When to use it + +**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): + +```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)) + } +} +``` + +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 + +**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. + +**`Self` is the provider, not the context.** The context is the first type parameter. + +**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, 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 built on this trait. +- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md): the + providers a chain is usually built from. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this trait + is an instance of. + +## Source + +- [`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 + +--- + +*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 new file mode 100644 index 00000000..8df71f00 --- /dev/null +++ b/docs/reference/traits/field-access/has_field.md @@ -0,0 +1,277 @@ +--- +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 +--- + +# `HasField` + +Reading a field by a type-level name, from a context you cannot name. + +## Overview + +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`. `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. + +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 + +`HasField` carries the field's type as an associated `Value` and returns a reference to it: + +```rust +pub trait HasField { + type Value; + + fn get_field(&self, _tag: PhantomData) -> &Self::Value; +} +``` + +`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 not in the prelude, though its derive is, so import it from `cgp::core::field::traits` when +you name it. 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: + +```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 + +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::core::field::traits::HasField; +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"); +} +``` + +`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. + +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 +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +## When to use it + +**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 + +`#[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 +#[diagnostic::do_not_recommend] +impl HasField for Context +where + Context: DerefMap, + Target: HasField, +{ + type Value = Value; + + fn get_field(&self, tag: PhantomData) -> &Self::Value { + self.map_deref(|context| context.get_field(tag)) + } +} +``` + +`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.** 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::macro_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; + + fn deref(&self) -> &Person { + &self.person + } +} +``` + +```text +error[E0119]: conflicting implementations of trait `cgp::macro_prelude::HasField>>>>>` for type `Wrapper` +``` + +Fields the target lacks are unaffected, so rename the wrapper's field or drop the `Deref` impl. + +**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; 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. +- [`HasFieldMut`](./has_field_mut.md): the mutable extension. +- [`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. + +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 + +- [`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 + +--- + +*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 new file mode 100644 index 00000000..adb497e4 --- /dev/null +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -0,0 +1,190 @@ +--- +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` + +Mutable tag-keyed field access. + +## Overview + +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. + +**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](/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 not in the prelude; import it from `cgp::core::field::traits`. An implementation that mutates +declares the bound on `Self`, pinning `Value` through the supertrait, and takes `&mut self`: + +```rust +Self: HasFieldMut +``` + +The call reads like its immutable sibling: + +```rust +*self.get_field_mut(PhantomData::) += 1; +``` + +## Examples + +A provider that increments a counter on its context, and a generic function that resets it through +a `Box`: + +```rust +use cgp::core::field::traits::HasFieldMut; +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); +} +``` + +`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 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 + +`#[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): + +```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 `'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 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 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` beside it is redundant. + +## Related constructs + +- [`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. + +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 + +- [`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 + +--- + +*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 new file mode 100644 index 00000000..c97b395b --- /dev/null +++ b/docs/reference/traits/field-access/index.md @@ -0,0 +1,50 @@ +--- +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 +--- + +# Field access + +Reading one field of a context by its type-level name, from code that cannot name the context. + +## Overview + +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 +[`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. + +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, 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. + +[`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 +[`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. + +--- + +*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 new file mode 100644 index 00000000..f3ead814 --- /dev/null +++ b/docs/reference/traits/field-access/map_field.md @@ -0,0 +1,210 @@ +--- +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` + +Read through a field of a generic context without adding a lifetime bound on its type. + +## Overview + +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 +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`. + +`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: + +```rust +pub trait MapField: HasField { + fn map_field( + &self, + _tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T; +} +``` + +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. Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::MapField; +``` + +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 + +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::component::WithProvider; +use cgp::core::field::impls::{ChainGetters, UseField}; +use cgp::core::field::traits::{HasField, 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"); +} +``` + +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 + +**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 + +The blanket impl reads the field once and passes the borrow to the mapper: + +```rust +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 `'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 + +**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 +``` + +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 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 +returns [`MRef`](../../types/mref.md) instead. + +**`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 twin. +- [`HasField`](./has_field.md): the supertrait, and the plain read. +- [`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. + +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface over field access. + +## Source + +- [`traits/map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): + `MapField` and `FieldMapper` + +--- + +*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 new file mode 100644 index 00000000..b88edf52 --- /dev/null +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -0,0 +1,184 @@ +--- +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 form of `HasFieldMut`: wired field access that can mutate. + +:::info + +### Generated machinery + +**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 + +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: + +| | 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; +} +``` + +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 not in the prelude; import it from `cgp::core::field::traits`. 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`: + +```rust +delegate_components! { + App { + CounterGetterComponent: WithField, + } +} +``` + +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 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_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); +} +``` + +`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 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. + +- **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 + +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: + +```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::, + ) + } +} +``` + +`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`. + +## Common Mistakes + +**`Self` is the provider, not the context.** The context is the first type parameter, and arrives as +`&mut Context` rather than as `&mut self`. + +**Implementing it means implementing [`FieldGetter`](./field_getter.md).** It is a supertrait, so +the read half is not optional. + +**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, where wired access is explained in full. +- [`HasFieldMut`](./has_field_mut.md): the consumer side you bound against. +- [`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 split this trait + is an instance of. + +## Source + +- [`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 + +--- + +*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/option_as_ref.md b/docs/reference/traits/field-access/option_as_ref.md new file mode 100644 index 00000000..da4566a3 --- /dev/null +++ b/docs/reference/traits/field-access/option_as_ref.md @@ -0,0 +1,103 @@ +--- +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 + +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. + +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).* 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/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md new file mode 100644 index 00000000..5328a821 --- /dev/null +++ b/docs/reference/traits/formatting/concat_path.md @@ -0,0 +1,201 @@ +--- +title: 'ConcatPath — join two type-level paths' +sidebar_label: 'ConcatPath' +sidebar_position: 3 +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` + +Joining two type-level paths. + +:::info + +### Generated machinery + +**You are not expected to call `ConcatPath` directly.** +[`#[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 + +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 + +`ConcatPath` carries a single associated type and nothing else: + +```rust +pub trait ConcatPath { + type Output: ?Sized; +} +``` + +`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 not in the prelude.** Import it from `cgp::core::base::traits`, the same module as +[`StaticFormat`](./static_format.md), which is defined in the same crate. +[`StaticString`](./static_string.md) comes from `cgp::core::field::traits` instead. + +## Examples + +Two paths joined at the type level, and a generic signature naming a composed route: + +```rust +use cgp::core::base::traits::ConcatPath; +use cgp::prelude::*; + +pub type Outer = Path!(@a.b); +pub type Inner = Path!(@c.d); + +pub type Joined = >::Output; + +// 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 +} +``` + +`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 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)** 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 + a type; decoding it means decoding each segment's symbol. + +## 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: + +```rust +impl ConcatPath for PathCons +where + Tail: ConcatPath, +{ + type Output = PathCons>::Output>; +} + +impl ConcatPath for Nil { + 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. 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: + +```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) + } +} +``` + +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)` 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 +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. + +**Its module differs from [`StaticString`](./static_string.md)'s.** `ConcatPath` comes from +`cgp::core::base::traits` and `StaticString` from `cgp::core::field::traits`, which 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/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. +- [`#[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: + +- [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` + +--- + +*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 new file mode 100644 index 00000000..045858c5 --- /dev/null +++ b/docs/reference/traits/formatting/index.md @@ -0,0 +1,39 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +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 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 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. None of them is in the +prelude, and they sit in two different modules, which is the group's sharpest edge. + +- [`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 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`. Import it from `cgp::core::base::traits`. + +## 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. + +--- + +*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 new file mode 100644 index 00000000..31c18d83 --- /dev/null +++ b/docs/reference/traits/formatting/static_format.md @@ -0,0 +1,214 @@ +--- +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` + +Writing a [type-level string](/docs/reference/glossary#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. + +::: + +## Overview + +[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. + +## Definition + +`StaticFormat` carries a single associated function and nothing else: + +```rust +pub trait StaticFormat { + fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error>; +} +``` + +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. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::base::traits`: + +```rust +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`, while +[`ConcatPath`](./concat_path.md), which lives in the same crate as this trait, shares its module. + +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::*; + +let s = ::default(); + +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` +delegating to its inner list. Every type-level string therefore formats, including the empty one. + +## Examples + +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; + +// A `Display` bound is all that formatting a name needs. +pub fn describe(_tag: PhantomData) -> String { + format!("missing field `{}`", Tag::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"); + + assert_eq!( + describe(PhantomData::), + "missing field `height`" + ); + + let name = FieldName(PhantomData::); + assert_eq!(format!("[{name}]"), "[width]"); +} +``` + +`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 + +**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.** + +- **`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 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, and the terminator writes nothing: + +```rust +impl StaticFormat for Chars +where + Tail: StaticFormat, +{ + fn fmt(f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{CHAR}")?; + Tail::fmt(f) + } +} + +impl StaticFormat for Nil { + fn fmt(_f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + Ok(()) + } +} +``` + +`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) + } +} +``` + +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 + +**It is not in the prelude, and its module differs from [`StaticString`](./static_string.md)'s.** +This trait and [`ConcatPath`](./concat_path.md) come from `cgp::core::base::traits`, and +`StaticString` from `cgp::core::field::traits`. 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 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. + +**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 + +- [`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 + 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 + +--- + +*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 new file mode 100644 index 00000000..9c376137 --- /dev/null +++ b/docs/reference/traits/formatting/static_string.md @@ -0,0 +1,187 @@ +--- +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` + +Recovering a [type-level string](/docs/reference/glossary#type-level-string) as a compile-time `&'static str`. + +## Overview + +[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 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. + +## Definition + +`StaticString` carries a single associated constant and nothing else: + +```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. The trait is implemented for the type-level string itself and lacks a method, because +there is nothing to call one on. + +## Usage + +**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`. Nothing needs a value or a call. + +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 eagerly and lazily, multi-byte and empty symbols, and a generic routine naming its +tag: + +```rust +use cgp::prelude::*; +use cgp::core::field::traits::StaticString; + +// 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`: reconstructed at the point of formatting + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + + assert_eq!(::VALUE, "世界你好"); + assert_eq!(::VALUE, ""); + + assert_eq!(field_name(PhantomData::), "height"); +} +``` + +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 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 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) +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`](../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 a +private `StaticBytes` trait, which only `Symbol` and `Nil` implement: + +```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 + +**It is not in the prelude, and its module differs from its neighbours'.** Import `StaticString` +from `cgp::core::field::traits`; [`ConcatPath`](./concat_path.md) and +[`StaticFormat`](./static_format.md) come from `cgp::core::base::traits`. + +**`VALUE` is a constant, so it is named through the trait.** Write +`::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.** 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: + +```rust +pub const NAME: &str = as StaticString>::VALUE; +``` + +```text +error[E0277]: the trait bound `cgp::macro_prelude::Chars<'a', Nil>: StaticString` is not satisfied +... + | ^^^^^^^^^^^^^^^ the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::macro_prelude::Chars<'a', Nil>` +``` + +## 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. + +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 + +--- + +*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 new file mode 100644 index 00000000..aaf5c37e --- /dev/null +++ b/docs/reference/traits/index.md @@ -0,0 +1,63 @@ +--- +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 +--- + +# Traits + +[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. + +## 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](/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. +- [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 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. + +--- + +*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/_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/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md new file mode 100644 index 00000000..6abc0c59 --- /dev/null +++ b/docs/reference/traits/monad/contains_value.md @@ -0,0 +1,197 @@ +--- +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` + +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/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. + +::: + +## Overview + +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. + +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 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 + +`ContainsValue` carries a single associated type and nothing else: + +```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. + +## Usage + +**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**. The trait lacks a method: it is a +type-level projection from an output type to the value beneath the wrapper. + +## Examples + +The value each shipped marker reads beneath an output, including a two-layer stack, checked as type +equalities: + +```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` 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 +} +``` + +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, 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 +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/index.md) chain steps without a branch and involve none +of this. + +## Under the hood + +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)), + } + } +} +``` + +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. + +[`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 + +**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/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 + 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) + +--- + +*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 new file mode 100644 index 00000000..29267c9d --- /dev/null +++ b/docs/reference/traits/monad/index.md @@ -0,0 +1,43 @@ +--- +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 + +The traits that give a monad marker its meaning for monadic handler composition. + +## Overview + +[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](/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](/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. + +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. + +--- + +*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 new file mode 100644 index 00000000..fd89b7cf --- /dev/null +++ b/docs/reference/traits/monad/lift_value.md @@ -0,0 +1,200 @@ +--- +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` + +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/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. + +::: + +## Overview + +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. + +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 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 + +`LiftValue` carries an associated type and two methods: + +```rust +pub trait LiftValue { + type Output; + + fn lift_value(value: Value) -> Self::Output; + fn lift_output(output: Output) -> Self::Output; +} +``` + +`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 + +**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 + +Each shipped marker's two lifting functions, called directly: + +```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); + + // 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())); +} +``` + +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 + +**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) +chain steps without a branch and involve none of this. + +## Under the hood + +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 `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 +(`ErrMonadicTrans`'s `lift_value` is `M::lift_value(Ok(value))`), which lets a stack lift through +*n* layers without depth-specific code. + +## Common Mistakes + +**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/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 + 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) + +--- + +*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 new file mode 100644 index 00000000..348bef17 --- /dev/null +++ b/docs/reference/traits/monad/monadic_bind.md @@ -0,0 +1,218 @@ +--- +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` + +Turning a continuation into one bind step of a monadic pipeline. + +:::info + +### 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 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. + +::: + +## Overview + +[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](/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. + +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](/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. + +## Definition + +`MonadicBind` carries a single associated type and nothing else: + +```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`: + +```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/pipe_monadic.md) and a marker in a wiring entry, +without naming a trait. + +The trait lacks a method: it is a type-level function from a continuation to the provider that +binds it. + +## Examples + +The bind provider each shipped marker wraps a continuation in, checked as type equalities: + +```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 +} +``` + +**`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` | `BindErr` | +| `OkMonadic` | `Err` | `Ok` | `BindOk` | + +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 + +**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 +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/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) 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. + +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. + +## Common Mistakes + +**It is not in the prelude.** Import from `cgp::extra::monad::traits`. + +**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 +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/index.md): `PipeMonadic`, `BindOk`, `BindErr`, and the monad + markers; what you actually wire. +- [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. + +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) + +--- + +*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 new file mode 100644 index 00000000..7654365b --- /dev/null +++ b/docs/reference/traits/monad/monadic_trans.md @@ -0,0 +1,205 @@ +--- +title: 'MonadicTrans — stack one monad on another' +sidebar_label: 'MonadicTrans' +sidebar_position: 4 +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` + +Stacking one monad on top of another. + +:::info + +### 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 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. + +::: + +## Overview + +[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. + +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](/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](/docs/reference/glossary#component).** It lacks a +generated [provider trait](/docs/reference/glossary#provider-trait) and is never wired. + +## Definition + +`MonadicTrans` carries a single associated type and nothing else: + +```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. 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 + +**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. The trait lacks a method: it is a type-level function from a base +monad to a composed one. + +## Examples + +What applying each shipped marker as a transformer produces, checked as type equalities: + +```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; + +// `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 +} +``` + +`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 + +**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 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 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. 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. 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 + +**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**, 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. + +## 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/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. + +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) + +--- + +*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/_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/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md new file mode 100644 index 00000000..a8f37236 --- /dev/null +++ b/docs/reference/traits/namespace/default_impls1.md @@ -0,0 +1,306 @@ +--- +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` + +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. + +::: + +## Overview + +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 + +`DefaultImpls1` carries a single associated type and nothing else: + +```rust +pub trait DefaultImpls1 { + type Delegate; +} +``` + +`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 +[`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 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. + +::: + +## 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: + +```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 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 the `String` default to a context pulling +registered defaults in and adding an entry for a type the registry does not cover: + +```rust +use core::fmt::Display; +use cgp::prelude::*; +use cgp::core::component::DefaultImpls1; + +#[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"); +} +``` + +**[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. After + +```rust +cgp_namespace! { + new DefaultShowComponents { + [String, u64]: ShowWithDisplay, + } +} +``` + +a `for in DefaultShowComponents { … }` loop wires the listed types through the same +projection. + +## When to use it + +**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(...)]`](../../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. +- **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](/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 +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 + +A `for in DefaultImpls1 { … }` loop emits a +[`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 +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 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: + +```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 + +**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.** 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.** 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. + +## 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. +- [`#[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. +- [`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) + +--- + +*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 new file mode 100644 index 00000000..85669693 --- /dev/null +++ b/docs/reference/traits/namespace/default_impls2.md @@ -0,0 +1,226 @@ +--- +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` + +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. + +::: + +## Overview + +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 + +`DefaultImpls2` carries a single associated type and nothing else: + +```rust +pub trait DefaultImpls2 { + type Delegate; +} +``` + +`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 the library generates +nothing to pattern-match against. The [next section](#usage) shows what a use looks like. + +::: + +## Usage + +**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 = Provider; +} +``` + +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-parameter component, a default registered under a pair, and a context pulling in every default +for one target type: + +```rust +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 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); +} +``` + +**[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 + +**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, 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 + 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-use-it). + +## Under the hood + +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 +impl<__Components__> DefaultImpls2 for String { + type Delegate = ParseU64; +} +``` + +The `for … in` loop emits a [`DelegateComponent`](../wiring/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 parameters are unconstrained and the compiler rejects the impl with `E0207`, as +[`DefaultImpls1`](./default_impls1.md#common-mistakes) shows. + +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.** 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`. + +**`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 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. + +## 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`](../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 + 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) + +--- + +*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 new file mode 100644 index 00000000..9b9a59df --- /dev/null +++ b/docs/reference/traits/namespace/default_namespace.md @@ -0,0 +1,261 @@ +--- +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` + +Resolving a namespace's default provider for a component. + +:::info + +### Generated machinery + +**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. + +::: + +## Overview + +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. +[`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 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 + +`DefaultNamespace` carries a single associated type and nothing else: + +```rust +pub trait DefaultNamespace { + type Delegate; +} +``` + +`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. 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 + +**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): + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + } +} +``` + +after which every lookup `App` does not wire directly forwards through the namespace. A component +registers into one with the [`#[prefix(...)]`](../../attributes/prefix.md) attribute on its +`#[cgp_component]` trait. + +## Examples + +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)] +#[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"); +} +``` + +**[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 + +**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. +- **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 + 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 + +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, 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<__Key__, __Value__> DelegateComponent<__Key__> for App +where + __Key__: DefaultNamespace, +{ + type Delegate = __Value__; +} +impl< + __Key__, + __Value__, + __Context__, + __Params__: ?Sized, +> IsProviderFor<__Key__, __Context__, __Params__> for App +where + __Key__: DefaultNamespace, + __Value__: IsProviderFor<__Key__, __Context__, __Params__>, +{} +``` + +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 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. + +## Common Mistakes + +**A namespace entry cannot be overridden from the context.** A direct entry for a key the namespace +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 +type takes the `Self` position instead. The inconsistency is the family's sharpest edge. + +**It is in the prelude while its two siblings are not.** They come from `cgp::core::component`. + +**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 +[`#[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. +- [`#[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. +- [`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. + +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 +- Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) + +--- + +*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 new file mode 100644 index 00000000..b647a466 --- /dev/null +++ b/docs/reference/traits/namespace/index.md @@ -0,0 +1,44 @@ +--- +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 + +The lookup traits behind a namespace and a per-type default. + +## Overview + +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 +[`#[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(...)]`](../../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`. +- [`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. + +--- + +*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/_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/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md new file mode 100644 index 00000000..f6b6c83f --- /dev/null +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -0,0 +1,230 @@ +--- +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 source''s fields by name and filling the rest from Default.' +--- + +# `CanBuildWithDefault` + +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. + +`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`, +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 because +those three lines, written out, say only that one record is widened into another. + +## Definition + +`CanBuildWithDefault` is keyed by the source record and builds the target directly: + +```rust +pub trait CanBuildWithDefault { + fn build_with_default(source: Source) -> Self; +} +``` + +`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 + +**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)`. + +## Examples + +Widening a record without naming a field, in one call and as the three calls it stands for: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::HasBuilder; +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); +} +``` + +Neither struct knows about the other. They share field *names*, matched at the type level, and `z` is +filled because `u64: Default`. + +## 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. + +- **[`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 + hand-written `From` is clearer, requires nothing of either type, and lets you choose values other than + `Default`. + +## Under the hood + +The trait's one impl chains the three steps and constrains each with a bound: + +```rust +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 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). + +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 only a builder.** Deriving only +[`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` lacks `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. + +**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: + +```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(), +}); +``` + +lacks a 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 + +- [`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. + +## 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` + +--- + +*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 new file mode 100644 index 00000000..ecc2197a --- /dev/null +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -0,0 +1,232 @@ +--- +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.' +--- + +# `CanFinalizeWithDefault` + +Finalizing a [partial record](/docs/reference/glossary#partial-record), filling whatever is unset from `Default`. + +## Overview + +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 +[`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: + +| | a field left unset | +|---|---| +| `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 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 + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::CanFinalizeWithDefault; +``` + +**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, from an optional builder and from a core one: + +```rust +use cgp::core::field::traits::{BuildField, HasBuilder}; +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); +} +``` + +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 + +**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`](../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. +- **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 + +The trait's one 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. 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 +[`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. + +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. + +## Common Mistakes + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**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); + +#[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) 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). + +**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`, as the [example](#examples) shows. + +**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 + entry points. +- [`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 + 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` + +--- + +*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 new file mode 100644 index 00000000..7e8a8f40 --- /dev/null +++ b/docs/reference/traits/optional/finalize_optional.md @@ -0,0 +1,230 @@ +--- +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` + +Finalizing an optional builder, reporting a missing field. + +## Overview + +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: + +| | a field left unset | +|---|---| +| `FinalizeOptional` | `Err("field_name")` | +| [`CanFinalizeWithDefault`](./can_finalize_with_default.md) | filled from `Default` | + +## Definition + +`FinalizeOptional` [supertraits](/docs/reference/glossary#supertrait) [`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](/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 + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +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). 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::prelude::*; +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; + +#[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")); +} +``` + +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 + +**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 + same value can go either way. +- **[`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, + 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 + +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*. The trait's one impl hands the walk the builder and finalizes whatever comes back: + +```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: + +```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 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 +`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 one missing field and is not a structured error, so it +cannot be matched on beyond string comparison. + +**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 +``` + +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.** 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 + +- [`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`](../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 + fits. + +## Source + +- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs): + `FinalizeOptional` + +--- + +*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 new file mode 100644 index 00000000..f09fe92a --- /dev/null +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -0,0 +1,206 @@ +--- +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` + +Starting a builder in which every field is already optional. + +## Overview + +[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 +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 { + type Builder; + + fn optional_builder() -> Self::Builder; +} +``` + +`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 + +**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; +``` + +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 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 +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) fills unset fields from `Default`. + +## Examples + +An all-optional builder, set in any order and finished by each of the two endings: + +```rust +use cgp::prelude::*; +use cgp::extra::field::impls::{ + CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, +}; + +#[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")); +} +``` + +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 + +**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`](../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, 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, or computed defaults that are not `Default::default()`. This layer models presence and defaulting, + and nothing else. + +## Under the hood + +The trait's one impl is a blanket impl over the core builder and [`ToOptional`](./to_optional.md): + +```rust +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. 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`. + +## Common Mistakes + +**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 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. + +**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, 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. +- [`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 + 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` + +--- + +*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 new file mode 100644 index 00000000..deb890b9 --- /dev/null +++ b/docs/reference/traits/optional/index.md @@ -0,0 +1,49 @@ +--- +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 + +Relaxing the strict record builder, so a field can be set in any order or left unset. + +## Overview + +[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. + +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 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. + +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. + +--- + +*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 new file mode 100644 index 00000000..e35c751e --- /dev/null +++ b/docs/reference/traits/optional/set_optional.md @@ -0,0 +1,204 @@ +--- +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.' +--- + +# `SetOptional` + +Setting one field of an optional builder, as many times as you like. + +## Overview + +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 + +`SetOptional` is keyed by the field's tag and exposes the field's type as an associated `Value`: + +```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); +} +``` + +`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 does not declare a [supertrait](/docs/reference/glossary#supertrait). 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`: + +```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`. The trait lacks an "unset" operation: a +field starts absent and stays so unless it is set. + +## Examples + +Setting fields in any order, and re-setting one: + +```rust +use cgp::prelude::*; +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; + +#[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"); +} +``` + +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 + +**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`](../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 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 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 +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 = Context` +pins the result to the same type on both sides. **That pinning allows repeated sets:** +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. + +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. + +## Common Mistakes + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**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 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`.** 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 +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`](../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 + fits. + +## Source + +- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs): + `SetOptional` + +--- + +*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 new file mode 100644 index 00000000..5d6251d2 --- /dev/null +++ b/docs/reference/traits/optional/to_optional.md @@ -0,0 +1,202 @@ +--- +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` + +Re-marking every field of an existing builder as optional. + +## Overview + +[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. + +## Definition + +`ToOptional` carries the re-marked builder type as an associated `Output` and converts a partial value +into it: + +```rust +pub trait ToOptional { + type Output; + + fn to_optional(self) -> Self::Output; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::ToOptional; +``` + +You call it on a partial value, as `builder.to_optional()`. + +## Examples + +Relaxing a partly filled core builder, and then a complete value: + +```rust +use cgp::core::field::traits::{BuildField, HasBuilder, IntoBuilder}; +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); +} +``` + +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 + +**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`](../builder/into_builder.md) then `to_optional`** to relax a complete value, typically before + overwriting some of its fields. +- **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 blanket impl over a [`TransformMapFields`](../type-level/transform_map_fields.md) +walk carrying the [`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: + +```rust +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 impls decide the +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 +same recursion with a different marker**, which is why the defaulted and optional workflows behave so +symmetrically. + +## Common Mistakes + +**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 does not apply to a builder that is already optional.** Converting the result of +`optional_builder()` again: + +```rust +let _ = Context::optional_builder().to_optional(); +``` + +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 +... + = note: the following trait bounds were not satisfied: + `__PartialContext: TransformMapFields` +``` + +**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 +(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`](../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 + 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` + +--- + +*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 new file mode 100644 index 00000000..1597328a --- /dev/null +++ b/docs/reference/traits/optional/transform_map_default.md @@ -0,0 +1,207 @@ +--- +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.' +--- + +# `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 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. + +::: + +## Overview + +[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 +[`finalize_with_default`](./can_finalize_with_default.md) or +[`build_with_default`](./can_build_with_default.md), without naming the marker. + +## Definition + +`TransformMapDefault` is a zero-sized marker type: + +```rust +pub struct TransformMapDefault; +``` + +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 | +|---|---| +| `IsPresent` | itself, unchanged | +| `IsNothing` | `Default::default()` | +| `IsOptional` | its contents, or the default if `None` | + +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 + +**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`](../type-level/transform_map_fields.md) bound, which is where an operation says *which* +conversion it drives: + +```rust +Builder: TransformMapFields +``` + +**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 + +A generic function that drives the defaulting conversion across any builder, and a core builder +passed through it: + +```rust +use cgp::core::field::impls::IsPresent; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder, 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); +} +``` + +`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 + +**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](/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. +- **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, so it stores nothing. What it carries is three +[`TransformMap`](../type-level/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 keeps the three from overlapping. And note that only two carry the `T: Default` bound: a 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 +whatever state that field is in, and a record may hold fields in all three states at once. + +## Common Mistakes + +**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 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. + +**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). + +## Related constructs + +- [`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. +- [`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. + +## Source + +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs): + `TransformMapDefault` and the operations built on it + +--- + +*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 new file mode 100644 index 00000000..91e1e239 --- /dev/null +++ b/docs/reference/traits/optional/transform_optional.md @@ -0,0 +1,215 @@ +--- +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` + +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 +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. + +::: + +## Overview + +[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 +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), without +naming the marker. + +## Definition + +`TransformOptional` is a zero-sized marker type: + +```rust +pub struct TransformOptional; +``` + +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`: + +| 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` 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 + +**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`](../type-level/transform_map_fields.md) bound, which is where an operation 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 neither `Default` nor any other bound, which is why the optional +path applies to records the defaulting path does not. + +## Examples + +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::impls::IsOptional; +use cgp::core::field::traits::{BuildField, HasBuilder, 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"); +} +``` + +`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 + +**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 + `builder().to_optional()`. +- **[`TransformMapDefault`](./transform_map_default.md)** when the destination is `IsPresent` rather than + `IsOptional`. +- **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 two [`TransformMap`](../type-level/transform_map.md) impls, +distinguished by their source marker, each targeting `IsOptional`: + +```rust +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: **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 +[`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](/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`. + +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`](../builder/finalize_build.md) not. + +## Common Mistakes + +**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 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.** It lacks a method and needs nothing wired. It is named in a +bound. + +**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. + +**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`](../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. + +## 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` + +--- + +*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/_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/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md new file mode 100644 index 00000000..01f740e7 --- /dev/null +++ b/docs/reference/traits/shape/from_fields.md @@ -0,0 +1,195 @@ +--- +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` + +Rebuilding a concrete value from its shape. + +## Overview + +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. + +## Definition + +`FromFields` adds one associated function to the shape trait it extends: + +```rust +pub trait FromFields: HasFields { + fn from_fields(fields: Self::Fields) -> Self; +} +``` + +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 not in the prelude.** Import it from `cgp::core::field::traits`. 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. + +## Examples + +A generic round trip through the shape, for a struct and an enum: + +```rust +use cgp::core::field::traits::{FromFields, ToFields}; +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)); +} +``` + +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. + +- **[`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. + +## Under the hood + +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 Config { + fn from_fields(Cons(host, Cons(port, Nil)): ::Fields) -> Self { + Self { + host: host.value, + port: port.value, + } + } +} +``` + +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: + +```rust +impl FromFields for Shape { + fn from_fields(rest: ::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. + +**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`](../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. + +## 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`](../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. + +## Source + +- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs): + `FromFields` + +--- + +*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 new file mode 100644 index 00000000..228329c1 --- /dev/null +++ b/docs/reference/traits/shape/has_fields.md @@ -0,0 +1,255 @@ +--- +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` + +A type's whole shape, as a single type. + +## Overview + +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. + +`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"*. + +**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 { + type Fields; +} +``` + +`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![ + Field, + Field, +]; +``` + +## Usage + +**It is not in the prelude**, though its derive is. Import it from `cgp::core::field::traits`. + +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. + +**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 + +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 +pub fn assert_shape() +where + T: HasFields, +{ +} +``` + +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 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 + +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::core::field::traits::HasFields; +use cgp::core::field::types::Field; +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::(); +} +``` + +`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. 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. + +## 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(...)]`. + +- **`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. +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). `cargo cgp expand` on the example's +`Config` and `Shape` shows the types it puts in `Fields`: + +```rust +impl HasFields for Config { + type Fields = Product![ + Field, Field + ]; +} +impl HasFields for Shape { + type Fields = Sum![ + Field, Field + ]; +} +``` + +`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. + +**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. + +**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 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`](../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. +- [`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. +- [`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. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..755ba512 --- /dev/null +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -0,0 +1,188 @@ +--- +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` + +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. + +::: + +## Overview + +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. + +## Definition + +`HasFieldsRef` carries one generic associated type and no method: + +```rust +pub trait HasFieldsRef { + type FieldsRef<'a> + where + Self: 'a; +} +``` + +`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. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +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 shapes of two structs at the `'static` lifetime, one with a field that is itself a +reference: + +```rust +use cgp::core::field::traits::HasFieldsRef; +use cgp::core::field::types::Field; +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, + ], + >(); +} +``` + +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 + +**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`](../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. `cargo cgp expand` on the example's `Config` shows: + +```rust +impl HasFieldsRef for Config { + type FieldsRef<'__a> = Product![ + 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. + +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. + +## 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. + +**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. + +## 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`](../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. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..9cc94465 --- /dev/null +++ b/docs/reference/traits/shape/index.md @@ -0,0 +1,39 @@ +--- +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 +--- + +# Field structure + +A type's whole shape as a single type, and the conversions that move a value through it. + +## Overview + +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). + +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 +[`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. + +--- + +*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 new file mode 100644 index 00000000..1e5f9b8f --- /dev/null +++ b/docs/reference/traits/shape/to_fields.md @@ -0,0 +1,177 @@ +--- +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` + +Taking a value apart into its shape. + +## Overview + +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 +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. + +## Definition + +`ToFields` adds one method to the shape trait it extends: + +```rust +pub trait ToFields: HasFields { + fn to_fields(self) -> Self::Fields; +} +``` + +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 not in the prelude.** Import it from `cgp::core::field::traits`. 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. + +## Examples + +A value taken apart by a generic function, read from the product, and rebuilt: + +```rust +use cgp::core::field::traits::{FromFields, ToFields}; +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); +} +``` + +`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 +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`](../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, 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 Config { + fn to_fields(self) -> ::Fields { + Cons(self.host.into(), Cons(self.port.into(), Nil)) + } +} +``` + +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 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. + +## 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. + +**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](../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 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. + +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` + +--- + +*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 new file mode 100644 index 00000000..e110342e --- /dev/null +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -0,0 +1,167 @@ +--- +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` + +Walking a value's shape without consuming it. + +## Overview + +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. + +**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 { + fn to_fields_ref<'a>(&'a self) -> Self::FieldsRef<'a> + where + Self: 'a; +} +``` + +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 not in the prelude.** Import it from `cgp::core::field::traits`. + +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all +five shape traits together. + +## Examples + +Reading one entry of a value's borrowed shape, and using the value afterwards: + +```rust +use cgp::core::field::traits::ToFieldsRef; +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 +} +``` + +`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. +- **[`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. + +## Under the hood + +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 +impl ToFieldsRef for Config { + fn to_fields_ref<'__a>(&'__a 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. + +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`](../variant/has_extractor_ref.md) reads a variant without consuming the value. + +## 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. + +**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. + +## 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 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` + +--- + +*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/_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/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md new file mode 100644 index 00000000..1e726d58 --- /dev/null +++ b/docs/reference/traits/type-level/append_product.md @@ -0,0 +1,175 @@ +--- +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. + +## Overview + +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**. + +**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 + +`AppendProduct` is parameterized by the item to add and exposes the extended list as an associated type: + +```rust +pub trait AppendProduct { + type Output; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +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 +when reading a bound. + +## Examples + +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::core::field::types::{Field, Nil}; +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 +} + +/// 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, +) -> Base { + fields +} +``` + +`with_extra_field` is the generic form: its return type names the shape the routine promises, +computed from its parameters. + +## 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. 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 + concat. +- **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](../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. + +`AppendSum` does not exist. Growing a sum is not an operation this layer provides. + +## Under the hood + +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 +impl AppendProduct for Nil { + type Output = Cons; +} + +impl AppendProduct for Cons +where + Tail: AppendProduct, +{ + type Output = Cons; +} +``` + +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. + +All of this is resolved during type checking. Neither impl contains a `fn`. + +## 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. + +**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.** 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. + +**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 + +- [`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. + +## Source + +- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs): + `AppendProduct` + +--- + +*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 new file mode 100644 index 00000000..65483642 --- /dev/null +++ b/docs/reference/traits/type-level/concat_product.md @@ -0,0 +1,174 @@ +--- +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. + +## Overview + +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 +never uses it; it is provided for generic code of your own. + +## Definition + +`ConcatProduct` is parameterized by the second product and exposes the joined list as an associated +type: + +```rust +pub trait ConcatProduct { + type Output; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::ConcatProduct; +``` + +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, here for the worked concatenation and the +two `Nil` identities: + +```rust +use cgp::core::field::traits::{AppendProduct, ConcatProduct}; +use cgp::core::field::types::{Field, Nil}; +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 +} +``` + +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 + +**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`](../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`](../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. + +`ConcatSum` does not exist. Combining two sums is not an operation this layer provides. + +## Under the hood + +Two impls, one per list 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. + +## Common Mistakes + +**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`](../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 +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`](../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. + +## Source + +- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs): + `ConcatProduct` + +--- + +*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 new file mode 100644 index 00000000..baad91fa --- /dev/null +++ b/docs/reference/traits/type-level/index.md @@ -0,0 +1,43 @@ +--- +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 + +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 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. None is 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](/docs/reference/glossary#partial-record). +- [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. + +--- + +*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 new file mode 100644 index 00000000..04dfa933 --- /dev/null +++ b/docs/reference/traits/type-level/map_fields.md @@ -0,0 +1,221 @@ +--- +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` + +Rewriting every entry of a type-level list through one marker. + +:::info + +### Generated machinery + +**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 +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 + +[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 +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** +lists: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum, so one marker applies to +either. + +## 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. The trait +lacks a method, because nothing needs executing. + +## 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`: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::MapFields; +``` + +None of the markers is in the prelude; import `IsPresent`, `IsNothing`, `IsVoid`, and `IsOptional` +from `cgp::core::field::impls`. + +## Examples + +One marker applied over a product and over a sum, checked as type equalities: + +```rust +use cgp::core::field::impls::{IsNothing, IsOptional, IsPresent}; +use cgp::prelude::*; +use cgp::core::field::traits::MapFields; + +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 +} +``` + +`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 +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. +- **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`](../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`](../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 + +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 +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 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. + +All of it resolves during type checking, so a mapped shape is a name for a type rather than a +computation that runs. + +## 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`. + +**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 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.** Neither `AppendSum` nor `ConcatSum` exists. + +**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 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. + +The ideas behind it: + +- [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 + +- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs): + `MapFields`, over both lists + +--- + +*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 new file mode 100644 index 00000000..f638ff97 --- /dev/null +++ b/docs/reference/traits/type-level/map_type.md @@ -0,0 +1,229 @@ +--- +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` + +The marker trait that decides how one field of a partial type is stored. + +:::info + +### Generated machinery + +**You are not expected to implement `MapType`.** Its four markers are supplied by the library, and +the partial types parameterized by them are generated by +[`#[derive(CgpData)]`](../../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. + +::: + +## Overview + +[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 +changing its runtime representation. A builder starts every field `IsNothing` and flips each to +`IsPresent` as it is filled; an extractor starts every variant `IsPresent` and flips each to `IsVoid` +as it is ruled out. Because a flip is a change of *type parameter*, the compiler tracks exactly which +fields are filled, and refuses to finalize an incomplete one. + +## Definition + +`MapType` carries a single generic associated type and nothing else: + +```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. 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 + +Four state markers implement it, and they are the ones a partial type is parameterized by. **Neither +the trait nor its markers is in the prelude.** Import `MapType` from `cgp::core::field::traits` and +the markers from `cgp::core::field::impls`. The library +also implements it for two list mappers that are not field states, `TryPromoteProviders` in +[`PipeMonadic`](../../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 +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**. That is exactly how an +extractor discharges its remainder with an empty `match`. Records use the first, variants the second. + +**Three companions complete the picture**, each on its own page: [`MapTypeRef`](./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 + +What each standard marker stores, checked as type equalities, and generic code bounded on the trait: + +```rust +use cgp::core::field::impls::{IsNothing, IsOptional, IsPresent, IsVoid}; +use cgp::core::field::traits::MapType; +use cgp::core::field::types::Void; +use cgp::prelude::*; + +// Each function compiles only if the projection is the type on its right. +pub fn present(value: ::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"); +} +``` + +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 +you read a builder's type in an error; `IsVoid` whenever you read an extractor's. Recognizing them is the +common case, and it is most of what this page is for. + +The trait itself has narrower uses. + +- **Bound on `MapType`** when you write generic code over a partial type's marker parameter, which is + what the builder and extractor families do internally, and what you would do writing your own + partial-type machinery. +- **Implement [`TransformMap`](./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 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. + +[`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 + +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: + +```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, +} +``` + +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`](../builder/update_field.md) performs one such +transition on a value. + +## Common Mistakes + +**`IsNothing` and `IsVoid` are not interchangeable.** `IsNothing` is inhabited (`()`), `IsVoid` is not +(`Void`). Records use the first, variants the second, and an error naming the wrong one usually means the +two families have been crossed. + +**The markers are not in the prelude.** Import all four, `IsOptional` included, from +`cgp::core::field::impls`. + +**`MapType` and [`MapFields`](./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, with no *s*, is a third, unrelated thing again. + +**A new marker gets you `update_field` and nothing more.** Implementing `MapType` is easy, and the +generic `UpdateField` impls accept it, but the finalize impls, the `HasField` impls on a partial +type, and the optional layer are written against the standard markers. + +**`Map` 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`](../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. + +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): + 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` + +--- + +*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 new file mode 100644 index 00000000..ce48c5d7 --- /dev/null +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -0,0 +1,225 @@ +--- +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` + +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 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. + +::: + +## Overview + +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 +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 nothing else: + +```rust +pub trait MapTypeRef { + type Map<'a, T: 'a>: 'a; +} +``` + +`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 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 + +**Neither the trait nor its markers is in the prelude.** Import `MapTypeRef` from +`cgp::core::field::traits`, and `IsRef`, `IsMut`, and `IsOwned` from `cgp::core::field::impls`. +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; } +``` + +:::warning + +**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 + +What each standard marker stores at a lifetime, and the two borrowed extractors that fix it: + +```rust +use cgp::core::field::impls::{IsMut, IsOwned, IsRef}; +use cgp::core::field::traits::{ExtractField, HasExtractorMut, HasExtractorRef, MapTypeRef}; +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 })); +} +``` + +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 + +**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`](../variant/has_extractor_ref.md) rather than consumed. + +- **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 + 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`](../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. + +## 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. `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>>), +} +``` + +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 +stays valid for the whole of the borrow. + +## Common Mistakes + +**`IsOwned` is unused by CGP.** It is a legal marker that nothing consumes, so selecting it means +writing the machinery that uses it yourself. + +**The markers are not in the prelude.** Import `IsOwned`, like `IsRef` and `IsMut`, from +`cgp::core::field::impls`. + +**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. + +## 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 + 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. + +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` + +--- + +*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 new file mode 100644 index 00000000..29501588 --- /dev/null +++ b/docs/reference/traits/type-level/transform_map.md @@ -0,0 +1,223 @@ +--- +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.' +--- + +# `TransformMap` + +The per-field function that converts a value from one marker's storage to another's. + +## Overview + +[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 +[`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 { + fn transform_mapped(value: M1::Map) -> M2::Map; +} +``` + +`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 + +**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 stores nothing +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 +[Common Mistakes](#common-mistakes). + +## Examples + +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::{IsNothing, IsOptional, IsPresent}; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder, 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, + } + ); +} +``` + +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, 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. + +## 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](../optional/can_finalize_with_default.md)** if what you want is defaulted or + 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, 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 is reachable only through `update_field` and a transform; a new *transform* + marker, by contrast, works immediately. + +## Under the hood + +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 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](/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. + +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 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, 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. + +**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.** It does not take a 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`](../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 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. +- [`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. + +## Source + +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs): + `TransformMap` and `TransformMapFields` + +--- + +*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 new file mode 100644 index 00000000..9fcde16e --- /dev/null +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -0,0 +1,251 @@ +--- +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` + +Applying one per-field transform across a whole [partial record](/docs/reference/glossary#partial-record). + +:::info + +### Generated machinery + +**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 +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. + +::: + +## Overview + +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 +`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 + +`TransformMapFields` is parameterized by a transform marker and a target marker, and carries one method: + +```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, 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 + +**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`](../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. + +**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 + +A transform of your own, applied at a concrete call site and through a bound: + +```rust +use cgp::core::field::impls::IsPresent; +use cgp::core::field::traits::{FinalizeBuild, IntoBuilder, 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 }); +} +``` + +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 + +**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 + [`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`](../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](/docs/reference/glossary#shape) as a type. + That trait computes the type; this one converts the values. + +## Under the hood + +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: + +```rust +impl TransformMapFields + for ContextA +where + ContextA: PartialData, + ContextB: HasFields, + ContextB::Fields: TransformMapFieldsImpl, +{ + type Output = Output; + + fn transform_map_fields(self) -> Self::Output { + ContextB::Fields::transform_map_fields(self) + } +} +``` + +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 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 +[`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. + +## 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 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 +requires. + +**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`](../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`](../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 operations built directly on this. +- [`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. + +## Source + +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs): + `TransformMapFields` and `TransformMap` + +--- + +*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/_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/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md new file mode 100644 index 00000000..c88c5bac --- /dev/null +++ b/docs/reference/traits/variant/extract_field.md @@ -0,0 +1,300 @@ +--- +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` + +Pulling one variant out of an extractor, or narrowing what remains. + +## Overview + +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. + +`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 +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 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*. + +## Definition + +`ExtractField` takes one variant, named by a type-level tag, out of an extractor: + +```rust +pub trait ExtractField { + type Value; + type Remainder; + + fn extract_field(self, _tag: PhantomData) -> Result; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +`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. + +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.md), written here in both orders: + +```rust +use cgp::core::field::traits::{ExtractField, FinalizeExtractResult, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + 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); +} +``` + +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 like the one above, generated, +with one implementation per variant chosen by wiring. + +## 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 +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 + 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/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`](../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. `cargo cgp expand` on the example's +`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), +} +``` + +[`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< + >::Value, + >::Remainder, + > { + match self { + __PartialShape::Circle(value) => Ok(value), + __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), + } + } +} +``` + +**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 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, 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. 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. + +**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). + +## Related constructs + +- [`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`](../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 + impl here. +- [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 + comes from. + +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): + `ExtractField` and the rest of the family + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +library's source. See +[How AI is used in this project](/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 new file mode 100644 index 00000000..415ac8db --- /dev/null +++ b/docs/reference/traits/variant/finalize_extract.md @@ -0,0 +1,215 @@ +--- +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` + +Discharging an extractor that has nothing left in it. + +## Overview + +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. + +**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 +finalizes because the value is *complete*, an extraction because the value is *impossible*. + +## Definition + +```rust +pub trait FinalizeExtract { + fn finalize_extract(self) -> T; +} +``` + +`Self` is the exhausted remainder, and `finalize_extract` consumes it to return whatever type `T` +the surrounding code needs. That return is sound because the receiver is uninhabited: no value of it +can exist, so no execution path reaches the method. The library implements the trait for the +uninhabited [`Void`](../../types/void.md) and the standard `Infallible`, and the derive for the +all-ruled-out configuration of each partial enum, owned and borrowed. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +**You will usually call [`FinalizeExtractResult`](./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 on partial enums come from +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md); the library supplies the ones +for `Void` and `Infallible`. + +## Examples + +Called directly, on a remainder a nested `match` has unwrapped: + +```rust +use cgp::core::field::traits::{ExtractField, FinalizeExtract, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub fn describe(shape: Shape) -> String { + match shape.to_extractor().extract_field(PhantomData::) { + 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" + ); +} +``` + +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 +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/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`](../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, 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 {} + } +} +impl<'__a__, __R__: MapTypeRef> FinalizeExtract +for __PartialRefShape<'__a__, __R__, IsVoid, IsVoid> { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} + } +} +``` + +The library's own impls for `Void` and `Infallible` have the same one-line body. An empty `match` is +legal because no value of the scrutinee's type can exist, and it satisfies any return type for the +same reason. So a caller reaches `finalize_extract` only after trying every variant, and the +compiler accepts the discharge without a fallback. + +**This is where the record and variant families diverge, and the difference decides the whole +design.** A record uses `IsNothing` for a missing field, which maps to `()` and is *inhabited*: an +absent field is a real state a value can be in. A variant uses `IsVoid`, which is *uninhabited*: a +ruled-out variant is a state no value can be in. That is why a builder needs an explicit all-present +[`FinalizeBuild`](../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`. 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; no value exists, so nothing executes. + +**Absence is `IsVoid` here and `IsNothing` in a builder.** An error naming the wrong one usually means +record and variant machinery have been crossed. + +**Adding a variant re-inhabits the final remainder**, so every hand-written chain stops compiling. That +is the guarantee, and the reason to prefer the +[dispatch combinators](../../providers/dispatch/index.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`](../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. + +## 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 + +--- + +*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 new file mode 100644 index 00000000..b74e8796 --- /dev/null +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -0,0 +1,222 @@ +--- +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` + +Collapsing the `Result` at the end of an extraction chain. + +## Overview + +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 +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 { + type Output; + + fn finalize_extract_result(self) -> Self::Output; +} +``` + +`Self` is the `Result` and `Output` is the payload alone. The trait has one blanket impl, for any +`Result` whose error half can be discharged, shown in [Under the hood](#under-the-hood). + + + +`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 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::{ExtractField, FinalizeExtractResult, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + 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); +} +``` + +The code needs neither `.unwrap()`, `expect`, nor a wildcard arm. The call compiles only because +both variants have been tried, which makes it a proof rather than an assertion; the +[Common Mistakes](#common-mistakes) section shows the call one step early. + +## When to use it + +**Use it to close every hand-written extraction chain**, and prefer not writing the chain at all. + +- **`finalize_extract_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/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. This trait does not resolve on such a single attempt. +- **A `match`** when the enum is concrete. + +## Under the hood + +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. + +`Output` is an associated type rather than a generic, so the call can sit at the end of a method +chain with nothing to annotate. + +## Common Mistakes + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. Without the import, a +complete chain on a one-variant enum: + +```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: + +```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()`, it compiles to a single path: the +`Err` case is discharged at the type level. + +**It applies to any `Result` with a dischargeable error**, not only to extraction remainders, which is +occasionally surprising when it resolves somewhere you did not expect. + +**Adding a variant breaks the call**, by design: the final remainder becomes inhabited again and the +bound stops being satisfied. + +## Related constructs + +- [`FinalizeExtract`](./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 + 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 + +--- + +*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 new file mode 100644 index 00000000..e28b42ef --- /dev/null +++ b/docs/reference/traits/variant/from_variant.md @@ -0,0 +1,262 @@ +--- +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` + +Generic construction of an enum from a named variant. + +## Overview + +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. + +`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.** 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 + +`FromVariant` carries the variant's 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; +} +``` + +`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 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 + +The trait is not in the prelude; import it from `cgp::core::field::traits`. 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. + +The associated `Value` makes a generic signature possible: a function that does not know the variant +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, with its payload type following the tag, and a narrow enum widens +into `Shape`: + +```rust +use cgp::core::field::traits::FromVariant; +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(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 })); +} +``` + +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 name it. + +- **Bound on it in a routine parameterized over the variant it produces.** Nothing else can do it. +- **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 + [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md), which bundles construction, deconstruction, and the + [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 +[`BuildField`](../builder/has_builder.md). + +## Under the hood + +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: ::core::marker::PhantomData, + value: >::Value, + ) -> Self { + Self::Circle(value) + } +} +impl FromVariant for Shape { + type Value = Rectangle; + fn from_variant( + _tag: ::core::marker::PhantomData, + value: >::Value, + ) -> Self { + Self::Rectangle(value) + } +} +``` + +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 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 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::macro_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 `Shape::from_variant(PhantomData::, circle)` reports an unsatisfied +bound: + +```text +error[E0277]: the trait bound `Shape: cgp::macro_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::macro_prelude::FromVariant>>>>>>>` for type `Shape` +... +14 | Circle(Circle), + | ^^^^^^ conflicting implementation for `Shape` +``` + +**Every variant needs one unnamed payload or none**, which is the derive's requirement rather than +the trait's: a multi-field or struct-style variant with fields cannot be given a single `Value`, +while a variant with no fields has the `Value` `Nil`. Wrap a richer 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`](../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 + 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) + +--- + +*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 new file mode 100644 index 00000000..b29c7cd5 --- /dev/null +++ b/docs/reference/traits/variant/has_extractor.md @@ -0,0 +1,210 @@ +--- +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` + +Turning an enum into an extractor, and back. + +## Overview + +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 | +|---|---|---| +| `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 { + type Extractor; + + fn to_extractor(self) -> Self::Extractor; + fn from_extractor(extractor: Self::Extractor) -> Self; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +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). + +## Examples + +Starting a chain, which is `to_extractor`'s job, and a round trip through `from_extractor`: + +```rust +use cgp::core::field::traits::{ExtractField, FinalizeExtractResult, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(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 })); +} +``` + +`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 + +**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/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`](../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 +impl HasExtractor for Shape { + type Extractor = __PartialShape; + fn to_extractor(self) -> ::Extractor { + match self { + Self::Circle(value) => __PartialShape::Circle(value), + Self::Rectangle(value) => __PartialShape::Rectangle(value), + } + } + fn from_extractor(extractor: ::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. + +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). + +## 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. + +**`from_extractor` only accepts an un-narrowed extractor.** Once a variant is ruled out the type is +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; +[`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. + +**Every variant must carry one unnamed payload or none** for the derive to apply at all, the family's +one real restriction, covered on the +[derive's page](../../derives/derive_extract_field.md). A variant with no fields is extracted as +`Nil`, or as `&Nil` and `&mut Nil` through the borrowed extractors. + +## 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`](../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. + +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 + +--- + +*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 new file mode 100644 index 00000000..a3668fb3 --- /dev/null +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -0,0 +1,200 @@ +--- +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` + +Obtaining an extractor that can change a payload in place. + +## Overview + +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) +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 | + +## 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, 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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), alongside the owning +and shared-borrow accessors. + +## Examples + +Changing whichever payload is present, without rebuilding the enum: + +```rust +use cgp::core::field::traits::{ExtractField, FinalizeExtractResult, HasExtractorMut}; +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 })); +} +``` + +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 + +**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/handler.md). + +## Under the hood + +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> + where + Self: '__a__; + fn extractor_mut<'__a__>(&'__a__ mut 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 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. + +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 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). + +**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 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**, so a `Result` holding one is neither +`Debug` nor `PartialEq`. + +## 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`](../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 + 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 + +--- + +*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 new file mode 100644 index 00000000..94823b04 --- /dev/null +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -0,0 +1,210 @@ +--- +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` + +Obtaining an extractor that borrows the value rather than consuming it. + +## Overview + +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. + +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 { + type ExtractorRef<'a> + where + Self: 'a; + + fn extractor_ref(&self) -> Self::ExtractorRef<'_>; +} +``` + +`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 + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. + +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), alongside the owning +and mutable accessors. + +## Examples + +Reading through a borrow, as a single attempt and as a full chain, leaves the value intact: + +```rust +use cgp::core::field::traits::{ExtractField, FinalizeExtractResult, HasExtractorRef}; +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 })); +} +``` + +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 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. +- **[`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 + +The borrowing accessors use a **second companion enum**, `__PartialRefShape`, beside the owned +`__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>>), +} +``` + +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 +impl HasExtractorRef for Shape { + type ExtractorRef<'__a__> = __PartialRefShape<'__a__, IsRef, IsPresent, IsPresent> + where + Self: '__a__; + fn extractor_ref<'__a__>(&'__a__ self) -> ::ExtractorRef<'__a__> { + match self { + Self::Circle(value) => __PartialRefShape::Circle(value), + Self::Rectangle(value) => __PartialRefShape::Rectangle(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. + +The trait lacks a `from_extractor` counterpart: a borrowed extractor cannot rebuild an owned enum, +and the original is still there anyway. + +## Common Mistakes + +**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). + +**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 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 + +- [`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. + +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 + +--- + +*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 new file mode 100644 index 00000000..3e8fe362 --- /dev/null +++ b/docs/reference/traits/variant/index.md @@ -0,0 +1,45 @@ +--- +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 + +Constructing an enum from one named variant, and taking one apart variant by variant. + +## Overview + +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 +[`#[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. + +--- + +*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/_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/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md new file mode 100644 index 00000000..4cf09638 --- /dev/null +++ b/docs/reference/traits/wiring/can_use_component.md @@ -0,0 +1,279 @@ +--- +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 +--- + +# `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 asserts, so +that its failure is legible. A hand-written bound on it is legal, and occasionally useful when +probing one case. + +::: + +## Overview + +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 +cause, often one absent field, does not appear. + +`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 trait whose meaning lives in one 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'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 not in the prelude, since the check macros name it for you; import it from +`cgp::core::component` when you write it yourself. A +[`check_components!`](../../macros/check_components.md) entry asserts it, carrying the component's +parameters after a colon: + +```rust +check_components! { + App { + GreeterComponent, + AreaCalculatorComponent: Rectangle, + } +} +``` + +The same bounds written by hand hold exactly when that check passes: + +```rust +pub fn assert_wiring() +where + App: + CanUseComponent + CanUseComponent, +{ +} +``` + +## Examples + +Two components checked on one context, one without parameters and one with a shape parameter: + +```rust +use cgp::core::component::CanUseComponent; +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); +} +``` + +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 + +**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, which is what localizes a failure in a + stack of [higher-order providers](/docs/concepts/higher-order-providers). + +**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. + +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 + +[`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: + +```rust +trait __CheckApp< + __Component__, + __Params__: ?Sized, +>: CanUseComponent<__Component__, __Params__> {} +impl __CheckApp for App {} +impl __CheckApp for App {} +``` + +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: + +- **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. + +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.** `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 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. + +**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 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. + +## Source + +- [`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). + +--- + +*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 new file mode 100644 index 00000000..988caec8 --- /dev/null +++ b/docs/reference/traits/wiring/delegate_component.md @@ -0,0 +1,344 @@ +--- +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 +--- + +# `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 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 + +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 +impl DelegateComponent for App { + type Delegate = GreetHello; +} +``` + +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. + +**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 + +`DelegateComponent` carries a single associated type and no method: + +```rust +pub trait DelegateComponent { + type Delegate; +} +``` + +`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 + +The trait is not in the prelude; import it from `cgp::core::component`. + +### Setting an entry, and reading one + +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 +pub fn provider_for() -> PhantomData<>::Delegate> +where + Table: DelegateComponent, +{ + PhantomData +} +``` + +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 an entry means, and three kinds occur: + +- **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. 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 + +`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 + +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) -> 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::(); +} +``` + +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__: ?Sized, +> IsProviderFor for App +where + GreetHello: IsProviderFor, +{} +``` + +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 +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__) + } +} +``` + +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: + +```rust +impl<__Key__, __Value__> DelegateComponent<__Key__> for App +where + __Key__: MyNamespace, +{ + type Delegate = __Value__; +} +``` + +That is how a context inherits a whole table while still adding direct entries at the keys the +namespace leaves open. + +## Common Mistakes + +**A missing entry and an unsatisfied provider are different errors.** A context that never wires the +component fails a check on the table entry: + +```rust +pub struct App; + +check_components! { + App { + GreeterComponent, + } +} +``` + +rustc names the missing entry in a help line: + +```text +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied +... +help: the trait `DelegateComponent` is not implemented for `App` +``` + +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, + } +} +``` + +It fails twice, once for the forwarding impl and once for the entry: + +```text +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` +... +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` +``` + +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. + +**`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 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, and required with it. +- [`CanUseComponent`](./can_use_component.md): combines an entry and a valid provider into one + assertion. +- [`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. + +## Source + +- [`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). + +--- + +*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 new file mode 100644 index 00000000..56a42c70 --- /dev/null +++ b/docs/reference/traits/wiring/index.md @@ -0,0 +1,45 @@ +--- +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 +--- + +# Wiring and checking + +The three traits every context's wiring rests on, and the ones a wiring error names. + +## Overview + +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. + +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 + 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. + +--- + +*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 new file mode 100644 index 00000000..5fe72639 --- /dev/null +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -0,0 +1,342 @@ +--- +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. + +:::info + +### Generated machinery + +**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 + +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, +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 trait with three type parameters: + +```rust +pub trait IsProviderFor {} +``` + +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 not in the prelude; import it from `cgp::core::component`. + +### How `Params` is filled + +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, 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 assert the trait rather than implement it, as a `where` bound on an empty function: + +```rust +pub fn assert_provider() +where + RectangleArea: IsProviderFor, +{ +} +``` + +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 + +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) -> 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!"); +} +``` + +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 + +**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: + +- **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/tooling/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. + +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 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) 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 AreaCalculator< + __Context__, + Shape, +>: IsProviderFor { +``` + +`(Shape)` is the one parameter in parentheses, not a tuple, which is the Params rule at work. + +**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<__Context__> Greeter<__Context__> for GreetHello +where + __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, +{} +``` + +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 chosen provider's marker: + +```rust +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for Person +where + GreetHello: IsProviderFor, +{} +``` + +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 + +**Read the error as "because", not "instead".** Give the example's `Person` a differently named +field, and its check fails: + +```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 +``` + +The marker is not the problem; the missing `name` field, which the error's help line names as an +unimplemented `HasField`, is. + +**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: + +```text +error[E0277]: the trait bound `RectangleArea: 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 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): 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. + +## Source + +- [`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). + +--- + +*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/_category_.json b/docs/reference/types/_category_.json new file mode 100644 index 00000000..78f2036d --- /dev/null +++ b/docs/reference/types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Types", + "position": 7, + "link": { + "type": "doc", + "id": "reference/types/index" + } +} diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md new file mode 100644 index 00000000..c59680e4 --- /dev/null +++ b/docs/reference/types/chars.md @@ -0,0 +1,216 @@ +--- +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` + +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 + +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. + +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 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 + +`Chars` is a zero-sized struct carrying one character as a const parameter and the rest of the string as +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. Neither type is in the prelude, since the macro writes them for you; import both from +`cgp::core::field::types` when you name one. + +## 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 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. 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 function or +provider reads. The same type rebuilds its string through `Display`: + +```rust +use cgp::core::field::traits::HasField; +use cgp::core::field::types::{Chars, Nil, Symbol}; +use cgp::prelude::*; + +// The tag names the field the function reads. +pub fn name_of(context: &Context) -> &str +where + Context: HasField, +{ + context.get_field(PhantomData::) +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +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); +} +``` + +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 + +**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 that mentions + `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 + string. + +## 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/tooling/cargo-cgp/check) reads the chain back into the name, and reports +``[CGP-E110] 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 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`. + +**`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. + +## 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 + `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). + +--- + +*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 new file mode 100644 index 00000000..33b37c10 --- /dev/null +++ b/docs/reference/types/cons.md @@ -0,0 +1,184 @@ +--- +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` + +The head-and-tail cell of the product list: the recursive list that describes a record, one field at a +time. + +## Overview + +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 +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 that pair a name with a value, so +a struct's layout becomes a `Product!` of `Field` cells over this list. + +## 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, 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. Neither it nor `Nil` is in the +prelude, since `Product!` writes both for you. Import them from `cgp::core::field::types` when you +name one. + +## 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 `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 +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 + +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::core::field::traits::{HasFields, ToFields}; +use cgp::core::field::types::{Cons, Field, Nil}; +use cgp::prelude::*; + +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +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; +} + +impl Len for Nil { + const LEN: usize = 0; +} + +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 +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, 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. +- **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-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 +[`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.** 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 + +- [`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. +- [`AppendProduct`](../traits/type-level/append_product.md): one of the operations that transform a + product list. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records): the record representation this list encodes. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..739efc38 --- /dev/null +++ b/docs/reference/types/either.md @@ -0,0 +1,194 @@ +--- +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` + +The head-or-rest cell of the sum list: the recursive list that describes an enum, one variant at a +time. + +## Overview + +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. + +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 that pair a +variant name with its payload, so an enum's [shape](/docs/reference/glossary#shape) becomes a `Sum!` of `Field` branches over this list. + +## 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, 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. Neither it nor +`Void` is in the prelude, since `Sum!` writes both for you. Import them from +`cgp::core::field::types` when you name one. + +## 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 `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 +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. + +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 + +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::core::field::traits::ToFields; +use cgp::core::field::types::{Cons, Either, Nil, Void}; +use cgp::prelude::*; + +#[derive(HasFields)] +pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, +} + +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 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::; +} +``` + +The derive writes `Shape`'s shape with the macros: + +```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 +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 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. +- **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 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 +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 matters less than +it sounds, 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 takes an enum + apart by variant name. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants): the variant representation this list encodes. + +## 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) + +--- + +*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 new file mode 100644 index 00000000..8b80a773 --- /dev/null +++ b/docs/reference/types/field.md @@ -0,0 +1,206 @@ +--- +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` + +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. + +## Overview + +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. +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 +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 +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`, 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 not in the prelude, so import it +from `cgp::core::field::types`. + +## Behavior + +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 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 + +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::core::field::traits::ToFields; +use cgp::core::field::types::{Cons, Field, Index, Nil}; +use cgp::prelude::*; + +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +#[derive(HasFields)] +pub struct Point(pub u32, pub u32); + +#[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\""); +} +``` + +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 + +**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 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. 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. 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 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. + +## 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. +- [`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. +- [`#[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) + +--- + +*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 new file mode 100644 index 00000000..6b430d14 --- /dev/null +++ b/docs/reference/types/index.md @@ -0,0 +1,59 @@ +--- +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 + +The types the library 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 + +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. + +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 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 a +type rather than a trait or a provider, and you name it yourself as a getter's return type. + +## 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 list describes. +- [Extensible variants](/docs/concepts/extensible-variants): the variant shape the sum list describes. + +--- + +*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 new file mode 100644 index 00000000..5b3b4bff --- /dev/null +++ b/docs/reference/types/index_type.md @@ -0,0 +1,179 @@ +--- +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` + +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 + +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 +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, 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, 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` 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](/docs/reference/glossary#shape), and as the type inside a +[`PhantomData`](phantom_data.md) wherever compile-time code needs a positional name. + +## 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 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 not +in the prelude, so import it from `cgp::core::field::types`. + +## 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 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. +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 + +A tuple struct that derives `HasField` is read by position, and an `Index` prints the number it +stands for: + +```rust +use cgp::core::field::traits::HasField; +use cgp::core::field::types::Index; +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Pair(pub u32, pub 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"); +} +``` + +The derive generates one impl pair per position. For the first field it writes: + +```rust +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 +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 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. + +## Common Mistakes + +**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::>) +} +``` + +The compiler reports +``error[E0277]: the trait bound `Point: cgp::macro_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. + +**`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::macro_prelude::HasField>>` is not satisfied``. + +## 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. +- [`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: + +- [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) + +--- + +*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 new file mode 100644 index 00000000..b94400bc --- /dev/null +++ b/docs/reference/types/life.md @@ -0,0 +1,242 @@ +--- +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` + +A lifetime lifted into a type, so a lifetime parameter can travel through machinery that accepts only +types. + +## Overview + +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 +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. +`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 + +`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 nothing at run time. Its only job is to carry the lifetime `'a` in the type system +through [`PhantomData`](phantom_data.md). It is not in the prelude, so import it from +`cgp::core::field::types`. + +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 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 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 + +A borrowing getter component, wired on a context that holds a borrow, and checked with `Life` in its +parameter tuple: + +```rust +use cgp::core::field::traits::HasField; +use cgp::core::field::types::Life; +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, +} + +#[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"); +} +``` + +`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 +pub trait ReferenceGetter< + 'a, + __Context__, + T: 'a + ?Sized, +>: IsProviderFor, T)> { + fn get_reference(__context__: &__Context__) -> &'a T; +} +``` + +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. + +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)] +#[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"); +} +``` + +## 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 +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 + +- [`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. +- [`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. + +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), + 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) + +--- + +*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 new file mode 100644 index 00000000..5adf2deb --- /dev/null +++ b/docs/reference/types/mref.md @@ -0,0 +1,222 @@ +--- +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.' +--- + +# `MRef` + +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. + +## Overview + +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 +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 a type you name in your own code, as the return type of a +getter. + +## Definition + +`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> { + Ref(&'a T), + Owned(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. It is not in the prelude; import it from +`cgp::core::field::types`. + +## Behavior + +`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` 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::core::field::types::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 + +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::core::field::impls::UseField; +use cgp::core::field::types::MRef; +use cgp::prelude::*; + +#[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, + } +} + +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!"); +} +``` + +`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 + +**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` 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 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. + +## Common Mistakes + +**`MRef` is not related to [`Life`](life.md).** Its `'a` is an ordinary borrow lifetime on a runtime +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. Use it only when you +need ownership. + +**A qualified path is not recognized.** A getter declared as +`fn greeting(&self) -> cgp::core::field::types::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. + +## 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. +- [`#[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) + +--- + +*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 new file mode 100644 index 00000000..e6f3097e --- /dev/null +++ b/docs/reference/types/nil.md @@ -0,0 +1,137 @@ +--- +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` + +The end marker of the product, string, and path lists: an empty, constructible list. + +## Overview + +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. + +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). 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 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`. It is not in the prelude, so import +it from `cgp::core::field::types`. + +## 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 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 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](/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 +ends in this inhabited one. + +## Examples + +Each list ends in `Nil`, and the empty product, the empty string, and a unit struct's shape are all +`Nil`: + +```rust +use cgp::core::base::types::PathCons; +use cgp::core::field::traits::ToFields; +use cgp::core::field::types::{Chars, Cons, Nil, Symbol}; +use cgp::prelude::*; + +#[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); +} +``` + +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 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: 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 +it is expected outside a record. + +## 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`. + +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 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 + [`path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/path.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/types/path_cons.md b/docs/reference/types/path_cons.md new file mode 100644 index 00000000..d6b81dc6 --- /dev/null +++ b/docs/reference/types/path_cons.md @@ -0,0 +1,190 @@ +--- +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` + +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. + +## Overview + +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 +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 +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 +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 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, 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 not in +the prelude, so import it from `cgp::core::base::types`, or let the prelude's `Path!` macro write it +for you. + +## 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 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. + +[`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 + +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::core::base::traits::ConcatPath; +use cgp::core::base::types::PathCons; +use cgp::core::field::types::Nil; +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 => + @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>; +} +``` + +The namespace entry expands into a `RedirectLookup` over the one-segment path. `cargo cgp expand` +prints the path in its `Path!` form: + +```rust +impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { + type Delegate = RedirectLookup<__Table__, Path!(@MyFooComponent)>; +} +``` + +which is `RedirectLookup<__Table__, PathCons>`. 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 you wire a namespace.** + +- **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 + [`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 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 +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. +- [`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): looks a path up in 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) + +--- + +*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 new file mode 100644 index 00000000..e629a25a --- /dev/null +++ b/docs/reference/types/phantom_data.md @@ -0,0 +1,272 @@ +--- +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` + +The standard-library marker that lets a type carry a type parameter without storing a value of it. +It makes 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 + +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. + +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 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` 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 +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 the struct stays empty 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 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` 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 ()>`, which makes it invariant in the +lifetime and neither `Send` nor `Sync`. That page explains the consequences. + +## How CGP uses it + +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 the type does not keep a value of it at run time. + +**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: + +```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 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 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. + +You meet `PhantomData` directly only when you work below these constructs. + +## Examples + +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::core::field::traits::HasField; +use cgp::prelude::*; + +#[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}!") + } +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetField, + } +} + +check_components! { + Person { + GreeterComponent, + } +} + +// 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.** +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 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 case you write yourself, and the turbofish names the type when + inference cannot. +- **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 + +**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. A +`PhantomData` in a signature does not mean a hidden allocation. + +**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::macro_prelude::HasField<_>` found +``` + +Write `PhantomData::` to name the field. + +**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 + +- [`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::` + 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. +- 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) + +--- + +*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 new file mode 100644 index 00000000..2a4672ed --- /dev/null +++ b/docs/reference/types/void.md @@ -0,0 +1,201 @@ +--- +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` + +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. + +## Overview + +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. + +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 + +`Void` is an empty enum: + +```rust +#[derive(Eq, PartialEq, Debug, Clone)] +pub enum Void {} +``` + +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 not in the prelude, so import it from `cgp::core::field::types`. + +## 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, 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 +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 +pub trait FinalizeExtract { + fn finalize_extract(self) -> T; +} + +impl FinalizeExtract for Void { + fn finalize_extract(self) -> T { + match self {} + } +} +``` + +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, 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::core::field::types::{Either, Void}; +use cgp::prelude::*; + +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))); + + // 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, 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 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 + 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 + +**`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. + +**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: `&Either::Right(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. + +## 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 + this one. +- [`Sum!`](../macros/sum.md): the macro whose empty form is `Void`. +- [`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: + +- [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` 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) + +--- + +*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/release-notes/_category_.json b/docs/release-notes/_category_.json new file mode 100644 index 00000000..37c64dd6 --- /dev/null +++ b/docs/release-notes/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Release notes", + "position": 12, + "link": { + "type": "doc", + "id": "release-notes/index" + } +} diff --git a/docs/release-notes/cargo-cgp/_category_.json b/docs/release-notes/cargo-cgp/_category_.json new file mode 100644 index 00000000..121b1fd3 --- /dev/null +++ b/docs/release-notes/cargo-cgp/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "cargo-cgp", + "position": 2, + "link": { + "type": "generated-index", + "slug": "/release-notes/cargo-cgp", + "description": "The release notes of cargo-cgp, the error toolchain for Context-Generic Programming (CGP) that rewrites CGP's compile errors and prints macro expansions: one page per official release, newest first." + } +} diff --git a/docs/release-notes/cargo-cgp/v0-1-0.md b/docs/release-notes/cargo-cgp/v0-1-0.md new file mode 100644 index 00000000..29069659 --- /dev/null +++ b/docs/release-notes/cargo-cgp/v0-1-0.md @@ -0,0 +1,106 @@ +--- +title: 'cargo-cgp v0.1.0 release notes' +sidebar_label: 'v0.1.0' +sidebar_position: 99900 +description: 'The first release of cargo-cgp: cargo cgp check rewrites CGP compile errors to lead with the root cause, and cargo cgp expand prints readable expansions.' +slug: v0.1.0 +--- + +# cargo-cgp v0.1.0 + +This page lists what the first release of `cargo-cgp` provides. The tool is the error toolchain of +[Context-Generic Programming (CGP)](/docs/), a Rust library whose macros generate traits and their +wiring: it rewrites CGP's compile errors to name their cause and prints the code the macros +generate. + +Released on 2026-11-18. + +- **Release post:** [CGP v0.8.0 - cargo-cgp, new documentation, and namespaces](/blog/v0.8.0-release#diagnosing-wiring-with-cargo-cgp) +- **Crate:** [`cargo-cgp` 0.1.0 on crates.io](https://crates.io/crates/cargo-cgp/0.1.0) +- **Tag:** [v0.1.0](https://github.com/contextgeneric/cargo-cgp/tree/v0.1.0) + +## Summary + +`cargo cgp check` runs `cargo check` and rewrites the CGP errors it recognizes, tagging each with a +`[CGP-Exxx]` code for its class. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. `cargo cgp expand` prints a target's +macro expansion with CGP's type-level constructs written as macros again. `cargo cgp setup` and +`cargo cgp update` install and refresh the pinned nightly and the driver built against it. + +## Compatibility + +- **Minimum Rust version:** 1.96, for the front end that `cargo install` builds. The driver + builds on the pinned nightly, `nightly-2026-11-16`, which `cargo cgp setup` installs, and a + project's own builds keep its toolchain. +- **CGP version:** the tool recognizes the errors of [`cgp` v0.8.0](/docs/release-notes/cgp/v0.8.0), + released beside it. Older CGP code compiles as it would under `cargo check`, but rewriting its + errors is untested. +- **Platforms:** tested on Linux; macOS and Windows are untested. +- **Crates:** `cargo-cgp`, `cargo-cgp-driver`, `cargo-cgp-error-processing`, and + `cargo-cgp-expand`, all at 0.1.0. + +## Upgrading + +This is the tool's first release, so there is nothing to upgrade from. Install it with +`cargo install --locked cargo-cgp` followed by `cargo cgp setup`, or through the Nix flake at +`github:contextgeneric/cargo-cgp/v0.1.0`, as [Installation](/docs/tooling/cargo-cgp/installation) +describes. + +## New features + +### Commands + +- **`cargo cgp check`** forwards its arguments to `cargo check` and rewrites each CGP error it + recognizes: it checks the program with Rust's next-generation trait solver to find the cause, + names it in the headline, draws the dependency chain, and keeps rustc's own code beside the CGP + code. Errors it does not recognize pass through unchanged, and rewriting applies to the crates of + the workspace. The errors come in the order of the code they point at, so the output is the same + on every run, however many threads the compiler checks on. See + [Check](/docs/tooling/cargo-cgp/check). +- **`cargo cgp check --message-format=json`** prints the rewritten errors as JSON, the form an + editor reads. +- **`cargo cgp expand`** prints the Rust one target's macros generate, writing a field tag as + `Symbol!("width")`, a list as `Product![A, B]`, a field list as `Struct! { width: f64 }`, and a + path as `Path!(@app.Component)`. `--item ` narrows the output to one module, type, or + trait, and the other arguments go to `cargo rustc`. See [Expand](/docs/tooling/cargo-cgp/expand). +- **`cargo cgp setup`** installs the pinned nightly with `rustc-dev` and `llvm-tools` through + rustup and builds the matching `cargo-cgp-driver` beside the front end. +- **`cargo cgp update`** reinstalls the tool when crates.io has a newer version in its release + channel, then runs that version's `setup`. +- **`--version` and `--help`** print the version and the list of commands. See + [Command reference](/docs/tooling/cargo-cgp/command-reference). + +### Error codes + +- **Whole-error codes:** 37 `CGP-E0xx` codes head a rewritten error, one per class of mistake, + grouped by kind: a trait a context cannot use, conflicting wiring, structural mistakes, wiring + that does not resolve, mistakes in a macro's input, and extensible data. +- **Dependency-step codes:** 24 `CGP-E1xx` codes label the lines of the dependency tree, for the + path through the requirements and the cause at its end. +- **A provider's missing component key:** `CGP-E041` reports a provider header whose component key + is not in scope, with the key's public import path, and a header that names its trait through a + module that re-exports the trait without its key; `CGP-E070` reports a header whose derived key is + not the component's, with a fix that names the key in the attribute. +- **Rewrites without a code:** an error the tool leaves unclassified still has its type-level + names written as macros, shorter type names, and the generated traits' notes renamed to the + consumer and provider traits. + +See [Error codes](/docs/tooling/cargo-cgp/error-codes) for each code. + +### Editor integration + +rust-analyzer can run `cargo cgp check` on save through `rust-analyzer.check.overrideCommand`, so +the editor shows the rewritten errors. `CGP-E041`'s import is a fix the editor applies on the +provider trait's name and on a wiring key, marked preferred when one path imports the key, and +`CGP-E070`'s fix appears on the trait's name the same way. See +[Editor integration](/docs/tooling/cargo-cgp/editor-integration). + +### Nix + +The repository's flake builds both binaries against the pinned nightly without rustup, and +`nix run github:contextgeneric/cargo-cgp/v0.1.0 -- check` runs the tool without installing it. + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the tool's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp-serde/_category_.json b/docs/release-notes/cgp-serde/_category_.json new file mode 100644 index 00000000..06a97f99 --- /dev/null +++ b/docs/release-notes/cgp-serde/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "cgp-serde", + "position": 3, + "link": { + "type": "generated-index", + "slug": "/release-notes/cgp-serde", + "description": "The release notes of cgp-serde, which rebuilds Serde's traits as Context-Generic Programming (CGP) components so each application chooses how a type is encoded: one page per official release, newest first." + } +} diff --git a/docs/release-notes/cgp-serde/v0-1-0.md b/docs/release-notes/cgp-serde/v0-1-0.md new file mode 100644 index 00000000..08af7a5f --- /dev/null +++ b/docs/release-notes/cgp-serde/v0-1-0.md @@ -0,0 +1,127 @@ +--- +title: 'cgp-serde v0.1.0 release notes' +sidebar_label: 'v0.1.0' +sidebar_position: 99900 +description: 'The first release of cgp-serde: Serde''s Serialize and Deserialize as CGP components, with providers for strings, bytes, dates, records, JSON, and arenas.' +slug: v0.1.0 +--- + +# cgp-serde v0.1.0 + +This page lists what the first release of cgp-serde provides. cgp-serde rebuilds Serde's +`Serialize` and `Deserialize` traits as components of +[Context-Generic Programming (CGP)](/docs/), a Rust library whose macros generate traits and their +wiring. Serde lets each type fix its encoding once; cgp-serde lets each application choose it. + +Released on 2025-11-01. + +- **Release post:** [Announcing cgp-serde](/blog/cgp-serde-release) +- **Crate:** [`cgp-serde` 0.1.0 on crates.io](https://crates.io/crates/cgp-serde/0.1.0) +- **Tag:** [v0.1.0](https://github.com/contextgeneric/cgp-serde/tree/v0.1.0) + +## Summary + +Two components, `CanSerializeValue` and `CanDeserializeValue`, move Serde's `Self` into a `Value` +parameter. The implementing type is then a context, which picks a provider for each value type. On +top of them the release ships providers that would overlap as blanket impls of Serde's traits, +encodings for bytes and dates, a JSON layer over `serde_json`, and components that let a +deserializer allocate borrowed values in an arena the context holds. + +## Compatibility + +- **Minimum Rust version:** 1.90. +- **CGP version:** requires `cgp` 0.6. +- **Crates:** `cgp-serde`, `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, and + `cgp-serde-typed-arena`, all at 0.1.0. + +## Upgrading + +This is the library's first release, so there is nothing to upgrade from. Add `cgp-serde` beside +`cgp`, with the other crates whose providers your wiring names. + +## New features + +### Components + +- **`CanSerializeValue`** writes a `Value` to a Serde `Serializer` with the context as + `&self`; its provider trait is `ValueSerializer`, and `Value` may be unsized. See + [the reference](/docs/projects/cgp-serde/reference/). +- **`CanDeserializeValue<'de, Value>`** reads a `Value` from a Serde `Deserializer` with the context + as `&self`; its provider trait is `ValueDeserializer`. +- **`UseDelegate` dispatch:** both components declare `derive_delegate: UseDelegate`, so a + context wires one provider per value type through a `UseDelegate` table. +- **`CanAlloc<'a, T>`**, in `cgp-serde-alloc`, moves a value into storage that lives for `'a` and + returns a reference to it; its provider trait is `Allocator`. See + [`CanAlloc`](/docs/projects/cgp-serde/reference/components/can_alloc). +- **`HasArena<'a, T>`**, in `cgp-serde-typed-arena`, is a getter for a `typed_arena::Arena` on + the context, with `UseDelegate` dispatch. + +### Context adapters + +- **[`SerializeWithContext`](/docs/projects/cgp-serde/reference/types/serialize_with_context)** + pairs a context with a value and implements Serde's `Serialize` through the context's + `CanSerializeValue`, so any Serde format can write the value. +- **[`DeserializeWithContext`](/docs/projects/cgp-serde/reference/types/deserialize_with_context)** + implements Serde's `DeserializeSeed` through the context's `CanDeserializeValue`. + +### Providers in `cgp-serde` + +- **[`UseSerde`](/docs/projects/cgp-serde/reference/providers/use_serde)** uses the value's own + `Serialize` and `Deserialize` impls. +- **[`SerializeString`](/docs/projects/cgp-serde/reference/providers/serialize_string)** writes any + `AsRef` as a string and reads a `String`. +- **[`SerializeBytes`](/docs/projects/cgp-serde/reference/providers/serialize_bytes)** writes any + `AsRef<[u8]>` as bytes and reads any `From<&[u8]>`; + **[`TryDeserializeBytes`](/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes)** + reads bytes through `TryFrom`. +- **[`SerializeWithDisplay`](/docs/projects/cgp-serde/reference/providers/serialize_with_display)** + writes a `Display` value as a string, and + **[`DeserializeWithFromStr`](/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str)** + reads one back through `FromStr`. +- **[`SerializeFrom`](/docs/projects/cgp-serde/reference/providers/serialize_from)** and + **[`TrySerializeFrom`](/docs/projects/cgp-serde/reference/providers/try_serialize_from)** + convert to and from `T` with `Into` or `TryInto` and encode `T` through the context. +- **[`SerializeDeref`](/docs/projects/cgp-serde/reference/providers/serialize_deref)** writes what a + reference or smart pointer points to. +- **[`SerializeIterator`](/docs/projects/cgp-serde/reference/providers/serialize_iterator)** writes + a collection iterable by reference as a sequence, and + **[`DeserializeExtend`](/docs/projects/cgp-serde/reference/providers/deserialize_extend)** reads a + sequence into any collection that is `Default` and `Extend`. +- **`SerializeFields`** writes a struct that derives CGP's field list, through `HasFields`, as a map + with each field encoded through the context, and + **[`DeserializeRecordFields`](/docs/projects/cgp-serde/reference/providers/deserialize_record_fields)** + reads such a struct back through its optional builder. +- **[`DeserializeDefault`](/docs/projects/cgp-serde/reference/providers/deserialize_default)** + reads an optional value with the inner provider, giving `Default::default()` when the value is + absent, such as a JSON `null`. + +### Providers in the other crates + +- **`cgp-serde-extra`:** + [`SerializeHex`](/docs/projects/cgp-serde/reference/providers/serialize_hex) and + [`SerializeBase64`](/docs/projects/cgp-serde/reference/providers/serialize_base64) encode bytes as + strings, and + [`SerializeRfc3339Date`](/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date) and + [`SerializeTimestamp`](/docs/projects/cgp-serde/reference/providers/serialize_timestamp) encode a + `chrono` `DateTime` as an RFC 3339 string or a Unix timestamp. +- **`cgp-serde-json`:** + [`SerializeToJsonString`](/docs/projects/cgp-serde/reference/providers/serialize_to_json_string), + [`DeserializeFromJsonReader`](/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader), + and + [`DeserializeFromJsonString`](/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string) + are `TryComputer` providers over `serde_json`, and + [`CanDeserializeJsonString`](/docs/projects/cgp-serde/reference/types/can_deserialize_json_string) + adds a `deserialize_json_string` method to every context that has an error type and can + deserialize `T` through `DeserializeFromJsonString`. +- **`cgp-serde-alloc`:** + [`DeserializeAndAllocate`](/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate) + deserializes a value and allocates it through `CanAlloc`, producing a `&'a Value`. +- **`cgp-serde-typed-arena`:** + [`AllocateWithArena`](/docs/projects/cgp-serde/reference/providers/allocate_with_arena) implements + `CanAlloc` with the arena that `HasArena` reaches. + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp-serde/v0-2-0.md b/docs/release-notes/cgp-serde/v0-2-0.md new file mode 100644 index 00000000..88da4ebf --- /dev/null +++ b/docs/release-notes/cgp-serde/v0-2-0.md @@ -0,0 +1,60 @@ +--- +title: 'cgp-serde v0.2.0 release notes' +sidebar_label: 'v0.2.0' +sidebar_position: 99800 +description: 'cgp-serde v0.2.0 moves the library to cgp v0.7.0, with the same components and providers as v0.1.0.' +slug: v0.2.0 +--- + +# cgp-serde v0.2.0 + +This page lists what cgp-serde v0.2.0 changed. cgp-serde rebuilds Serde's `Serialize` and +`Deserialize` traits as components of [Context-Generic Programming (CGP)](/docs/), a Rust library +whose macros generate traits and their wiring, and this release moves it onto +[`cgp` v0.7.0](/docs/release-notes/cgp/v0.7.0). + +Released on 2026-03-04. + +- **Crate:** [`cgp-serde` 0.2.0 on crates.io](https://crates.io/crates/cgp-serde/0.2.0) +- **Compare:** + [v0.1.0...v0.2.0](https://github.com/contextgeneric/cgp-serde/compare/v0.1.0...v0.2.0) + +## Summary + +The library requires `cgp` 0.7.0 in place of 0.6.0, the release's one breaking change. Its +components, providers, and context adapters are those of v0.1.0. The providers are written in +`cgp` 0.7.0's syntax, which changes nothing a user sees. + +## Compatibility + +- **Minimum Rust version:** 1.90. +- **CGP version:** requires `cgp` 0.7. +- **Crates:** `cgp-serde`, `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, and + `cgp-serde-typed-arena`, all at 0.2.0. + +## Upgrading + +1. Move the project to `cgp` 0.7.0, following the + [`cgp` v0.7.0 notes](/docs/release-notes/cgp/v0.7.0#upgrading); see + [The `cgp` requirement is 0.7.0](#the-cgp-requirement-is-070). +2. Change every cgp-serde crate's requirement to `0.2.0`. + +## Breaking changes + +### The `cgp` requirement is 0.7.0 + +Every cgp-serde crate requires `cgp` 0.7.0 where v0.1.0 required 0.6.0. cgp-serde's components +and a project's wiring of them must come from the same `cgp` release, so cgp-serde 0.2.0 does not +compile beside `cgp` 0.6, and a project moves to `cgp` 0.7.0 with it. + +## Improvements + +- **[`CanDeserializeJsonString`](/docs/projects/cgp-serde/reference/types/can_deserialize_json_string)** + is generated with `#[cgp_fn]` rather than written by hand. Its method and its `HasErrorType` + supertrait are unchanged, so code bounded on the trait can still name `C::Error`. + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp-serde/v0-3-0.md b/docs/release-notes/cgp-serde/v0-3-0.md new file mode 100644 index 00000000..1bdabe90 --- /dev/null +++ b/docs/release-notes/cgp-serde/v0-3-0.md @@ -0,0 +1,94 @@ +--- +title: 'cgp-serde v0.3.0 release notes' +sidebar_label: 'v0.3.0' +sidebar_position: 99700 +description: 'cgp-serde v0.3.0 moves to cgp v0.8.0, adds providers that serialize and deserialize enums, and renames SerializeFields to SerializeRecordFields.' +slug: v0.3.0 +--- + +# cgp-serde v0.3.0 + +This page lists what cgp-serde v0.3.0 changed. cgp-serde rebuilds Serde's `Serialize` and +`Deserialize` traits as components of [Context-Generic Programming (CGP)](/docs/), a Rust library +whose macros generate traits and their wiring, and this release moves it onto +[`cgp` v0.8.0](/docs/release-notes/cgp/v0.8.0) and extends it to enums. + +Released on 2026-11-18. + +- **Crate:** [`cgp-serde` 0.3.0 on crates.io](https://crates.io/crates/cgp-serde/0.3.0) +- **Compare:** + [v0.2.0...v0.3.0](https://github.com/contextgeneric/cgp-serde/compare/v0.2.0...v0.3.0) + +## Summary + +The library requires `cgp` 0.8.0, and `SerializeFields` is renamed `SerializeRecordFields` to +match `DeserializeRecordFields`. Three new providers serialize and deserialize enums, including +variants with no fields. Every published crate now has a README that is also its crate +documentation, and every public component, provider, and type has a doc comment. + +## Compatibility + +- **Minimum Rust version:** 1.90. +- **CGP version:** built on `cgp` 0.8.0, released beside it. +- **Crates:** `cgp-serde`, `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, and + `cgp-serde-typed-arena`, all at 0.3.0. + +## Upgrading + +1. Move the project to `cgp` 0.8.0, following the + [`cgp` v0.8.0 notes](/docs/release-notes/cgp/v0.8.0#upgrading); see + [The `cgp` requirement is 0.8.0](#the-cgp-requirement-is-080). +2. Replace `SerializeFields` with `SerializeRecordFields` in the wiring; see + [`SerializeFields` is renamed](#serializefields-is-renamed). +3. Change every cgp-serde crate's requirement to `0.3.0`. + +## Breaking changes + +### The `cgp` requirement is 0.8.0 + +Every cgp-serde crate requires `cgp` 0.8.0 where v0.2.0 required 0.7.0, and cgp-serde's components +and a project's wiring of them must come from the same `cgp` release. The components keep their +names, parameters, and methods, so a project's cgp-serde wiring changes only where `cgp` 0.8.0's +syntax and prelude changed. A `UseDelegate` table still dispatches the components per value type, +and `cgp` 0.8.0's `open` statement does the same without one. Introduced in +[#2](https://github.com/contextgeneric/cgp-serde/pull/2). + +### `SerializeFields` is renamed + +[`SerializeRecordFields`](/docs/projects/cgp-serde/reference/providers/serialize_record_fields) is +the provider that writes a struct as a map of its fields, which v0.2.0 named `SerializeFields`; the +old name is gone. A context that wired `SerializeFields` wires `SerializeRecordFields`. Introduced +in [#2](https://github.com/contextgeneric/cgp-serde/pull/2). + +## New features + +- **[`SerializeVariantFields`](/docs/projects/cgp-serde/reference/providers/serialize_variant_fields)** + writes an enum that derives CGP's variant list in Serde's externally tagged form, + `{"Variant": payload}`, encoding the payload through the context. The enum must be `'static`. + Introduced in [#2](https://github.com/contextgeneric/cgp-serde/pull/2). +- **[`DeserializeVariantFields`](/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields)** + reads such an enum back, finding the variant by name in text formats and by index in binary ones. + Introduced in [#2](https://github.com/contextgeneric/cgp-serde/pull/2). +- **[`SerializeUnit`](/docs/projects/cgp-serde/reference/providers/serialize_unit)** writes any + value as Serde's unit and reads a unit into the type's `Default`. Wired for `Nil`, the payload of + a variant with no fields, it writes that variant as `{"Variant": null}` in JSON, unlike Serde's + derive. Introduced in [#2](https://github.com/contextgeneric/cgp-serde/pull/2). + +## Improvements + +- **Crate documentation:** each published crate's README is its crate documentation, so docs.rs and + crates.io show the same page, and `cgp-serde`'s runs its example as a doc test. Introduced in + [#2](https://github.com/contextgeneric/cgp-serde/pull/2). +- **Doc comments:** every public component trait, provider, and type has a doc comment, most linking + its page in the website's reference; modules, methods, and struct fields do not yet have one. + Introduced in [#2](https://github.com/contextgeneric/cgp-serde/pull/2). +- **Package metadata:** each crate's `repository` names the cgp-serde repository, where v0.2.0 named + `cgp`'s; each crate has a description of its own, a `homepage`, keywords, and categories; and each + package includes the license file. Introduced in + [#2](https://github.com/contextgeneric/cgp-serde/pull/2). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/_category_.json b/docs/release-notes/cgp/_category_.json new file mode 100644 index 00000000..009c4e52 --- /dev/null +++ b/docs/release-notes/cgp/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "cgp", + "position": 1, + "link": { + "type": "generated-index", + "slug": "/release-notes/cgp", + "description": "The release notes of cgp, the Context-Generic Programming (CGP) library for pluggable trait implementations in Rust: one page per official release, newest first." + } +} diff --git a/docs/release-notes/cgp/v0-1-0.md b/docs/release-notes/cgp/v0-1-0.md new file mode 100644 index 00000000..7bcc6e2f --- /dev/null +++ b/docs/release-notes/cgp/v0-1-0.md @@ -0,0 +1,72 @@ +--- +title: 'cgp v0.1.0 release notes' +sidebar_label: 'v0.1.0' +sidebar_position: 99900 +description: 'The first release of cgp publishes the component and wiring macros, field access by name, an abstract error type, and error backends for eyre and std.' +slug: v0.1.0 +--- + +# cgp v0.1.0 + +Version 0.1.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, is its first release on crates.io. This page lists what the release provides. + +Released on 2024-09-03. + +- **Crate:** [`cgp` 0.1.0 on crates.io](https://crates.io/crates/cgp/0.1.0) +- **Tag:** [v0.1.0](https://github.com/contextgeneric/cgp/tree/v0.1.0) + +## Summary + +A trait becomes a component with `#[derive_component]`, and `delegate_components!` writes the table through which a context chooses a provider for each component. `define_components!` writes a reusable table, `#[derive(HasField)]` and `symbol!` read a context's fields by name, and `HasErrorType` with `CanRaiseError` gives generic code an error type to raise into. The release ships as 17 crates, with backends for `eyre` and standard errors. + +## Compatibility + +- **Minimum Rust version:** 1.79. +- **Released together:** the workspace's 17 crates, all at 0.1.0. The facade crates are `cgp`, `cgp-core`, and `cgp-extra`. The library crates are `cgp-component`, `cgp-field`, `cgp-error`, `cgp-async`, `cgp-sync`, `cgp-run`, and `cgp-inner`. The macro crates are `cgp-component-macro`, `cgp-component-macro-lib`, `cgp-field-macro`, `cgp-field-macro-lib`, and `cgp-async-macro`. The error backends are `cgp-error-eyre` and `cgp-error-std`. +- **Features:** the crates declare none. + +## Upgrading + +This is the first release, so there is nothing to upgrade from. A project adds `cgp = "0.1.0"` and writes `use cgp::prelude::*;`. + +## New features + +### Components and wiring + +- **`#[derive_component]` turns a trait into a component.** The attribute names the component and the provider trait positionally, as in `#[derive_component(ErrorTypeComponent, ProvideErrorType)]`. It generates the component's name struct, the provider trait with the context as an explicit first type parameter, a blanket impl of the consumer trait that forwards to the provider chosen by the context's `Components` table, and a blanket impl of the provider trait for any table that delegates the component to a provider. +- **`delegate_components!` writes a context's wiring table.** Each entry of `delegate_components! { Context { Component: Provider } }` implements `DelegateComponent` for the target type with `Provider` as its `Delegate`. An entry may name several components in brackets, as in `[A, B]: Provider`, and the target and each component may carry generic parameters ([#17](https://github.com/contextgeneric/cgp/pull/17)). See [`delegate_components!`](/docs/reference/macros/delegate_components). +- **`define_components!` writes a reusable table.** It takes the entries of `delegate_components!` and declares a struct that holds them, as in `define_components! { Name { ... } }` ([#17](https://github.com/contextgeneric/cgp/pull/17)). Beside the struct it generates a `DelegatesToName` marker trait for the types that delegate every component of the table to `Name`, and a `with_name!` macro that replaces each `@Name` in its input with the bracketed list of the table's components. +- **`DelegateComponent` and `HasComponents` hold the table.** `DelegateComponent` has an associated `Delegate` type that names the provider for a component, and `HasComponents` has an associated `Components` type that names the table of a context. See [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component). + +### Fields + +- **`HasField` reads a field by a type-level key.** Its `get_field(&self, key: PhantomData)` returns a reference to the field, whose type is the associated type `Field`, and a blanket impl gives the same access to a context that dereferences to a type with the field ([#19](https://github.com/contextgeneric/cgp/pull/19)). See [`HasField`](/docs/reference/traits/field-access/has_field). +- **`#[derive(HasField)]` implements `HasField` for each named field of a struct.** The key of each impl is `symbol!` of the field's name, and a tuple struct gets no impls. See [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field). +- **`symbol!("name")` builds a type-level string.** It expands to the `Char<'c'>` type of each character, separated by commas inside parentheses, where `Char` takes a `char` as a const parameter. + +### Errors + +- **`HasErrorType` declares the one error type of a context.** Its associated `Error` type must be `Async + Debug`, and `ErrorOf` names it. The component is `ErrorTypeComponent`, with the provider trait `ProvideErrorType`. See [`HasErrorType`](/docs/reference/components/has_error_type). +- **`CanRaiseError` converts a source error into the context's error.** `Context::raise_error(e)` returns `Self::Error`. The component is `ErrorRaiserComponent`, with the provider trait `ErrorRaiser`, and `DelegateErrorRaiser` picks the raiser for each source error type from a table. See [`CanRaiseError`](/docs/reference/components/can_raise_error). +- **`cgp-error-eyre` provides `eyre`'s `Report` as the error type.** `ProvideEyreError` sets the type, and `RaiseStdError`, `RaiseDebugError`, and `RaiseDisplayError` raise a source error that implements `std::error::Error`, `Debug`, or `Display` ([#11](https://github.com/contextgeneric/cgp/pull/11)). +- **`cgp-error-std` provides a boxed standard error.** Its `Error` is `Box`, and `HandleErrorsWithStdError` sets it as the context's error type and raises any standard error into it ([#11](https://github.com/contextgeneric/cgp/pull/11)). + +### Async + +- **`Async` abbreviates `Sized + Send + Sync + 'static`.** `cgp-async` defines the trait with a blanket impl for every such type, and its `async_trait` attribute rewrites each `async fn` of a trait to return `impl Future + Send`. +- **`cgp-sync` offers the same names without `Send` and `Sync`.** Its `Async` abbreviates `Sized + 'static`, and its `async_trait` attribute strips `async` and `.await` from a trait, so the same code compiles as synchronous code. + +### Running and composing + +- **`CanRun` runs a context.** Its `async fn run(&self) -> Result<(), Self::Error>` is the component `RunnerComponent`, with the provider trait `Runner`, in `cgp-run` ([#3](https://github.com/contextgeneric/cgp/pull/3)). See [`CanRun`](/docs/reference/components/runner). +- **`HasInner` exposes a wrapped context.** It declares an associated `Inner` type and `inner(&self) -> &Self::Inner`, as the component `InnerComponent` with the provider trait `ProvideInner`, in `cgp-inner` ([#7](https://github.com/contextgeneric/cgp/pull/7)). + +### Crates and the prelude + +- **`cgp` re-exports the rest.** `cgp::core` is `cgp-core`, which re-exports the component, error, field, and inner crates and the `Async` items, `cgp::extra` is `cgp-extra`, which re-exports `cgp-run` as `run`, and `cgp::prelude` is the core prelude. +- **The prelude brings in the names a program writes.** They are `async_trait`, `Async`, `define_components`, `delegate_components`, `derive_component`, `DelegateComponent`, `HasComponents`, `CanRaiseError`, `HasErrorType`, `symbol`, `Char`, and `HasField`. + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-2-0.md b/docs/release-notes/cgp/v0-2-0.md new file mode 100644 index 00000000..459b2d5a --- /dev/null +++ b/docs/release-notes/cgp/v0-2-0.md @@ -0,0 +1,127 @@ +--- +title: 'cgp v0.2.0 release notes' +sidebar_label: 'v0.2.0' +sidebar_position: 99800 +description: 'cgp v0.2.0 renames the component macro to cgp_component, adds type-level lists and sums and the cgp-type crate, and puts async behind feature flags.' +slug: v0.2.0 +--- + +# cgp v0.2.0 + +Version 0.2.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, renames its component macro and adds type-level lists and sums. This page lists every change a user can see and the steps that take a project there from v0.1.0. + +Released on 2024-12-08. + +- **Crate:** [`cgp` 0.2.0 on crates.io](https://crates.io/crates/cgp/0.2.0) +- **Changes:** [v0.1.0...v0.2.0](https://github.com/contextgeneric/cgp/compare/v0.1.0...v0.2.0) + +## Summary + +`#[cgp_component]` replaces `#[derive_component]` with named arguments, and `cgp_preset!` replaces `define_components!`. The `Cons`, `Nil`, `Either`, and `Void` types with the `Product!` and `Sum!` macros give CGP type-level lists and sums, and `symbol!` now builds such a list. The new `cgp-type` crate adds `HasType`, and `cgp-async` gains feature flags that can compile async code away. + +## Compatibility + +- **Minimum Rust version:** 1.81, up from 1.79. `cgp-error-std` now uses `core::error::Error`, which Rust stabilized in 1.81. +- **Released together:** the workspace's 18 crates, all at 0.2.0. +- **New crates:** `cgp-type`. +- **Features:** `cgp-async` gains `async`, `send`, `sync`, `static`, and `full`, with `full` on by default. `cgp` and `cgp-core` gain a default `full` feature that turns on `cgp-async/full`; see [the async feature flags](#async-code-compiles-away-through-feature-flags). + +## Upgrading + +A project moving from v0.1.0 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.2.0"` and use Rust 1.81 or newer. +2. **Rewrite each `#[derive_component]`** as `#[cgp_component]`, per [the component macro](#cgp_component-replaces-derive_component). +3. **Rename each `define_components!`** to `cgp_preset!`, per [the preset macro](#cgp_preset-replaces-define_components). +4. **Rename the associated type** `HasField::Field` to `Value`, per [the field type](#hasfieldfield-is-renamed-hasfieldvalue). +5. **Replace `DelegateErrorRaiser`** with `UseDelegate`, per [the error raiser](#usedelegate-replaces-delegateerrorraiser). +6. **Spell a symbol's type as a list**, and import `MaybeSend` where `#[async_trait]` is used without the prelude, per [the symbol type](#symbol-builds-a-cons-list) and [`#[async_trait]`](#async_trait-expands-through-maybesend). + +## Breaking changes + +### `#[cgp_component]` replaces `#[derive_component]` + +`#[cgp_component]` takes the component's names as `key: value` entries ([#38](https://github.com/contextgeneric/cgp/pull/38)), and the prelude no longer exports `derive_component`. + +- **Old:** `#[derive_component(NameGetterComponent, NameGetter)]`. +- **New:** `#[cgp_component { name: NameGetterComponent, context: MyContext, provider: NameGetter }]`. Only `provider` is required: `name` defaults to the provider's name followed by `Component`, and `context` defaults to `Context`. +- **What to do:** rewrite each attribute. A global search and replace does it for the common form: search for `#\[derive_component\(([\w<>, ]+), (\w+)<(\w+)>\)\]` and replace with `#[cgp_component {\n name: $1,\n provider: $2,\n context: $3,\n}]`. + +### `cgp_preset!` replaces `define_components!` + +`cgp_preset!` takes the entries that `define_components!` took ([#41](https://github.com/contextgeneric/cgp/pull/41)). The prelude no longer exports `define_components`. + +- **Old:** `define_components! { MyPreset { ... } }`. +- **New:** `cgp_preset! { MyPreset { ... } }`, which also generates a marker trait `IsMyPreset`. The generated `with_my_preset!` macro now expands through `replace_with!`, which the prelude exports. +- **What to do:** rename each use. + +### `HasField::Field` is renamed `HasField::Value` + +The associated type of `HasField` is `Value` ([#35](https://github.com/contextgeneric/cgp/pull/35)), and the new `FieldGetter` trait uses the same name. + +- **Old:** `type Field`, as in `HasField`. +- **New:** `type Value`, as in `HasField`. +- **What to do:** rename each `Field =` bound and each `Self::Field` path. `#[derive(HasField)]` generates the new name. + +### `symbol!` builds a `Cons` list + +`symbol!("name")` expands to a list of `Char` types built from `Cons` and `Nil` ([#36](https://github.com/contextgeneric/cgp/pull/36)). + +- **Old:** the expansion was the `Char<'c'>` types of the characters, separated by commas inside parentheses. +- **New:** `Cons, Cons, Cons, Cons, Nil>>>>` for `symbol!("name")`. +- **What to do:** write a field's key with `symbol!` rather than spelling out the expansion. The `HasField` impls that `#[derive(HasField)]` generates use the new key. + +### `UseDelegate` replaces `DelegateErrorRaiser` + +`UseDelegate` implements `ErrorRaiser` by looking the source error type up in `Components`, and `cgp-error` no longer exports `DelegateErrorRaiser` ([#23](https://github.com/contextgeneric/cgp/pull/23), [#24](https://github.com/contextgeneric/cgp/pull/24)). See [`UseDelegate`](/docs/reference/providers/use_delegate). + +- **Old:** `ErrorRaiserComponent: DelegateErrorRaiser`. +- **New:** `ErrorRaiserComponent: UseDelegate`, with `UseDelegate` imported from `cgp::core::component`. +- **What to do:** rename each use and add the import. + +### `#[async_trait]` expands through `MaybeSend` + +`#[async_trait]` rewrites each `async fn` of a trait to return `impl Future + MaybeSend` ([#37](https://github.com/contextgeneric/cgp/pull/37)), so `MaybeSend` must be in scope where the attribute is used. + +- **Old:** the return type named `Send`, which every module has. +- **New:** the return type names `MaybeSend`, which `use cgp::prelude::*;` imports. +- **What to do:** write `use cgp::prelude::*;` in each module that uses `#[async_trait]`. + +## New features + +### Components and wiring + +- **`UseContext`, `WithProvider`, and `WithContext` turn existing impls into providers.** `UseContext` is a provider that answers `ProvideType` and `FieldGetter` through the context's own `HasType` and `HasField`. `WithProvider` adapts a provider of a general trait into the provider of a named component, as it does for `ProvideErrorType`, and `WithContext` is `WithProvider` ([#23](https://github.com/contextgeneric/cgp/pull/23), [#24](https://github.com/contextgeneric/cgp/pull/24)). See [`UseContext`](/docs/reference/providers/use_context), [`WithProvider`](/docs/reference/providers/with_provider), and [`WithContext`](/docs/reference/providers/with_context). +- **`UseDelegate` dispatches a provider trait through a table.** It implements `ErrorRaiser` by looking the source error type up in its table, and `ProvideType` by looking the tag up ([#24](https://github.com/contextgeneric/cgp/pull/24)). +- **`replace_with!` and `for_each_replace!` rewrite a body with a list of types.** `replace_with!` replaces an identifier in a body with a bracketed list of types, and `for_each_replace!` repeats a body once for each type in a list ([#41](https://github.com/contextgeneric/cgp/pull/41)). + +### Abstract types + +- **The `cgp-type` crate adds `HasType`.** The component is `TypeComponent`, with the provider trait `ProvideType`, and `cgp::core::types` re-exports the crate. `UseType` fixes the type, `UseDelegatedType` looks the type up in a table by the tag, and `WithType` and `WithDelegatedType` adapt them to a named component ([#23](https://github.com/contextgeneric/cgp/pull/23), [#24](https://github.com/contextgeneric/cgp/pull/24)). See [`HasType`](/docs/reference/components/has_type), [`UseType`](/docs/reference/providers/use_type), and [`UseDelegatedType`](/docs/reference/providers/use_delegated_type). +- **`HasErrorType` accepts a `ProvideType` provider.** `WithProvider` implements `ProvideErrorType` when `Provider` provides the error type through `ProvideType`, as in `WithProvider>` ([#23](https://github.com/contextgeneric/cgp/pull/23)). + +### Type-level data and fields + +- **`Cons`, `Nil`, `Either`, and `Void` build lists and sums at the type level.** `Cons` and `Nil` form a product list, and `Either` and the empty `Void` form a sum. `Field` pairs a value with its name tag, and `Index` is a type-level number ([#36](https://github.com/contextgeneric/cgp/pull/36)). See [`Cons`](/docs/reference/types/cons), [`Either`](/docs/reference/types/either), and [`Field`](/docs/reference/types/field). +- **`Product!`, `product!`, and `Sum!` write those types.** `Product![A, B]` is the product type, `product![a, b]` builds a value of it, and `Sum![A, B]` is the sum type ([#36](https://github.com/contextgeneric/cgp/pull/36)). See [`Product!`](/docs/reference/macros/product) and [`Sum!`](/docs/reference/macros/sum). +- **`HasFieldMut` reads a field mutably.** `HasFieldMut` returns `&mut Self::Value`, and `#[derive(HasField)]` implements it beside `HasField` ([#23](https://github.com/contextgeneric/cgp/pull/23)). See [`HasFieldMut`](/docs/reference/traits/field-access/has_field_mut). +- **`FieldGetter` and `MutFieldGetter` are the provider traits of field access.** `UseField` implements them, and `ProvideType`, by reading the field named by `Tag`, and `WithField` adapts it to a named component ([#23](https://github.com/contextgeneric/cgp/pull/23), [#24](https://github.com/contextgeneric/cgp/pull/24)). See [`FieldGetter`](/docs/reference/traits/field-access/field_getter) and [`UseField`](/docs/reference/providers/use_field). + +### Async code compiles away through feature flags + +`cgp-async` has the features `async`, `send`, `sync`, and `static`, and `full` turns on all four ([#37](https://github.com/contextgeneric/cgp/pull/37)). + +- **`MaybeSend`, `MaybeSync`, and `MaybeStatic`** stand for `Send`, `Sync`, and `'static` when their feature is on, and for an empty trait when it is off. `Async` is now `MaybeSend + MaybeSync + MaybeStatic`. +- **`#[async_trait]`** strips `async` and `.await` from a trait when the `async` feature is off, so the code compiles as synchronous code. +- **Turning the flags off** takes `default-features = false` on `cgp`, because `cgp` and `cgp-core` depend on `cgp-async` without its default features and forward their own default `full` feature. + +## Improvements + +- **`Async` no longer requires `Sized`**, so a `dyn` trait can use it as a bound ([#34](https://github.com/contextgeneric/cgp/pull/34)). +- **`HasInner` and `ProvideEyreError` ask less of their types.** `HasInner` and its `Inner` type no longer require `Async`, and `ProvideEyreError` no longer requires the context to be `Async` ([#23](https://github.com/contextgeneric/cgp/pull/23)). +- **`cgp-error-std` builds without `std`.** It is `no_std` with `alloc`, since it uses `core::error::Error` ([#23](https://github.com/contextgeneric/cgp/pull/23)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-3-0.md b/docs/release-notes/cgp/v0-3-0.md new file mode 100644 index 00000000..9995c4e2 --- /dev/null +++ b/docs/release-notes/cgp/v0-3-0.md @@ -0,0 +1,134 @@ +--- +title: 'cgp v0.3.0 release notes' +sidebar_label: 'v0.3.0' +sidebar_position: 99700 +description: 'cgp v0.3.0 adds getter macros, cgp_type!, error wrapping, an anyhow backend, and a runtime crate, and renames the eyre and std error providers.' +slug: v0.3.0 +--- + +# cgp v0.3.0 + +Version 0.3.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, adds getter macros, one-line abstract-type declarations, and error wrapping. This page lists every change a user can see and the steps that take a project there from v0.2.0. + +Released on 2025-01-08. + +- **Release post:** [CGP Updates: v0.3.0 Release and New Chapters](/blog/v0-3-0-release) +- **Crate:** [`cgp` 0.3.0 on crates.io](https://crates.io/crates/cgp/0.3.0) +- **Changes:** [v0.2.0...v0.3.0](https://github.com/contextgeneric/cgp/compare/v0.2.0...v0.3.0) + +## Summary + +`#[cgp_getter]` and `#[cgp_auto_getter]` define getter traits that read a context's fields, and `cgp_type!` declares an abstract type in one line. `CanWrapError` adds detail to an error, the new `cgp-error-extra` crate holds generic error providers, and `cgp-error-anyhow` and `cgp-runtime` are new crates. The release also reorganizes the crates: macros and modules are no longer re-exported through the library crates, and the eyre and standard-library error providers have new names. + +## Compatibility + +- **Minimum Rust version:** 1.83, up from 1.81. +- **Released together:** the workspace's 21 crates, all at 0.3.0. +- **New crates:** `cgp-error-extra`, `cgp-error-anyhow`, and `cgp-runtime`. +- **Features:** `cgp-error-extra` has an `alloc` feature, on by default, that provides `DebugError` and `DisplayError`. `cgp-extra` has a default `full` feature that turns it on, and the `full` feature of `cgp` now forwards to `cgp-core` and `cgp-extra`. + +## Upgrading + +A project moving from v0.2.0 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.3.0"` and use Rust 1.83 or newer. +2. **Import macros and items from the prelude or a crate's root**, per [the macro re-exports](#cgp-component-and-cgp-field-no-longer-export-their-macros) and [the module paths](#crate-modules-are-private). +3. **Rename the error providers** of `cgp-error-eyre` and `cgp-error-std`, per [the renames](#the-eyre-and-std-error-providers-are-renamed). +4. **Move `cgp::core::inner`** to `cgp::extra::inner`, per [the `cgp-inner` move](#cgp-inner-moves-to-cgp-extra). +5. **Require `HasAsyncErrorType`** where code needs a `Send + Sync + 'static` error, per [the error bound](#haserrortypeerror-no-longer-requires-async). +6. **Install an eyre hook** in an application that builds `eyre` reports, per [the eyre features](#cgp-error-eyre-builds-eyre-without-its-default-features). + +## Breaking changes + +### `cgp-component` and `cgp-field` no longer export their macros + +The macro crates are no longer dependencies of the library crates they generate code for ([#47](https://github.com/contextgeneric/cgp/pull/47)). The prelude exports the macros from their own crates. + +- **Old:** `use cgp_component::{cgp_component, delegate_components};` and `use cgp_field::{symbol, HasField};` imported the macros and the derive. +- **New:** the macros come from `cgp::prelude`, or from `cgp-component-macro` and `cgp-field-macro` for a crate that depends on them directly. +- **What to do:** write `use cgp::prelude::*;`. A crate that imports through `cgp-component` or `cgp-field` adds the macro crate or switches to the prelude. + +### Crate modules are private + +The crates keep their submodules private and export each item by name ([#53](https://github.com/contextgeneric/cgp/pull/53)). + +- **Old:** an import could name a module path, such as `cgp_field::types::Char` or `cgp_type::traits::has_type::ProvideType`. +- **New:** each item is imported from its crate's root, such as `cgp_field::Char` and `cgp_type::ProvideType`. The `cgp::core` and `cgp::extra` modules stay as they were, apart from the move below. +- **What to do:** shorten each deep import to the crate root, or import from the prelude. + +### `cgp-inner` moves to `cgp-extra` + +`cgp::core` no longer re-exports `cgp-inner`, and `cgp::extra` re-exports it along with `cgp-runtime` ([#51](https://github.com/contextgeneric/cgp/pull/51)). + +- **Old:** `cgp::core::inner`. +- **New:** `cgp::extra::inner`, with the new runtime crate at `cgp::extra::runtime`. +- **What to do:** change the path. + +### `HasErrorType::Error` no longer requires `Async` + +The associated `Error` type of [`HasErrorType`](/docs/reference/components/has_error_type) requires only `Debug` ([#48](https://github.com/contextgeneric/cgp/pull/48)). + +- **Old:** `type Error: Async + Debug`, so with the default features every context's error was `Send + Sync + 'static`. +- **New:** `type Error: Debug`. The new trait `HasAsyncErrorType` is `Async + HasErrorType`. +- **What to do:** where code relies on the error being `Send + Sync + 'static`, add `HasAsyncErrorType` to its bounds. + +### The eyre and std error providers are renamed + +The providers of `cgp-error-eyre` and `cgp-error-std` have new names, and `cgp-error-std` splits one provider in two ([#48](https://github.com/contextgeneric/cgp/pull/48)). + +| Crate | Old | New | +|---|---|---| +| `cgp-error-eyre` | `ProvideEyreError` | `UseEyreError` | +| `cgp-error-eyre` | `RaiseStdError` | `RaiseEyreError` | +| `cgp-error-eyre` | `RaiseDebugError` | `DebugEyreError` | +| `cgp-error-eyre` | `RaiseDisplayError` | `DisplayEyreError` | +| `cgp-error-std` | `HandleErrorsWithStdError` | `UseBoxedStdError` for the error type, `RaiseBoxedStdError` for raising | + +- **What to do:** rename each use in the wiring. A context that wired `HandleErrorsWithStdError` for both the error type and the raiser wires the two new providers. + +### `cgp-error-eyre` builds eyre without its default features + +`cgp-error-eyre` depends on `eyre` 0.6.12 with `default-features = false`, which leaves out eyre's `auto-install` and `track-caller` features ([#48](https://github.com/contextgeneric/cgp/pull/48)). + +- **Old:** eyre's default features were on, so a report could be built at any time. +- **New:** when nothing else in the build turns `auto-install` on, building a report panics with "a handler must always be installed if the `auto-install` feature is disabled" until the application installs a hook. +- **What to do:** call `eyre::set_hook` at startup, or depend on `eyre` with its default features in the application. + +## New features + +### Getters + +- **`#[cgp_getter]` defines a getter component.** It extends `#[cgp_component]` and implements the provider trait for `UseFields`, which reads each field named like a getter method. A trait with a single getter also gets the `UseField` and `WithProvider` impls, so a context can choose the field by wiring ([#56](https://github.com/contextgeneric/cgp/pull/56)). See [`#[cgp_getter]`](/docs/reference/macros/cgp_getter) and [`UseFields`](/docs/reference/providers/use_fields). +- **`#[cgp_auto_getter]` implements a getter trait for every context that has the fields.** The blanket impl reads each field through `HasField`, so the trait needs no wiring, and the attribute takes no argument ([#56](https://github.com/contextgeneric/cgp/pull/56)). See [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter). + +### Abstract types + +- **`cgp_type!` declares an abstract type in one line.** `cgp_type! { Error: Debug }` generates the consumer trait `HasErrorType`, the provider trait `ProvideErrorType`, the component `ErrorTypeComponent`, the alias `ErrorOf`, the blanket impls that connect them, and impls for `UseType` and `WithProvider` ([#55](https://github.com/contextgeneric/cgp/pull/55)). `HasErrorType` and `HasRuntimeType` are declared this way. +- **`TypeOf` is an alias for the `Type` of a context's `HasType`.** + +### Errors + +- **`CanWrapError` adds detail to an error.** `Context::wrap_error(error, detail)` returns the context's error. The component is `ErrorWrapperComponent`, with the provider trait `ErrorWrapper`, and `UseDelegate` dispatches it per detail type ([#48](https://github.com/contextgeneric/cgp/pull/48)). +- **`cgp-error-extra` holds generic `ErrorRaiser` and `ErrorWrapper` providers** ([#48](https://github.com/contextgeneric/cgp/pull/48), [#53](https://github.com/contextgeneric/cgp/pull/53)): + - `RaiseFrom` raises a source error through the context error's `From` impl. + - `ReturnError` returns a source error that is already the context's error. + - `RaiseInfallible` raises an `Infallible`, which cannot occur. + - `PanicOnError` panics with the source error's `Debug` text. + - `DiscardDetail` wraps an error by dropping the detail. + - `DebugError` and `DisplayError`, which need the `alloc` feature, format the source error into a `String` and raise or wrap that. +- **More providers implement `ErrorWrapper`.** `DebugError`, `DisplayError`, `RaiseEyreError`, `RaiseAnyhowError`, and the debug and display providers of the three backends wrap an error as well as raise one ([#54](https://github.com/contextgeneric/cgp/pull/54)). +- **`cgp-error-anyhow` is a backend for `anyhow`.** `UseAnyhowError` sets `anyhow::Error` as the error type, and `RaiseAnyhowError`, `DebugAnyhowError`, and `DisplayAnyhowError` raise and wrap into it ([#48](https://github.com/contextgeneric/cgp/pull/48)). +- **`cgp-error-std` adds providers and error types for boxed standard errors.** `DebugBoxedStdError` and `DisplayBoxedStdError` raise a source error as a `StringError` holding its `Debug` or `Display` text, and wrap an error in a `WrapError` that holds the detail and the source and prints them as `detail: source` ([#48](https://github.com/contextgeneric/cgp/pull/48)). + +### Runtimes + +- **`cgp-runtime` gives generic code a runtime to program against.** `HasRuntimeType` declares the runtime type, `HasRuntime` adds `runtime(&self) -> &Self::Runtime` through the getter component `RuntimeGetter`, and `HasAsyncRuntimeType` requires the runtime to be `Async` ([#50](https://github.com/contextgeneric/cgp/pull/50)). See [`HasRuntimeType`](/docs/reference/components/has_runtime_type) and [`HasRuntime`](/docs/reference/components/has_runtime). + +### Fields + +- **`Index` implements `Display`** ([#49](https://github.com/contextgeneric/cgp/pull/49)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-3-1.md b/docs/release-notes/cgp/v0-3-1.md new file mode 100644 index 00000000..7fe92f29 --- /dev/null +++ b/docs/release-notes/cgp/v0-3-1.md @@ -0,0 +1,42 @@ +--- +title: 'cgp v0.3.1 release notes' +sidebar_label: 'v0.3.1' +sidebar_position: 99699 +description: 'cgp v0.3.1 adds CanRaiseAsyncError and CanWrapAsyncError, exports HasAsyncErrorType from the prelude, and raises the minimum Rust version to 1.84.' +slug: v0.3.1 +--- + +# cgp v0.3.1 + +Version 0.3.1 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, adds two error traits that require an `Async` context and raises the minimum Rust version. This page lists every change a user can see and the steps that take a project there from v0.3.0. + +Released on 2025-01-16. + +- **Crate:** [`cgp` 0.3.1 on crates.io](https://crates.io/crates/cgp/0.3.1) +- **Changes:** [v0.3.0...v0.3.1](https://github.com/contextgeneric/cgp/compare/v0.3.0...v0.3.1) + +## Summary + +`CanRaiseAsyncError` and `CanWrapAsyncError` combine `CanRaiseError` and `CanWrapError` with `HasAsyncErrorType`, and the prelude exports both new traits and `HasAsyncErrorType`. The minimum Rust version rises to 1.84. The release removes and renames nothing. + +## Compatibility + +- **Minimum Rust version:** 1.84, up from 1.83 ([#58](https://github.com/contextgeneric/cgp/pull/58)). +- **Released together:** only `cgp`, `cgp-core`, and `cgp-error` have a 0.3.1 version. The workspace's other 18 crates stay at 0.3.0, and the three new versions depend on them. + +## Upgrading + +A project on Rust 1.84 or newer takes one step: change the version to `cgp = "0.3.1"`. Nothing else changes, because the release adds names without removing or renaming any. + +## New features + +- **`CanRaiseAsyncError` and `CanWrapAsyncError` require an `Async` context.** Each is the matching [`CanRaiseError`](/docs/reference/components/can_raise_error) or [`CanWrapError`](/docs/reference/components/can_wrap_error) bound together with `HasAsyncErrorType`, and each is implemented for every context that meets both bounds, so a bound on either needs no wiring. `cgp-error` and the prelude export both ([#60](https://github.com/contextgeneric/cgp/pull/60)). + +## Improvements + +- **The prelude exports `HasAsyncErrorType`**, so `use cgp::prelude::*;` brings it in. It was already exported from `cgp-error`, but not from the prelude ([#59](https://github.com/contextgeneric/cgp/pull/59)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-4-0.md b/docs/release-notes/cgp/v0-4-0.md new file mode 100644 index 00000000..d7321d6a --- /dev/null +++ b/docs/release-notes/cgp/v0-4-0.md @@ -0,0 +1,176 @@ +--- +title: 'cgp v0.4.0 release notes' +sidebar_label: 'v0.4.0' +sidebar_position: 99600 +description: 'cgp v0.4.0 adds IsProviderFor and check_components! for readable errors, presets, #[cgp_context], and HasFields, and requires #[cgp_provider].' +slug: v0.4.0 +--- + +# cgp v0.4.0 + +Version 0.4.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, makes an unmet dependency show up in compiler errors, and adds presets, contexts, and datatype-generic traits. This page lists every change a user can see and the steps that take a project there from v0.3.1. + +Released on 2025-05-09. + +- **Release post:** [CGP v0.4.0 Release: Unlocking Easier Debugging, Extensible Presets, and More](/blog/v0-4-0-release) +- **Crate:** [`cgp` 0.4.0 on crates.io](https://crates.io/crates/cgp/0.4.0) +- **Changes:** [v0.3.1...v0.4.0](https://github.com/contextgeneric/cgp/compare/v0.3.1...v0.4.0) + +## Summary + +`IsProviderFor`, `CanUseComponent`, `check_components!`, and `delegate_and_check_components!` put a missing dependency into the compiler's error, at the price of an attribute on every provider impl. `cgp_preset!` groups wirings and inherits other presets, `#[cgp_context]` declares a context's provider, and `#[derive(HasFields)]` exposes a type's fields as a type-level list. The getter macros read more kinds of field, and a getter trait may be generic. The release also renames `HasComponents`, replaces the macro crates with `cgp-macro`, and lowers the minimum Rust version to 1.81. + +## Compatibility + +- **Minimum Rust version:** 1.81, down from 1.84 ([#62](https://github.com/contextgeneric/cgp/pull/62)). +- **Released together:** the workspace's 19 crates published on crates.io, all at 0.4.0. +- **New crates:** `cgp-macro` and `cgp-macro-lib`, which replace `cgp-component-macro`, `cgp-component-macro-lib`, `cgp-field-macro`, and `cgp-field-macro-lib`; those four have no 0.4.0 version. See [the macro crates](#the-macro-crates-are-replaced-by-cgp-macro). +- **Features:** the `static` feature of `cgp-async` stays declared but gates nothing, because `MaybeStatic` is removed; see [the `Async` bound](#async-no-longer-requires-static). + +## Upgrading + +A project moving from v0.3.1 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.4.0"`. Rust 1.81 or newer builds it. +2. **Annotate each provider impl** with `#[cgp_provider]` or `#[cgp_new_provider]`, per [the provider attribute](#provider-impls-need-cgp_provider). +3. **Rename `HasComponents`** to `HasCgpProvider` and its `Components` type to `CgpProvider`, per [the rename](#hascomponents-is-renamed-hascgpprovider). +4. **Replace each `cgp_type!`** with a `#[cgp_type]` trait and rename the generated provider traits and component keys, per [the attribute](#cgp_type-becomes-the-cgp_type-attribute). +5. **Add `'static`** where code relied on `Async` implying it, per [the `Async` bound](#async-no-longer-requires-static). +6. **Write symbols with `symbol!`**, per [the symbol type](#symbol-builds-a-chain-of-char-types). +7. **Rename the items of each preset**, per [the preset module](#cgp_preset-expands-to-a-module). +8. **Delete a hand-written `UseContext` impl** of a component, per [the generated impl](#cgp_component-implements-the-provider-trait-for-usecontext). +9. **Remove each `for_each_replace!`**, per [the removal](#for_each_replace-is-removed). +10. **Import macros from `cgp::prelude` or `cgp-macro`**, per [the macro crates](#the-macro-crates-are-replaced-by-cgp-macro). +11. **Make the error `Async`** in a context that implements `CanRun`, per [the `CanRun` bound](#canrun-requires-an-async-error-type). + +## Breaking changes + +### Provider impls need `#[cgp_provider]` + +Every provider trait has the supertrait `IsProviderFor` ([#63](https://github.com/contextgeneric/cgp/pull/63), [#73](https://github.com/contextgeneric/cgp/pull/73)), which an impl of the provider trait must satisfy. [`#[cgp_provider]`](/docs/reference/macros/cgp_provider) writes that impl under the provider's own bounds. + +- **Old:** `impl Greeter for GreetHello { … }`, with no attribute. +- **New:** `#[cgp_provider]` above the impl, which names the component as the provider trait's name followed by `Component`, or `#[cgp_provider(GreeterComponent)]` to name it. `#[cgp_new_provider]` also declares the provider struct from the impl's self type ([#67](https://github.com/contextgeneric/cgp/pull/67)). +- **What to do:** add the attribute to each provider impl, including impls of `ProvideType`, `ErrorRaiser`, and the other provider traits. Without it, the build fails with the unsatisfied bound `GreetHello: IsProviderFor`. + +### `HasComponents` is renamed `HasCgpProvider` + +The consumer trait's blanket impl reads the context's provider from `HasCgpProvider`, whose associated type is `CgpProvider` ([#69](https://github.com/contextgeneric/cgp/pull/69), [#97](https://github.com/contextgeneric/cgp/pull/97)). + +- **Old:** `impl HasComponents for App { type Components = AppComponents; }`. +- **New:** `impl HasCgpProvider for App { type CgpProvider = AppComponents; }`, which `#[cgp_context]` writes. +- **What to do:** rename the trait and its associated type, or replace the impl with `#[cgp_context]`. The prelude exports `HasCgpProvider`. + +### `cgp_type!` becomes the `#[cgp_type]` attribute + +[`#[cgp_type]`](/docs/reference/macros/cgp_type) goes on a trait that declares one associated type ([#68](https://github.com/contextgeneric/cgp/pull/68)). The provider trait is named after the associated type, as `{Type}TypeProvider`, and the component after the provider trait. + +- **Old:** `cgp_type! { Error: Debug }` generated `HasErrorType`, `ProvideErrorType`, `ErrorTypeComponent`, and the alias `ErrorOf`. +- **New:** `#[cgp_type] pub trait HasErrorType { type Error: Debug; }` generates the same trait and alias, the provider trait `ErrorTypeProvider`, and the component `ErrorTypeProviderComponent`. +- **What to do:** replace each `cgp_type!` call with the trait and the attribute, and rename each use of a generated name. + +| Crate | Old | New | +|---|---|---| +| `cgp-error` | `ProvideErrorType` | `ErrorTypeProvider` | +| `cgp-error` | `ErrorTypeComponent` | `ErrorTypeProviderComponent` | +| `cgp-runtime` | `ProvideRuntimeType` | `RuntimeTypeProvider` | +| `cgp-runtime` | `RuntimeTypeComponent` | `RuntimeTypeProviderComponent` | + +### `Async` no longer requires `'static` + +`Async` is `MaybeSend + MaybeSync`, and the trait `MaybeStatic` is removed ([#89](https://github.com/contextgeneric/cgp/pull/89)). An abstract type bounded by `Async` can now be a type that borrows. + +- **Old:** with the default features, `Async` meant `Send + Sync + 'static`, and the prelude exported `MaybeStatic`. +- **New:** `Async` means `Send + Sync`, and `MaybeStatic` does not exist. +- **What to do:** add `'static` to each bound that needs it, such as a context passed to `tokio::spawn`, and delete imports of `MaybeStatic`. + +### `symbol!` builds a chain of `Char` types + +`Char` carries the rest of the string as its second parameter, so `symbol!("name")` expands to one nested type ([#85](https://github.com/contextgeneric/cgp/pull/85)). + +- **Old:** `Cons, Cons, Cons, Cons, Nil>>>>`. +- **New:** `Char<'n', Char<'a', Char<'m', Char<'e', Nil>>>>`. +- **What to do:** write a field's key with `symbol!`. Code that spelled out the old expansion, or named `Char` with one parameter, changes it. The `HasField` impls that `#[derive(HasField)]` generates use the new key. + +### `cgp_preset!` expands to a module + +`cgp_preset!` declares a module named after the preset, in place of a struct ([#72](https://github.com/contextgeneric/cgp/pull/72), [#91](https://github.com/contextgeneric/cgp/pull/91)). The module holds the provider struct `Provider` and a hidden trait `IsPreset`, and the trait `DelegatesToMyPreset` is no longer generated. + +- **Old:** `cgp_preset! { MyPreset { … } }` declared the struct `MyPreset` and the trait `IsMyPreset`, and a table wired `[…]: MyPreset`. +- **New:** `MyPreset::Provider` replaces the struct and `MyPreset::IsPreset` replaces the trait, so a table wires `[…]: MyPreset::Provider`. +- **What to do:** rename each use of the preset's struct and trait. + +### `#[cgp_component]` implements the provider trait for `UseContext` + +The macro writes the impl of the provider trait for `UseContext`, and its `IsProviderFor` impl, for each component ([#88](https://github.com/contextgeneric/cgp/pull/88)). See [`UseContext`](/docs/reference/providers/use_context). + +- **Old:** a component that needed the impl had it written by hand. +- **New:** the macro writes it, so a hand-written `impl Greeter for UseContext` conflicts with it and fails with `E0119`. +- **What to do:** delete the hand-written impl. + +### `for_each_replace!` is removed + +`for_each_replace!`, which repeated a body for each type in a list, is no longer exported ([#77](https://github.com/contextgeneric/cgp/pull/77)). `replace_with!` remains, and nothing replaces `for_each_replace!`. + +- **What to do:** write the repeated items out. + +### The macro crates are replaced by `cgp-macro` + +`cgp-macro` holds every macro and derive, and `cgp-macro-lib` their implementation ([#83](https://github.com/contextgeneric/cgp/pull/83)). `cgp::core::macros` re-exports `cgp-macro`, and `cgp::re_export_imports` exports the attribute of that name. + +- **Old:** `use cgp_component_macro::cgp_component;` and `use cgp_field_macro::symbol;`. +- **New:** the macros come from `cgp::prelude`, or from `cgp_macro` for a crate that depends on it directly. +- **What to do:** write `use cgp::prelude::*;`. A crate that depends on the old macro crates changes its manifest to `cgp-macro`. + +### `CanRun` requires an `Async` error type + +[`CanRun`](/docs/reference/components/runner) requires `HasAsyncErrorType` ([#90](https://github.com/contextgeneric/cgp/pull/90)), which also requires the context's `Error` to be `Async`. + +- **Old:** `CanRun: Async + HasErrorType`, which left the error type unconstrained. +- **New:** `CanRun: HasAsyncErrorType`. +- **What to do:** make the error type `Send + Sync` for a context that implements or wires `CanRun`. + +## New features + +### Checking wiring + +- **`IsProviderFor` and `CanUseComponent` name the missing dependency.** `IsProviderFor` is an empty trait that each provider trait carries as a supertrait and `#[cgp_provider]` implements under the provider's own `where` bounds. A dependency the provider needs but the context lacks then appears in the error. `CanUseComponent` holds for a context whose `HasCgpProvider` provider implements `IsProviderFor` for the component ([#63](https://github.com/contextgeneric/cgp/pull/63), [#65](https://github.com/contextgeneric/cgp/pull/65), [#73](https://github.com/contextgeneric/cgp/pull/73)). See [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for) and [`CanUseComponent`](/docs/reference/traits/wiring/can_use_component). +- **`check_components!` asserts that a context can use components.** `check_components! { CanUseApp for App { GreeterComponent, FooGetterComponent: [Index<0>, Index<1>] } }` implements the trait `CanUseApp` for `App` once per entry, and each impl requires `CanUseComponent`. A component with type parameters lists them after a colon, in brackets for several, and the macro accepts impl generics and a `where` clause ([#78](https://github.com/contextgeneric/cgp/pull/78)). See [`check_components!`](/docs/reference/macros/check_components). +- **`delegate_and_check_components!` wires and checks in one step.** `delegate_and_check_components! { CanUseApp for App; AppComponents { … } }` wires the entries and checks each of them ([#98](https://github.com/contextgeneric/cgp/pull/98)). See [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components). + +### Components, providers, and contexts + +- **`#[cgp_component(Greeter)]` takes only the provider name.** The component is named by adding `Component` to it, and the context type parameter is `Context` ([#96](https://github.com/contextgeneric/cgp/pull/96)). See [`#[cgp_component]`](/docs/reference/macros/cgp_component). +- **A component trait may declare associated constants.** A provider impl defines each one with `const CONSTANT: u64 = CONSTANT;` ([#95](https://github.com/contextgeneric/cgp/pull/95)). +- **`#[cgp_context]` declares a context.** `#[cgp_context] pub struct App;` declares the provider struct `AppComponents` and implements `HasCgpProvider` for `App`. `#[cgp_context(AppProvider)]` names the provider struct, and `#[cgp_context(AppProvider)]` serves a generic context ([#66](https://github.com/contextgeneric/cgp/pull/66), [#96](https://github.com/contextgeneric/cgp/pull/96)). +- **`delegate_components!` declares a new struct.** `delegate_components! { new MyComponents { … } }` declares `MyComponents` and wires it, `new MyComponents { … }` takes generic parameters, and `UseDelegate` declares a nested table in the same way ([#93](https://github.com/contextgeneric/cgp/pull/93)). See [`delegate_components!`](/docs/reference/macros/delegate_components). +- **`#[blanket_trait]` defines a trait alias.** A trait with supertraits, default methods, and associated types gets a blanket impl for every type that meets its supertraits ([#79](https://github.com/contextgeneric/cgp/pull/79), [#82](https://github.com/contextgeneric/cgp/pull/82)). See [`#[blanket_trait]`](/docs/reference/macros/blanket_trait). + +### Presets + +- **A preset inherits other presets.** `cgp_preset! { Child: ParentA + ParentB { … } }` copies the parents' entries into the child, an entry marked `override` replaces a parent's entry for the same component, and presets may take generic parameters ([#91](https://github.com/contextgeneric/cgp/pull/91), [#92](https://github.com/contextgeneric/cgp/pull/92)). +- **A context inherits a preset.** `#[cgp_context(AppComponents: MyPreset)]` wires every component of the preset to `MyPreset::Provider`, and the context's own entries add to it ([#66](https://github.com/contextgeneric/cgp/pull/66), [#91](https://github.com/contextgeneric/cgp/pull/91)). +- **`#[cgp::re_export_imports]` re-exports a module's imports.** On a module, it re-exports the `use` items through a hidden `re_exports` module and the other items from the parent. A preset that inherits another can then import the parent's components ([#70](https://github.com/contextgeneric/cgp/pull/70), [#71](https://github.com/contextgeneric/cgp/pull/71), [#72](https://github.com/contextgeneric/cgp/pull/72)). + +### Getters and fields + +- **A getter trait may take generic parameters.** `#[cgp_auto_getter]` and `#[cgp_getter]` traits may be generic, and a getter method may take a second `PhantomData` argument that selects a field by a type parameter ([#64](https://github.com/contextgeneric/cgp/pull/64), [#76](https://github.com/contextgeneric/cgp/pull/76), [#80](https://github.com/contextgeneric/cgp/pull/80), [#81](https://github.com/contextgeneric/cgp/pull/81)). See [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) and [`#[cgp_getter]`](/docs/reference/macros/cgp_getter). +- **A getter returns more than `&T`.** A method may return `&str`, read from a `String` field; `&[T]`, read from a `Vec` field; `Option<&T>`, read from an `Option` field; `MRef<'a, T>`; or an owned value, which the impl clones from the field ([#81](https://github.com/contextgeneric/cgp/pull/81), [#87](https://github.com/contextgeneric/cgp/pull/87)). [`MRef`](/docs/reference/types/mref) is an enum of a borrowed `&'a T` or an owned `T` that dereferences to `T`. +- **`#[cgp_getter]` names its provider by convention.** A trait named `HasName` gets the provider `NameGetter` and the component `NameGetterComponent` when the attribute names neither ([#94](https://github.com/contextgeneric/cgp/pull/94)). +- **`ChainGetters` and `UseFieldRef` read nested and referenced fields.** `ChainGetters, UseField]>` reads a field through a chain of getters, and `UseFieldRef` reads a field through `AsRef`. `FieldMapper` and `MapField` carry the lifetimes the chain needs ([#81](https://github.com/contextgeneric/cgp/pull/81), [#94](https://github.com/contextgeneric/cgp/pull/94)). See [`ChainGetters`](/docs/reference/providers/chain_getters), [`UseFieldRef`](/docs/reference/providers/use_field_ref), [`FieldMapper`](/docs/reference/traits/field-access/field_mapper), and [`MapField`](/docs/reference/traits/field-access/map_field). + +### Data shapes + +- **`#[derive(HasFields)]` lists a type's fields.** `HasFields::Fields` is a `Cons` list of `Field` entries for a struct's fields, and an `Either` list for an enum's variants. `HasFieldsRef` gives the borrowed form, and `ToFields`, `FromFields`, and `ToFieldsRef` convert a value to and from it ([#84](https://github.com/contextgeneric/cgp/pull/84)). See [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields), [`HasFields`](/docs/reference/traits/shape/has_fields), [`ToFields`](/docs/reference/traits/shape/to_fields), and [`FromFields`](/docs/reference/traits/shape/from_fields). + +## Improvements + +- **The type-level types are declared under Greek letters.** `π` is `Cons`, `ε` is `Nil`, `σ` is `Either`, `θ` is `Void`, `ω` is `Field`, `ι` is `Char`, and `δ` is `Index`, with the English names as aliases, so existing code compiles unchanged and compiler output prints the shorter names ([#85](https://github.com/contextgeneric/cgp/pull/85)). +- **Type-level types implement more traits.** A `Char` list implements `Display` and prints its text, and `Cons`, `Nil`, `Either`, `Void`, `Field`, and `Index` implement `Debug`, `PartialEq`, and `Eq` where their parameters do ([#85](https://github.com/contextgeneric/cgp/pull/85), [#86](https://github.com/contextgeneric/cgp/pull/86)). +- **Core traits explain an unmet bound.** `DelegateComponent`, `IsProviderFor`, `HasField`, and `HasFieldMut` carry `#[diagnostic::on_unimplemented]` messages, and the `Deref` blanket impl of `HasField` carries `#[diagnostic::do_not_recommend]` ([#63](https://github.com/contextgeneric/cgp/pull/63), [#74](https://github.com/contextgeneric/cgp/pull/74)). +- **`HasField` reads through `Deref` without a `'static` target.** A context that dereferences to a struct borrowing other data can use the field traits ([#94](https://github.com/contextgeneric/cgp/pull/94)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-4-1.md b/docs/release-notes/cgp/v0-4-1.md new file mode 100644 index 00000000..288c5324 --- /dev/null +++ b/docs/release-notes/cgp/v0-4-1.md @@ -0,0 +1,67 @@ +--- +title: 'cgp v0.4.1 release notes' +sidebar_label: 'v0.4.1' +sidebar_position: 99599 +description: 'cgp v0.4.1 adds the cgp-handler crate, derive_delegate for components, and wrapped presets, and changes how type-level strings are formatted.' +slug: v0.4.1 +--- + +# cgp v0.4.1 + +Version 0.4.1 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, adds the `cgp-handler` crate and lets a component pick its implementation by the type of one of its parameters. This page lists every change a user can see and the steps that take a project there from v0.4.0. + +Released on 2025-06-13. + +- **Release post:** [CGP v0.4.1 Release: new cgp-handler crate, improved preset macros, and more](/blog/v0-4-1-release) +- **Crate:** [`cgp` 0.4.1 on crates.io](https://crates.io/crates/cgp/0.4.1) +- **Changes:** [v0.4.0...v0.4.1](https://github.com/contextgeneric/cgp/compare/v0.4.0...v0.4.1) + +## Summary + +The new `cgp-handler` crate defines the `CanCompute`, `CanProduce`, and `CanHandle` components, with `PipeHandlers` and the promotion providers that connect them. `#[cgp_component]` derives a `UseDelegate` provider from a `derive_delegate` entry, and `cgp_preset!` can wrap its provider in `UseDelegate`. Type-level strings now format through a new `StaticFormat` trait, which changes what `Char` and `Nil` implement. + +## Compatibility + +- **Minimum Rust version:** 1.81, unchanged from v0.4.0. +- **Released together:** the workspace's 20 crates published on crates.io, all at 0.4.1. +- **New crates:** `cgp-handler`, which `cgp::extra::handler` re-exports. + +## Upgrading + +A project moving from v0.4.0 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.4.1"`. +2. **Build a `Char` with `PhantomData`**, and format a type-level string through its `Char` type, per [the string formatting](#type-level-strings-format-through-staticformat). + +## Breaking changes + +### Type-level strings format through `StaticFormat` + +The new trait `StaticFormat` formats a type without a value, and `Char` implements `Display` through it ([#104](https://github.com/contextgeneric/cgp/pull/104)). See [`StaticFormat`](/docs/reference/traits/formatting/static_format). + +- **Old:** `Nil` implemented `Display`, `Char(pub Tail)` held its tail value, and a `Char` list displayed when its tail did. +- **New:** `Nil` implements `StaticFormat` and no longer `Display`. `Char(pub PhantomData)` holds a `PhantomData`, and implements `Display` and `StaticFormat` when its tail implements `StaticFormat`. +- **What to do:** write `Char(PhantomData)` or `Default::default()` where code built a `Char` from a tail value, and display a whole type-level string rather than a bare `Nil`. + +## New features + +### Handlers + +- **`cgp-handler` defines three components that share one shape.** `CanCompute`, with the provider trait `Computer`, transforms an input into `Self::Output`. `CanProduce`, with `Producer`, produces an `Output` from the context alone. `CanHandle`, with `Handler`, is asynchronous and fallible, returns `Result`, and requires `HasAsyncErrorType`. Each method takes a `PhantomData` that selects the operation ([#105](https://github.com/contextgeneric/cgp/pull/105)). See [`Computer`](/docs/reference/components/handler/computer), [`Producer`](/docs/reference/components/handler/producer), and [`Handler`](/docs/reference/components/handler/handler). +- **`PipeHandlers` runs providers in order.** `PipeHandlers` feeds the output of each provider to the next, for both `Computer` and `Handler` providers, and `PipeHandlers` returns its input ([#105](https://github.com/contextgeneric/cgp/pull/105)). See [`PipeHandlers`](/docs/reference/providers/handler/pipe_handlers). +- **`Promote` and `TryPromote` turn a `Computer` into a `Handler`.** `Promote` wraps the output in `Ok`, and `TryPromote` serves a `Computer` whose output is already a `Result` of the context's error ([#105](https://github.com/contextgeneric/cgp/pull/105), [#107](https://github.com/contextgeneric/cgp/pull/107)). See [`Promote`](/docs/reference/providers/handler/promote) and [`TryPromote`](/docs/reference/providers/handler/try_promote). + +### Dispatching on a parameter + +- **`derive_delegate` derives a `UseDelegate` provider.** `#[cgp_component { provider: ErrorRaiser, derive_delegate: UseDelegate }]` implements the provider trait for `UseDelegate`, which looks the named parameter up in `Components` and forwards to the provider it finds. A list, such as `derive_delegate: [UseDelegate, UseInputDelegate]`, derives one wrapper per entry ([#106](https://github.com/contextgeneric/cgp/pull/106), [#107](https://github.com/contextgeneric/cgp/pull/107)). See [`UseDelegate`](/docs/reference/providers/use_delegate) and [`UseInputDelegate`](/docs/reference/providers/handler/use_input_delegate). +- **`#[wrap_provider(UseDelegate)]` wraps a preset's provider.** `cgp_preset! { #[wrap_provider(UseDelegate)] MyPreset { … } }` makes `MyPreset::Provider` the type `UseDelegate`, so a table keyed by ordinary types can be a delegation target. Without the attribute, `MyPreset::Provider` names the struct `MyPreset::Components` ([#103](https://github.com/contextgeneric/cgp/pull/103)). + +## Improvements + +- **The prelude exports `UseDelegate`.** `use cgp::prelude::*;` brings it in ([#103](https://github.com/contextgeneric/cgp/pull/103)). +- **Common constructs carry documentation.** The docs.rs pages for `Async`, `#[async_trait]`, `DelegateComponent`, `IsProviderFor`, `CanUseComponent`, `HasCgpProvider`, `Char`, and the macros of `cgp-macro` explain what each does and give an example ([#109](https://github.com/contextgeneric/cgp/pull/109)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-4-2.md b/docs/release-notes/cgp/v0-4-2.md new file mode 100644 index 00000000..322c57ae --- /dev/null +++ b/docs/release-notes/cgp/v0-4-2.md @@ -0,0 +1,109 @@ +--- +title: 'cgp v0.4.2 release notes' +sidebar_label: 'v0.4.2' +sidebar_position: 99598 +description: 'cgp v0.4.2 adds extensible records and variants, builders, extractors and casts, the cgp-dispatch crate, ref handlers, and direct delegation.' +slug: v0.4.2 +--- + +# cgp v0.4.2 + +Version 0.4.2 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, adds extensible records and variants, which build and take apart structs and enums one field at a time. This page lists every change a user can see and the steps that take a project there from v0.4.1. + +Released on 2025-07-07. + +- **Release post:** [Programming Extensible Data Types in Rust with CGP - Part 1: Modular App Construction and Extensible Builders](/blog/extensible-datatypes-part-1), the first of four parts +- **Crate:** [`cgp` 0.4.2 on crates.io](https://crates.io/crates/cgp/0.4.2) +- **Changes:** [v0.4.1...v0.4.2](https://github.com/contextgeneric/cgp/compare/v0.4.1...v0.4.2) + +## Summary + +Builder and extractor traits with three derives let a record be assembled field by field and an enum be taken apart variant by variant, and the new `cgp-dispatch` crate turns them into handler providers. Casts convert between enums that share variants. The handler family gains `TryComputer`, reference variants, and new providers, and `delegate_components!` gains a direct delegation mode. `Promote` now promotes one level at a time, which changes how a `Computer` becomes a `Handler`. + +## Compatibility + +- **Minimum Rust version:** 1.81, unchanged from v0.4.1. +- **Released together:** the workspace's 21 crates published on crates.io, all at 0.4.2. +- **New crates:** `cgp-dispatch`, which `cgp::extra::dispatch` re-exports. + +## Upgrading + +A project moving from v0.4.1 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.4.2"`. +2. **Write `Promote2

`** where `Promote

` turned a `Computer` into a `Handler`, per [the promotion levels](#promote-promotes-one-level-at-a-time). +3. **Add `Send` bounds** where generic code relied on `CanHandle` requiring them, per [the handler bounds](#canhandle-no-longer-requires-send). + +## Breaking changes + +### `Promote` promotes one level at a time + +`Promote` lifts a provider one step along `Producer`, `Computer`, `TryComputer`, and `Handler` ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`Promote`](/docs/reference/providers/handler/promote). + +- **Old:** `Promote

` implemented `Handler` for a `Computer` provider `P`. +- **New:** `Promote

` implements `TryComputer` for a `Computer`, `Handler` for a `TryComputer`, and `Computer` for a `Producer`. The aliases `Promote2

` and `Promote3

` stack two and three levels. +- **What to do:** write `Promote2

` where a `Computer` was promoted to a `Handler`. `TryPromote

` now raises its error through `CanRaiseError`, so it no longer needs the context's error type to equal the computer's. + +### `CanHandle` no longer requires `Send` + +`CanHandle` and its provider trait `Handler` drop the `Send` bounds on `Code` and `Input`, and `Output` no longer has to be `Send` ([#117](https://github.com/contextgeneric/cgp/pull/117)). + +- **Old:** `CanHandle` with `type Output: Send`, so generic code could rely on all three being `Send`. +- **New:** none of them is bounded. +- **What to do:** add `Send` to the bounds of generic code that needs it, such as code that spawns the result. + +## New features + +### Extensible records + +- **Builder traits assemble a record field by field.** `HasBuilder::builder()` returns a record's empty builder, `BuildField` sets one field and returns a builder whose type records the change, and `FinalizeBuild` turns a complete builder into the record. `IntoBuilder` and `TakeField` run the process backwards, moving fields out of a record ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`HasBuilder`](/docs/reference/traits/builder/has_builder), [`BuildField`](/docs/reference/traits/builder/build_field), [`FinalizeBuild`](/docs/reference/traits/builder/finalize_build), [`IntoBuilder`](/docs/reference/traits/builder/into_builder), and [`TakeField`](/docs/reference/traits/builder/take_field). +- **`#[derive(BuildField)]` implements the builder traits for a struct.** It generates a partial struct with one type parameter per field, with `HasField` impls for the fields that are set ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`#[derive(BuildField)]`](/docs/reference/derives/derive_build_field). +- **`CanBuildFrom` merges one record into another.** It sets every field of a builder that the source supplies ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`CanBuildFrom`](/docs/reference/traits/casting/can_build_from). + +### Extensible variants + +- **Extractor traits take an enum apart variant by variant.** `HasExtractor` converts an enum to its extractor and back, `HasExtractorRef` borrows one, `ExtractField` removes one variant and returns `Result`, and `FromVariant` builds an enum from one variant's value. `FinalizeExtract` and `FinalizeExtractResult` discharge a remainder with no variants left, so a match over every variant needs no wildcard ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`HasExtractor`](/docs/reference/traits/variant/has_extractor), [`ExtractField`](/docs/reference/traits/variant/extract_field), [`FromVariant`](/docs/reference/traits/variant/from_variant), and [`FinalizeExtract`](/docs/reference/traits/variant/finalize_extract). +- **`#[derive(ExtractField)]` and `#[derive(FromVariant)]` implement them for an enum** ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_field) and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant). +- **`IsPresent`, `IsNothing`, and `IsVoid` implement `MapType`,** which maps a type to itself, to `()`, or to `Void`, and `MapFields` applies such a mapping to a field list ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`MapType`](/docs/reference/traits/type-level/map_type) and [`MapFields`](/docs/reference/traits/type-level/map_fields). + +### Casting + +- **`CanUpcast` widens an enum and `CanDowncast` narrows it.** `upcast` converts into an enum with a superset of the variants, and `downcast` returns `Result`; `CanDowncastFields` does the same by field list ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`CanUpcast`](/docs/reference/traits/casting/can_upcast) and [`CanDowncast`](/docs/reference/traits/casting/can_downcast). + +### Dispatch providers + +`cgp-dispatch` holds the handler providers that build records and match variants ([#112](https://github.com/contextgeneric/cgp/pull/112), [#116](https://github.com/contextgeneric/cgp/pull/116), [#117](https://github.com/contextgeneric/cgp/pull/117), [#119](https://github.com/contextgeneric/cgp/pull/119), [#120](https://github.com/contextgeneric/cgp/pull/120)). Each provider serves `Computer`, `TryComputer`, and `Handler`. + +- **`BuildWithHandlers`** starts from `Output`'s empty builder, pipes it through the handlers, and finalizes it. See [`BuildWithHandlers`](/docs/reference/providers/dispatch/build_with_handlers). +- **`BuildAndSetField` and `BuildAndMerge`** run a provider on a reference to the builder, then set one field or merge the result into the builder. See [`BuildAndSetField`](/docs/reference/providers/dispatch/build_and_set_field) and [`BuildAndMerge`](/docs/reference/providers/dispatch/build_and_merge). +- **`BuildAndMergeOutputs`** builds an output by merging what each handler returns. See [`BuildAndMergeOutputs`](/docs/reference/providers/dispatch/build_and_merge_outputs). +- **`MatchWithHandlers`** converts its input to an extractor and tries each handler on one variant. It then finalizes the remainder. `MatchWithHandlersRef` does the same on a reference, and `DispatchMatchers` runs the matchers in order. See [`MatchWithHandlers`](/docs/reference/providers/dispatch/match_with_handlers). +- **`ExtractFieldAndHandle` and `DowncastAndHandle`** extract one variant, or downcast to a smaller enum, and run a provider on it. See [`ExtractFieldAndHandle`](/docs/reference/providers/dispatch/extract_field_and_handle) and [`DowncastAndHandle`](/docs/reference/providers/dispatch/downcast_and_handle). +- **`MatchWithFieldHandlers`** chooses a handler per variant from the input type, and `MatchWithValueHandlers`, `MatchWithFieldHandlersRef`, and `MatchWithValueHandlersRef` are its aliases for unwrapped values and references. See [`MatchWithFieldHandlers`](/docs/reference/providers/dispatch/match_with_field_handlers) and [`MatchWithValueHandlers`](/docs/reference/providers/dispatch/match_with_value_handlers). + +### Handlers + +- **`TryComputer` is a fallible, synchronous computation.** `CanTryCompute` returns `Result` and requires `HasErrorType` ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`TryComputer`](/docs/reference/components/handler/try_computer). +- **Reference variants take `&Input`.** `CanComputeRef`, `CanTryComputeRef`, and `CanHandleRef`, with the provider traits `ComputerRef`, `TryComputerRef`, and `HandlerRef`, compute from a borrowed input, and `PromoteRef` turns a reference provider into one for owned input ([#118](https://github.com/contextgeneric/cgp/pull/118)). See [`ComputerRef`](/docs/reference/components/handler/computer_ref), [`HandlerRef`](/docs/reference/components/handler/handler_ref), and [`PromoteRef`](/docs/reference/providers/handler/promote_ref). +- **`Computer` and the new components derive `UseInputDelegate`,** so a context can choose a provider by input type as well as by `Code`, as `Handler` already could ([#112](https://github.com/contextgeneric/cgp/pull/112), [#118](https://github.com/contextgeneric/cgp/pull/118)). +- **`ReturnInput` and `HandleFieldValue` are new providers.** `ReturnInput` returns its input, and `HandleFieldValue` passes the value inside a `Field` to `Provider` ([#112](https://github.com/contextgeneric/cgp/pull/112)). See [`ReturnInput`](/docs/reference/providers/handler/return_input) and [`HandleFieldValue`](/docs/reference/providers/dispatch/handle_field_value). +- **`PipeHandlers` serves `TryComputer` as well as `Computer` and `Handler`** ([#112](https://github.com/contextgeneric/cgp/pull/112)). +- **Three attributes turn a function into a provider.** `#[cgp_computer]` makes a `Computer` from a plain function, `#[cgp_producer]` makes a `Producer` from a function without parameters, and `#[cgp_handler]` makes a `Handler` from an `async` function. The provider is named by writing the function name in CamelCase unless the attribute names it. A function with one reference parameter also gets the reference providers ([#112](https://github.com/contextgeneric/cgp/pull/112), [#121](https://github.com/contextgeneric/cgp/pull/121)). See [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and [`#[cgp_producer]`](/docs/reference/macros/cgp_producer). + +### Wiring + +- **`->` delegates a key to another table's entry.** `delegate_components! { App { [A, B] -> Other } }` sets each key's delegate to what `Other` wires for the same key, where `:` names a provider ([#111](https://github.com/contextgeneric/cgp/pull/111)). See [the operators](/docs/reference/macros/delegate_components#the-operators). + +## Improvements + +- **`cgp::prelude` includes the extra crate's prelude.** The prelude now exports `PhantomData`, the builder, extractor, and `MapType` traits and markers, the three new derives, `Computer`, `TryComputer`, `Handler`, `Producer` with their component keys, `Promote`, `PromoteRef`, `TryPromote`, and the three function attributes ([#112](https://github.com/contextgeneric/cgp/pull/112)). + +## Fixes + +- **`#[derive(HasField)]` on a tuple struct:** it implements `HasField>`, `HasField>`, and so on for the fields, where v0.4.1 implemented nothing ([#115](https://github.com/contextgeneric/cgp/pull/115)). +- **Unsized parameters:** `IsProviderFor` and the `CanUseComponent` trait accept an unsized parameter such as `str`, where v0.4.1 failed with `E0277` ([#114](https://github.com/contextgeneric/cgp/pull/114)). The blanket `CanUseComponent` impl for a context still requires a sized parameter. + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-5-0.md b/docs/release-notes/cgp/v0-5-0.md new file mode 100644 index 00000000..e984d800 --- /dev/null +++ b/docs/release-notes/cgp/v0-5-0.md @@ -0,0 +1,214 @@ +--- +title: 'cgp v0.5.0 release notes' +sidebar_label: 'v0.5.0' +sidebar_position: 99500 +description: 'cgp v0.5.0 removes the Async trait, adds CgpData, auto dispatch, monadic computation and optional builders, and renames symbol! to Symbol!.' +slug: v0.5.0 +--- + +# cgp v0.5.0 + +Version 0.5.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, removes the `Async` trait and adds monadic computation, automatic dispatch over enums, and one derive for extensible data. This page lists every change a user can see and the steps that take a project there from v0.4.2. + +Released on 2025-10-12. + +- **Release post:** [CGP v0.5.0 Release: Auto dispatchers, extensible datatype improvements, monadic computation, RTN emulation, modular serde, and more](/blog/v0-5-0-release) +- **Crate:** [`cgp` 0.5.0 on crates.io](https://crates.io/crates/cgp/0.5.0) +- **Changes:** [v0.4.2...v0.5.0](https://github.com/contextgeneric/cgp/compare/v0.4.2...v0.5.0) + +## Summary + +The `Async` trait and the async aliases are removed, and a project recovers `Send` where it spawns a future through a proxy trait such as `CanSendRun`. `#[derive(CgpData)]` derives extensible records and variants in one step, `#[cgp_auto_dispatch]` implements a trait for an enum from its variants, and the new `cgp-monad` crate composes handlers that short-circuit. `Symbol!` replaces `symbol!` and can produce a `&'static str`, and `cgp-field` moves its exports into submodules. + +## Compatibility + +- **Minimum Rust version:** 1.89, up from 1.81. +- **Released together:** the workspace's 23 crates published on crates.io, all at 0.5.0. +- **New crates:** `cgp-monad`, for monadic computation; `cgp-field-extra`, for the optional builder and defaults; and `cgp-extra-macro` with `cgp-extra-macro-lib`, which hold `#[cgp_computer]`, `#[cgp_producer]`, and `#[cgp_auto_dispatch]`. +- **Removed crates:** `cgp-async`, `cgp-sync`, and `cgp-inner`; see [the async removal](#async-and-the-async-aliases-are-removed) and [`HasInner`](#hasinner-and-cgp-inner-are-removed). +- **Features:** `cgp` and `cgp-core` lose their `full` feature; see [the features](#the-full-features-are-removed). + +## Upgrading + +A project moving from v0.4.2 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.5.0"` on Rust 1.89 or newer, and delete `features = ["full"]` from a `cgp` or `cgp-core` dependency, per [the features](#the-full-features-are-removed). +2. **Remove the `Async` constructs:** replace `HasAsyncErrorType`, `CanRaiseAsyncError`, `CanWrapAsyncError`, and `HasAsyncRuntimeType` with their plain counterparts, and delete `Async`, `MaybeSend`, and `MaybeSync` bounds, per [the removal](#async-and-the-async-aliases-are-removed). +3. **Recover `Send` where a future is spawned** through a proxy trait, per [the `Send` bound](#async_trait-no-longer-requires-send), and name a `Code` wherever `CanRun` is used, per [`CanRun`](#canrun-takes-a-code-parameter). +4. **Rename the type-level strings:** `symbol!` becomes `Symbol!`, and `Char` becomes `Chars`, per [`Symbol!`](#symbol-becomes-symbol-and-its-expansion-carries-the-length) and [`Chars`](#char-is-renamed-chars). +5. **Update the imports** of `cgp-field` items and of the names that moved, per [the field modules](#cgp-field-exports-move-into-submodules) and [the moved names](#several-names-move-to-other-modules). +6. **Rewrite the handler code:** promotions per [the promotion chain](#the-handler-promotion-chain-gains-an-async-step), `Result` errors per [the error rule](#trypromote-and-function-providers-no-longer-convert-errors), and `#[cgp_handler]` per [its replacement](#cgp_handler-is-folded-into-cgp_computer). +7. **Rewrite the builder code** that names a generated type or a trait that changed, per [the partial types](#generated-partial-types-gain-the-__partial-prefix) and [`FinalizeBuild`](#finalizebuild-takes-its-target-from-partialdata), and replace `HasInner` per [its removal](#hasinner-and-cgp-inner-are-removed). +8. **Build the crate** and fix what the compiler reports. + +## Breaking changes + +### `Async` and the async aliases are removed + +`Async`, `MaybeSend`, and `MaybeSync` are removed, together with the traits built on them, `HasAsyncErrorType`, `CanRaiseAsyncError`, `CanWrapAsyncError`, and `HasAsyncRuntimeType` ([#149](https://github.com/contextgeneric/cgp/pull/149)). The crates `cgp-async` and `cgp-sync` are removed too, and `cgp-async-macro` exports only `#[async_trait]`: its `native_async` and `strip_async` macros are gone. + +- **Old:** `Async` aliased `Send + Sync`, and `HasAsyncErrorType` required it of the context and of its error type. +- **New:** [`HasErrorType`](/docs/reference/components/has_error_type), [`CanRaiseError`](/docs/reference/components/can_raise_error), [`CanWrapError`](/docs/reference/components/can_wrap_error), and [`HasRuntimeType`](/docs/reference/components/has_runtime_type) carry no `Send` or `Sync` bound, and `CanHandle` requires `HasErrorType` where it required `HasAsyncErrorType`. +- **What to do:** replace each removed trait with its plain counterpart, and delete `Async`, `MaybeSend`, and `MaybeSync` from bounds. A project that still wants an old trait can copy its definition into its own crate. + +### `#[async_trait]` no longer requires `Send` + +[`#[async_trait]`](/docs/reference/macros/async_trait) desugars an `async fn` in a trait to a function that returns `impl Future`, without a `Send` bound on the future ([#149](https://github.com/contextgeneric/cgp/pull/149)). Every async trait that `cgp` defines is affected, among them `CanRun`, `CanComputeAsync`, and `CanHandle`. + +- **Old:** the desugared future was `impl Future + MaybeSend`, so generic code could pass the future of a call such as `context.run()` to `tokio::spawn`. +- **New:** the future is `impl Future`, and generic code can no longer show that it is `Send`. +- **What to do:** where generic code must spawn a future, require a proxy trait whose method returns `impl Future + Send`, such as [`CanSendRun`](/docs/reference/components/send_runner). Implement its provider trait `SendRunner` on the concrete context by forwarding to `run`, where the compiler sees the concrete types. The release post works the pattern through in [Emulating RTN](/blog/v0-5-0-release#emulating-rtn). A trait of the project's own that promises a `Send` future needs a copy with the bound, for code that calls the traits `cgp` defines. + +### `CanRun` takes a `Code` parameter + +`CanRun` and its provider trait `Runner` take a `Code` type parameter, and `run` takes a `PhantomData` argument ([#149](https://github.com/contextgeneric/cgp/pull/149)). See [`CanRun`](/docs/reference/components/runner). + +- **Old:** `CanRun: HasAsyncErrorType` with `run(&self)`, and `Runner`. +- **New:** `CanRun: HasErrorType` with `run(&self, _code: PhantomData)`, and `Runner`. A bound written as `CanRun` without a parameter fails with `E0107`. +- **What to do:** name a `Code` type, such as a marker struct, wherever the project uses `CanRun`, and pass `PhantomData` to `run`. A context can choose a provider per code, because the component derives `UseDelegate`. + +### `cgp-field` exports move into submodules + +The root of `cgp-field`, which `cgp::core::field` re-exports, stops re-exporting its items ([#150](https://github.com/contextgeneric/cgp/pull/150)). They are in three public modules instead: `traits`, `impls`, and `types`. + +- **Old:** `cgp::core::field::HasField`, `cgp::core::field::UseField`, and `cgp::core::field::Cons`. +- **New:** `cgp::core::field::traits::HasField`, `cgp::core::field::impls::UseField`, and `cgp::core::field::types::Cons`. +- **What to do:** update each explicit import of a `cgp-field` item. The traits are in `traits`; the providers, the field-state markers, and the casting traits are in `impls`; and `Cons`, `Nil`, `Either`, `Void`, `Field`, `Index`, `Chars`, `Symbol`, and `Life` are in `types`. A glob import of `cgp::prelude` is unaffected for the names the prelude exports. + +### Several names move to other modules + +Four names change their import path, and a project that imports them explicitly updates the import: + +- **`TakeField`** leaves the prelude, and is imported from `cgp::core::field::traits` ([#148](https://github.com/contextgeneric/cgp/pull/148)). +- **`Promote`, `PromoteRef`, and `TryPromote`** leave the prelude, and are imported from `cgp::extra::handler` ([#137](https://github.com/contextgeneric/cgp/pull/137)). +- **`HandleFieldValue`** moves from `cgp::extra::handler` to `cgp::extra::dispatch` ([#139](https://github.com/contextgeneric/cgp/pull/139)). +- **`#[cgp_computer]` and `#[cgp_producer]`** live in the new `cgp-extra-macro` crate, so the path `cgp::core::macros::cgp_computer` no longer resolves ([#138](https://github.com/contextgeneric/cgp/pull/138)). The prelude exports both. + +### `symbol!` becomes `Symbol!` and its expansion carries the length + +`symbol!` is removed, and [`Symbol!`](/docs/reference/macros/symbol) takes its place with a different expansion ([#151](https://github.com/contextgeneric/cgp/pull/151), [#159](https://github.com/contextgeneric/cgp/pull/159), [#173](https://github.com/contextgeneric/cgp/pull/173)). + +- **Old:** `symbol!("abc")` expanded to the nested `Char<'a', Char<'b', Char<'c', Nil>>>`, which the compiler printed as `ι<'a', ι<'b', ι<'c', ε>>>`. +- **New:** `Symbol!("abc")` expands to `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>`, with the length as the first parameter, and the compiler prints `ψ<3, ζ<'a', ζ<'b', ζ<'c', ε>>>>`. The `HasField` impls that `#[derive(HasField)]` and the getter macros generate use the new type. +- **What to do:** write `Symbol!` for `symbol!`, and give a type-level string that was written out by hand the new shape. + +### `Char` is renamed `Chars` + +[`Chars`](/docs/reference/types/chars) holds one character of a type-level string and the rest of the string, and replaces `Char` ([#165](https://github.com/contextgeneric/cgp/pull/165), [#159](https://github.com/contextgeneric/cgp/pull/159)). Its short name changes from `ι` to `ζ`, which avoids the `confusable_idents` warning that `ι` raised beside a variable named `i`. + +- **Old:** `Char`, written `ι`. +- **New:** `Chars`, written `ζ`. +- **What to do:** rename each use. Neither `Char` nor `ι` exists any more. + +### `HasInner` and `cgp-inner` are removed + +The trait `HasInner`, its component, and the `cgp-inner` crate are removed, along with the `cgp::extra::inner` module ([#170](https://github.com/contextgeneric/cgp/pull/170)). [`UseField`](/docs/reference/providers/use_field) composes contexts more flexibly. Nothing replaces `HasInner` by name. + +- **Old:** `HasInner` with `type Inner` and `fn inner(&self) -> &Self::Inner`. +- **New:** a getter or an abstract type read from a field with `UseField`. +- **What to do:** read the inner context through `UseField`, or copy the old trait into the project's own crate. + +### Generated partial types gain the `__Partial` prefix + +The types that `#[derive(BuildField)]` and `#[derive(ExtractField)]` generate gain a `__Partial` prefix, which keeps them out of the user's namespace ([#156](https://github.com/contextgeneric/cgp/pull/156)). + +- **Old:** `PartialPerson` for a struct `Person`, and `PartialShape` and `PartialRefShape` for an enum `Shape`. +- **New:** `__PartialPerson`, `__PartialShape`, and `__PartialRefShape`. +- **What to do:** rename each generated type that the code names. Most code reaches them only through `builder()` and the traits. + +### `FinalizeBuild` takes its target from `PartialData` + +[`FinalizeBuild`](/docs/reference/traits/builder/finalize_build) becomes a subtrait of the new [`PartialData`](/docs/reference/traits/builder/partial_data), and its `Output` associated type is gone ([#152](https://github.com/contextgeneric/cgp/pull/152)). [`BuildField`](/docs/reference/traits/builder/build_field) is now implemented for every type that implements `UpdateField` ([#148](https://github.com/contextgeneric/cgp/pull/148)). + +- **Old:** `trait FinalizeBuild { type Output; fn finalize_build(self) -> Self::Output; }`. +- **New:** `trait FinalizeBuild: PartialData { fn finalize_build(self) -> Self::Target; }`, with `Target` the record the partial type completes. +- **What to do:** write `Target` where a bound named `FinalizeBuild::Output`, and implement `PartialData` for a hand-written partial type. The derives generate both. + +### The handler promotion chain gains an async step + +`Promote` lifts a provider one step: a `Producer` to a `Computer`, a `Computer` to a `TryComputer`, and an `AsyncComputer` to a `Handler`. The new `PromoteAsync` lifts a `Computer` to an `AsyncComputer` and a `TryComputer` to a `Handler` ([#136](https://github.com/contextgeneric/cgp/pull/136), [#137](https://github.com/contextgeneric/cgp/pull/137)). See [`Promote`](/docs/reference/providers/handler/promote) and [`PromoteAsync`](/docs/reference/providers/handler/promote_async). + +- **Old:** `Promote

` turned a `TryComputer` into a `Handler`, `Promote>` turned a `Computer` into one, and the aliases `Promote2` and `Promote3` stacked two and three levels. +- **New:** `PromoteAsync

` turns a `TryComputer` into a `Handler`, and `PromoteAsync>` turns a `Computer` into one. `Promote2` and `Promote3` are removed. +- **What to do:** replace `Promote

` with `PromoteAsync

` where it produced a `Handler` from a `TryComputer`, and `Promote>` with `PromoteAsync>`. + +### `TryPromote` and function providers no longer convert errors + +[`TryPromote`](/docs/reference/providers/handler/try_promote) requires the `Result` that its provider returns to carry `Context::Error` ([#129](https://github.com/contextgeneric/cgp/pull/129), [#136](https://github.com/contextgeneric/cgp/pull/136)). The providers that [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) generates for a function that returns `Result` promote through it, so they follow the same rule. + +- **Old:** `TryPromote` and `#[cgp_handler]` converted any error type `E` into `Context::Error` through `CanRaiseError`. +- **New:** `E` must be `Context::Error`; a provider whose `E` differs fails with a type mismatch. +- **What to do:** return the context's error type from the function, or convert the error inside it before it returns. + +### `#[cgp_handler]` is folded into `#[cgp_computer]` + +`#[cgp_handler]` is removed, and [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) accepts an `async` function and generates the `Handler` that `#[cgp_handler]` generated ([#137](https://github.com/contextgeneric/cgp/pull/137)). + +- **Old:** `#[cgp_handler] async fn double(x: u8) -> u8`. +- **New:** `#[cgp_computer] async fn double(x: u8) -> u8`, which derives an `AsyncComputer` and promotes it to a `Handler`. +- **What to do:** change the attribute name, and apply [the error rule](#trypromote-and-function-providers-no-longer-convert-errors) to a function that returns a `Result`. + +### The `full` features are removed + +`cgp` and `cgp-core` lose their `full` feature, which forwarded to the removed async features and to `cgp-extra` ([#149](https://github.com/contextgeneric/cgp/pull/149)). `cgp-extra` keeps its own default `full` feature, and `cgp` now depends on `cgp-extra` with its default features. + +- **Old:** `cgp = { version = "0.4.2", features = ["full"] }` resolved, and `default-features = false` left out the providers that need an allocator, such as `DebugError`. +- **New:** `features = ["full"]` fails to resolve, because `cgp` has no such feature, and `DebugError` is available even with `default-features = false`. +- **What to do:** delete `"full"` from the feature list. + +## New features + +### Derives and macros + +- **`#[derive(CgpData)]` derives the extensible-data traits for a struct or an enum.** On a struct it derives `HasField`, `HasFields`, and the builder traits, and on an enum it derives `HasFields`, `ExtractField`, and `FromVariant`; `#[derive(CgpRecord)]` and `#[derive(CgpVariant)]` are its struct and enum forms ([#154](https://github.com/contextgeneric/cgp/pull/154)). See [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data), [`#[derive(CgpRecord)]`](/docs/reference/derives/derive_cgp_record), and [`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant). +- **`#[cgp_auto_dispatch]` implements a trait for an enum whose variants all implement it.** `HasArea` for `Circle` and `Rectangle` gives `Shape` an implementation, and neither the trait nor the enum needs to know about the other, so it works across crates. A method may take `self`, `&self`, or `&mut self` and extra arguments, and may be `async` ([#139](https://github.com/contextgeneric/cgp/pull/139), [#142](https://github.com/contextgeneric/cgp/pull/142)). See [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch). + +### Extensible records + +- **`UpdateField` replaces a wrapped field value in a partial record.** `BuildField` is implemented through it, and `#[derive(CgpData)]` derives it ([#148](https://github.com/contextgeneric/cgp/pull/148)). See [`UpdateField`](/docs/reference/traits/builder/update_field). +- **`finalize_with_default` completes a partial record.** `CanFinalizeWithDefault` fills each unset field from `Default`, and `CanBuildWithDefault` builds a record from a source record and defaults the rest ([#128](https://github.com/contextgeneric/cgp/pull/128), [#130](https://github.com/contextgeneric/cgp/pull/130)). See [`CanFinalizeWithDefault`](/docs/reference/traits/optional/can_finalize_with_default) and [`CanBuildWithDefault`](/docs/reference/traits/optional/can_build_with_default). +- **The optional builder keeps one type while fields are set.** The `IsOptional` marker stores each field as an `Option`, `HasOptionalBuilder::optional_builder()` starts one, `SetOptional::set` fills a field, and `FinalizeOptional::finalize_optional` returns the record, or the name of the first missing field as a `&'static str` ([#152](https://github.com/contextgeneric/cgp/pull/152)). The traits are in the new `cgp-field-extra` crate, which `cgp::extra::field` re-exports. See [`HasOptionalBuilder`](/docs/reference/traits/optional/has_optional_builder), [`SetOptional`](/docs/reference/traits/optional/set_optional), and [`FinalizeOptional`](/docs/reference/traits/optional/finalize_optional). + +### Extensible variants and visitors + +- **`HasExtractorMut` extracts from a mutable reference,** and `#[derive(ExtractField)]` implements it for an enum ([#135](https://github.com/contextgeneric/cgp/pull/135)). See [`HasExtractorMut`](/docs/reference/traits/variant/has_extractor_mut). +- **`MapTypeRef` maps a field type to a reference type.** The markers `IsRef`, `IsMut`, and `IsOwned` implement it ([#132](https://github.com/contextgeneric/cgp/pull/132), [#135](https://github.com/contextgeneric/cgp/pull/135)). See [`MapTypeRef`](/docs/reference/traits/type-level/map_type_ref). +- **The matchers cover a mutable reference and an input with extra arguments.** `MatchWithHandlersMut` and `MatchWithValueHandlersMut` match a `&mut` value. `MatchFirstWithHandlers`, `MatchFirstWithValueHandlers`, and their `Ref` and `Mut` forms match the first element of a tuple `(Value, Args)` and pass `Args` on ([#134](https://github.com/contextgeneric/cgp/pull/134), [#135](https://github.com/contextgeneric/cgp/pull/135), [#161](https://github.com/contextgeneric/cgp/pull/161)). `ExtractFirstFieldAndHandle` and `HandleFirstFieldValue` are the providers they use. See [`MatchFirstWithHandlers`](/docs/reference/providers/dispatch/match_first_with_handlers) and [`MatchWithValueHandlers`](/docs/reference/providers/dispatch/match_with_value_handlers). + +### Monadic computation + +- **The `cgp-monad` crate composes computations that short-circuit.** `PipeMonadic` runs providers in order under the monad `M`. `ErrMonadic` passes on the `Ok` value and stops at an `Err`, `OkMonadic` does the opposite, and `IdentMonadic` composes plainly. `BindOk` and `BindErr` lift a provider over `Result`, and `OkMonadicTrans` and `ErrMonadicTrans` stack monads. The traits behind them are `MonadicBind`, `ContainsValue`, `LiftValue`, and `MonadicTrans` ([#127](https://github.com/contextgeneric/cgp/pull/127), [#129](https://github.com/contextgeneric/cgp/pull/129)). `DispatchMatchers` is now an alias for `PipeMonadic`, and `cgp::extra::monad` re-exports the crate. See [`PipeMonadic`](/docs/reference/providers/monad/pipe_monadic), [`BindOk`](/docs/reference/providers/monad/bind_ok), [`BindErr`](/docs/reference/providers/monad/bind_err), and [`MonadicBind`](/docs/reference/traits/monad/monadic_bind). + +### Handlers + +- **`AsyncComputer` is the asynchronous counterpart of `Computer`.** `CanComputeAsync` returns an `Output` without a `Result`, and `Handler` remains the asynchronous counterpart of `TryComputer`. `AsyncComputerRef` and `CanComputeAsyncRef` take a reference ([#136](https://github.com/contextgeneric/cgp/pull/136)). See [`AsyncComputer`](/docs/reference/components/handler/async_computer) and [`AsyncComputerRef`](/docs/reference/components/handler/async_computer_ref). +- **`#[cgp_computer]` accepts an `async` function** and derives an `AsyncComputer` for it ([#137](https://github.com/contextgeneric/cgp/pull/137)). +- **`ComposeHandlers` runs one provider and passes its output to the next,** for `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`. `PipeHandlers` is built on it ([#129](https://github.com/contextgeneric/cgp/pull/129), [#136](https://github.com/contextgeneric/cgp/pull/136)). See [`ComposeHandlers`](/docs/reference/providers/handler/compose_handlers). +- **Five promotion providers collect what a provider can be promoted to:** `PromoteComputer`, `PromoteTryComputer`, `PromoteProducer`, `PromoteAsyncComputer`, and `PromoteHandler`, each a table of the promotions for one kind of provider ([#137](https://github.com/contextgeneric/cgp/pull/137)). See [`PromoteComputer`](/docs/reference/providers/handler/promote_computer) and [`PromoteHandler`](/docs/reference/providers/handler/promote_handler). +- **`UseField` is a `Computer` and an `AsyncComputer`.** It runs the `CanCompute` or `CanComputeAsync` implementation of the field named by `Tag` ([#132](https://github.com/contextgeneric/cgp/pull/132), [#136](https://github.com/contextgeneric/cgp/pull/136)). See [`UseField`](/docs/reference/providers/use_field). +- **`NoCode` is a value of type `PhantomData<()>`** for calling a handler that has no code ([#132](https://github.com/contextgeneric/cgp/pull/132)). +- **`ErrorOnly` is a context that carries only an error type,** with `HasErrorType::Error = E` ([#129](https://github.com/contextgeneric/cgp/pull/129)). +- **`CanSendRun` and its provider trait `SendRunner` return a `Send` future** ([#149](https://github.com/contextgeneric/cgp/pull/149)); see [the `Send` bound](#async_trait-no-longer-requires-send). + +### Type-level strings and lifetimes + +- **`StaticString` produces a `&'static str` from a `Symbol!` type.** `::VALUE` is `"hello"` in a const context, which the length that `Symbol!` now carries makes possible ([#159](https://github.com/contextgeneric/cgp/pull/159)). See [`StaticString`](/docs/reference/traits/formatting/static_string). +- **`Life<'a>` writes a lifetime as a type** ([#145](https://github.com/contextgeneric/cgp/pull/145), [#166](https://github.com/contextgeneric/cgp/pull/166)). See [`Life`](/docs/reference/types/life). + +## Improvements + +- **A getter method may take a first argument other than `self`:** `#[cgp_getter]` and `#[cgp_auto_getter]` accept `fn foo_bar(foo: &Self::Foo) -> &Self::Bar`, and `UseField` implements the provider when `Self::Foo` has the field ([#169](https://github.com/contextgeneric/cgp/pull/169)). See [`#[cgp_getter]`](/docs/reference/macros/cgp_getter) and [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter). +- **A component trait may declare lifetime parameters,** which `IsProviderFor` carries as `Life<'a>` and `check_components!` accepts ([#145](https://github.com/contextgeneric/cgp/pull/145)). A component such as `trait CanGreet<'a>` compiles where v0.4.2 rejected it. +- **A bare identifier sets the provider name:** `#[cgp_getter(FooGetter)]` and `#[cgp_type(FooTypeProvider)]` mean the same as `provider: FooGetter` and `provider: FooTypeProvider` ([#143](https://github.com/contextgeneric/cgp/pull/143), [#163](https://github.com/contextgeneric/cgp/pull/163)). See [`#[cgp_type]`](/docs/reference/macros/cgp_type). +- **The prelude exports the new names:** `Chars`, `Symbol`, `Life`, `CgpData`, `CgpRecord`, `CgpVariant`, `UpdateField`, `PartialData`, `MapTypeRef`, `IsRef`, `IsMut`, `HasExtractorMut`, `AsyncComputer`, `#[cgp_auto_dispatch]`, and the `MatchWithValueHandlers` and `MatchFirstWithValueHandlers` providers, so `use cgp::prelude::*` reaches them ([#154](https://github.com/contextgeneric/cgp/pull/154), [#137](https://github.com/contextgeneric/cgp/pull/137), [#139](https://github.com/contextgeneric/cgp/pull/139)). +- **`DelegateComponent` accepts an unsized name:** `impl DelegateComponent for Table` compiles, where v0.4.2 failed with `E0277` ([#147](https://github.com/contextgeneric/cgp/pull/147)). See [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component). + +## Fixes + +- **`new` with an array key:** `delegate_components!` declares a struct named by `new` once, where an entry such as `[FooKey, BarKey]: UseDelegate` declared it once per key and failed with `E0428` ([#164](https://github.com/contextgeneric/cgp/pull/164)). See [`delegate_components!`](/docs/reference/macros/delegate_components). +- **`CanUseComponent` for an unsized parameter:** a context whose provider implements `IsProviderFor` for `str` satisfies `CanUseComponent`, where v0.4.2 failed with `E0277` ([#166](https://github.com/contextgeneric/cgp/pull/166)). See [`CanUseComponent`](/docs/reference/traits/wiring/can_use_component). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-6-0.md b/docs/release-notes/cgp/v0-6-0.md new file mode 100644 index 00000000..b3028e13 --- /dev/null +++ b/docs/release-notes/cgp/v0-6-0.md @@ -0,0 +1,63 @@ +--- +title: 'cgp v0.6.0 release notes' +sidebar_label: 'v0.6.0' +sidebar_position: 99400 +description: 'cgp v0.6.0 adds #[cgp_impl], direct delegation on the context, and #[cgp_inherit], and removes the HasCgpProvider trait.' +slug: v0.6.0 +--- + +# cgp v0.6.0 + +Version 0.6.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, lets a provider be written like a blanket impl of its consumer trait and lets a context own its wiring table. This page lists every change a user can see and the steps that take a project there from v0.5.0. + +Released on 2025-10-26. + +- **Release post:** [CGP v0.6.0 Release: Major ergonomic improvements for provider and context implementations](/blog/v0-6-0-release) +- **Crate:** [`cgp` 0.6.0 on crates.io](https://crates.io/crates/cgp/0.6.0) +- **Changes:** [v0.5.0...v0.6.0](https://github.com/contextgeneric/cgp/compare/v0.5.0...v0.6.0) + +## Summary + +`#[cgp_impl]` writes a provider as an impl of its consumer trait, and `delegate_components!` accepts the context type itself, so a context needs no separate table struct. Consumer traits now route through `DelegateComponent`, which removes the `HasCgpProvider` trait. `#[cgp_context]` keeps working through a blanket `DelegateComponent` impl, and `#[cgp_inherit]` lets a context inherit a preset. + +## Compatibility + +- **Minimum Rust version:** 1.89, unchanged from v0.5.0. +- **Released together:** the workspace's 23 crates published on crates.io, all at 0.6.0. + +## Upgrading + +A project moving from v0.5.0 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.6.0"`. +2. **Replace `HasCgpProvider`** where the project names the trait or implements it by hand, per [the removal](#hascgpprovider-is-removed). A context declared with `#[cgp_context]` and a provider declared with `#[cgp_provider]` need no change. + +## Breaking changes + +### `HasCgpProvider` is removed + +The trait `HasCgpProvider` and its `CgpProvider` associated type are removed from the prelude and from `cgp::core::component` ([#175](https://github.com/contextgeneric/cgp/pull/175)). The blanket impls of consumer traits and `CanUseComponent` now look a context's provider up through [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component). + +- **Old:** `HasCgpProvider` gave a context its provider table through `type CgpProvider`, and a consumer-trait blanket impl required `Context: HasCgpProvider` and `Context::CgpProvider: Provider`. +- **New:** the blanket impl requires `Context: DelegateComponent` and `Context::Delegate: Provider`. `#[cgp_context]` generates `impl DelegateComponent for App { type Delegate = AppComponents; }`, so a context that it declares works unchanged. +- **What to do:** replace a hand-written `impl HasCgpProvider for Ctx { type CgpProvider = Table; }` with `impl DelegateComponent for Ctx { type Delegate = Table; }`, or wire the context directly as [the new feature](#contexts) describes. Replace a bound `C: HasCgpProvider` with `C: DelegateComponent`, and `C::CgpProvider` with `C::Delegate`. + +## New features + +### Providers + +- **`#[cgp_impl]` writes a provider as an impl of its consumer trait.** The impl keeps the consumer trait's signature, with the context in the `Self` position, and the macro rewrites it into the provider-trait shape and generates the `IsProviderFor` impl ([#174](https://github.com/contextgeneric/cgp/pull/174)). The attribute names the provider type, optionally after `new` to declare its struct, and optionally names the component after a colon, as `#[cgp_impl(new GreetHello: GreeterComponent)]`. The prelude exports it. See [`#[cgp_impl]`](/docs/reference/macros/cgp_impl). + +### Contexts + +- **A context implements the consumer traits of the components it wires directly.** [`delegate_components!`](/docs/reference/macros/delegate_components) accepts the context type, as in `delegate_components! { App { GreeterComponent: GreetHello } }`, so a separate `AppComponents` struct is unnecessary ([#175](https://github.com/contextgeneric/cgp/pull/175)). The context may also implement the consumer trait of a component it does not wire by hand. +- **`#[cgp_inherit]` makes a context inherit a preset.** `#[cgp_inherit(MyPreset)]` on a struct replaces `#[cgp_context(AppComponents: MyPreset)]`, with no intermediate `AppComponents` struct ([#176](https://github.com/contextgeneric/cgp/pull/176)). The prelude exports it. + +## Fixes + +- **`self` in a default method body:** a default body in a `#[cgp_component]` trait may use `self`, which the macro rewrites to the context in the provider trait, where v0.5.0 failed with `E0424` ([#179](https://github.com/contextgeneric/cgp/pull/179)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-6-1.md b/docs/release-notes/cgp/v0-6-1.md new file mode 100644 index 00000000..3a1394df --- /dev/null +++ b/docs/release-notes/cgp/v0-6-1.md @@ -0,0 +1,50 @@ +--- +title: 'cgp v0.6.1 release notes' +sidebar_label: 'v0.6.1' +sidebar_position: 99399 +description: 'cgp v0.6.1 lets #[cgp_impl] omit the context type, adds #[check_providers] to check each provider, and allows associated types in getter traits.' +slug: v0.6.1 +--- + +# cgp v0.6.1 + +Version 0.6.1 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, lets a provider leave out its context type, checks a provider on its own, and lets a getter trait declare an associated type. This page lists every change a user can see and the steps that take a project there from v0.6.0. + +Released on 2026-02-01. + +- **Release post:** [CGP v0.6.1 Release: Improving Ergonomics and Debugging](/blog/v0-6-1-release) +- **Crate:** [`cgp` 0.6.1 on crates.io](https://crates.io/crates/cgp/0.6.1) +- **Changes:** [v0.6.0...v0.6.1](https://github.com/contextgeneric/cgp/compare/v0.6.0...v0.6.1) + +## Summary + +`#[cgp_impl]` accepts an impl header without the context type, so a provider reads as `impl Greeter where Self: HasName`. `check_components!` gains `#[check_providers(...)]`, which asserts that each listed provider works for a context, and `#[cgp_auto_getter]` and `#[cgp_getter]` accept a getter trait that declares an associated type. The release removes and renames nothing. + +## Compatibility + +- **Minimum Rust version:** 1.89, unchanged from v0.6.0. +- **Released together:** the workspace's 23 crates published on crates.io, all at 0.6.1. + +## Upgrading + +A project moving from v0.6.0 changes the version to `cgp = "0.6.1"`, and nothing else is needed. The release removes and renames no item, and the explicit `impl Greeter for Context` header, a plain `check_components!` table, and a getter trait without an associated type all compile as they did at v0.6.0. + +## New features + +### Providers + +- **`#[cgp_impl]` accepts an impl header without the context type.** `#[cgp_impl(new GreetHello)] impl Greeter where Self: HasName { … }` means the same as `impl Greeter for Context where Context: HasName { … }`. The header names the consumer trait where the explicit form names the context, and the macro adds the context parameter itself, so `Self` stands for that context ([#189](https://github.com/contextgeneric/cgp/pull/189)). A v0.6.0 `#[cgp_impl]` rejected the header with ``expect impl trait to contain path``. The explicit form keeps working. See [`#[cgp_impl]`](/docs/reference/macros/cgp_impl). + +### Wiring and checking + +- **`#[check_providers(...)]` checks each listed provider.** `check_components!` asserts by default that the context can use each component. With `#[check_providers(RectangleArea, ScaledArea)]` before the check trait's name, it asserts instead that each listed provider is a provider for the component and the context, meaning that it implements `IsProviderFor` ([#190](https://github.com/contextgeneric/cgp/pull/190)). The check does not read the context's wiring, so it passes for a provider that the context does not use. A missing dependency is reported against the provider that needs it, which separates the failing layer of a composed provider from the layers that work. See [checking each provider](/docs/reference/macros/check_components#checking-each-provider-instead-of-the-context). +- **One `check_components!` invocation may hold several tables,** so a plain check and a provider check sit in the same invocation ([#190](https://github.com/contextgeneric/cgp/pull/190)). A v0.6.0 invocation with a second table failed with ``unexpected token``. See [`check_components!`](/docs/reference/macros/check_components). + +### Getter traits + +- **A getter trait may declare an associated type.** `#[cgp_auto_getter]` and `#[cgp_getter]` accept `type Name: Display;` beside one getter method that returns `&Self::Name`, and the context's field decides the type, which must satisfy the declared bound ([#191](https://github.com/contextgeneric/cgp/pull/191)). A v0.6.0 getter trait with an associated type failed with ``getter trait can only contain getter methods``, so the type needed a separate `#[cgp_type]` trait. The trait takes one associated type, without generic parameters, and exactly one getter method. The method's return type must read that type. See [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter#a-type-inferred-from-the-field) and [`#[cgp_getter]`](/docs/reference/macros/cgp_getter). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-7-0.md b/docs/release-notes/cgp/v0-7-0.md new file mode 100644 index 00000000..d126194d --- /dev/null +++ b/docs/release-notes/cgp/v0-7-0.md @@ -0,0 +1,117 @@ +--- +title: 'cgp v0.7.0 release notes' +sidebar_label: 'v0.7.0' +sidebar_position: 99300 +description: 'cgp v0.7.0 adds #[cgp_fn], #[implicit], #[use_type] and #[use_provider], removes #[cgp_context], and renames ProvideType to TypeProvider.' +slug: v0.7.0 +--- + +# cgp v0.7.0 + +Version 0.7.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables pluggable trait implementations in Rust, adds attributes that write context-generic code as plain functions, and removes `#[cgp_context]`. This page lists every change a user can see and the steps that take a project there from v0.6.1. + +Released on 2026-02-28. + +- **Release post:** [Supercharge Rust functions with implicit arguments using CGP v0.7.0](/blog/v0.7.0-release) +- **Crate:** [`cgp` 0.7.0 on crates.io](https://crates.io/crates/cgp/0.7.0) +- **Changes:** [v0.6.1...v0.7.0](https://github.com/contextgeneric/cgp/compare/v0.6.1...v0.7.0) + +## Summary + +`#[cgp_fn]` turns a function into a trait, and `#[implicit]`, `#[uses]`, `#[extend]`, `#[use_provider]`, and `#[use_type]` replace the getter traits and `where` clauses that surround it. `#[cgp_context]` is removed, so a context is a plain struct that `delegate_components!` wires, and `check_components!` and `delegate_and_check_components!` take that context directly. `ProvideType` is renamed `TypeProvider`, and `#[cgp_type]` no longer generates its `{Type}Of` alias. + +## Compatibility + +- **Minimum Rust version:** 1.89, unchanged from v0.6.1. +- **Released together:** the workspace's 23 crates published on crates.io, all at 0.7.0. + +## Upgrading + +A project moving from v0.6.1 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.7.0"`. +2. **Remove `#[cgp_context]`** from each context, per [the removal](#cgp_context-is-removed). +3. **Rewrite the check macros:** [`check_components!`](#check_components-takes-the-context-and-an-optional-trait-name) and [`delegate_and_check_components!`](#delegate_and_check_components-delegates-on-the-context). +4. **Rename the type provider:** `ProvideType` and `TypeComponent`, per [the rename](#providetype-and-typecomponent-are-renamed-typeprovider-and-typeprovidercomponent). +5. **Replace the generated aliases** of `#[cgp_type]`, per [the alias removal](#the-typeof-alias-is-removed-from-cgp_type). +6. **Build the crate** and fix what the compiler reports. + +## Breaking changes + +### `#[cgp_context]` is removed + +`#[cgp_context]` is removed from `cgp` and from the prelude ([#205](https://github.com/contextgeneric/cgp/pull/205)). A context is an ordinary struct that `delegate_components!` wires directly. + +- **Old:** `#[cgp_context] pub struct App;` generated an `AppComponents` struct that held the wiring table, so the table was written as `delegate_components! { AppComponents { … } }`. +- **New:** `pub struct App;` with `delegate_components! { App { GreeterComponent: GreetHello } }`, which v0.6.1 already accepts. The attribute fails with ``cannot find attribute `cgp_context` in this scope``. +- **What to do:** delete the attribute, and write the context's name wherever the code named `AppComponents`. Update the context's check macros as the next two entries describe. + +### `check_components!` takes the context and an optional trait name + +`check_components!` writes the context where it wrote the check trait's name, and an attribute names the trait ([#214](https://github.com/contextgeneric/cgp/pull/214), [#215](https://github.com/contextgeneric/cgp/pull/215)). See [`check_components!`](/docs/reference/macros/check_components). + +- **Old:** `check_components! { CanUseApp for App { GreeterComponent } }`. +- **New:** `check_components! { App { GreeterComponent } }` generates a check trait named `__CheckApp`, and `check_components! { #[check_trait(CanUseApp)] App { GreeterComponent } }` names it. A `#[check_providers(...)]` attribute may stand beside `#[check_trait(...)]` in either order. +- **What to do:** delete `CanUseApp for`, and add `#[check_trait(CanUseApp)]` where other code names the trait. The old form fails with `expected curly braces`. + +### `delegate_and_check_components!` delegates on the context + +`delegate_and_check_components!` wires the context itself and takes no separate table type ([#214](https://github.com/contextgeneric/cgp/pull/214)). See [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components). + +- **Old:** `delegate_and_check_components! { CanUseApp for App; App { GreeterComponent: GreetHello } }`, where the name after `for` and the table type after `;` came first, and the table type could differ from the context, as `AppComponents` did. +- **New:** `delegate_and_check_components! { App { GreeterComponent: GreetHello } }` wires `App` and generates a check trait named `__CanUseApp`, and `#[check_trait(CanUseApp)]` names it. +- **What to do:** delete the `CanUseApp for App;` prefix, and add `#[check_trait(...)]` where other code names the trait. A table that is not the context, such as one reached through a hand-written `impl DelegateComponent for App`, is wired with `delegate_components!` and checked with a separate `check_components!`. + +### `ProvideType` and `TypeComponent` are renamed `TypeProvider` and `TypeProviderComponent` + +The provider trait of `HasType` and its component key take the names that `#[cgp_type]` gives its own providers ([#211](https://github.com/contextgeneric/cgp/pull/211)). `UseType`, `UseDelegatedType`, and `UseField` implement the renamed trait, and the prelude exports `TypeProvider` where it exported `ProvideType`. See [`HasType`](/docs/reference/components/has_type). + +- **Old:** `ProvideType` with the component `TypeComponent`. +- **New:** `TypeProvider`, which the prelude exports, with the component `TypeProviderComponent` in `cgp::core::types`. +- **What to do:** rename the trait and the key in each import, impl, bound, and `#[cgp_provider(TypeComponent)]` attribute. + +### The `{Type}Of` alias is removed from `#[cgp_type]` + +[`#[cgp_type]`](/docs/reference/macros/cgp_type) no longer generates a type alias for the associated type ([#212](https://github.com/contextgeneric/cgp/pull/212)). The aliases `ErrorOf` and `RuntimeOf` remain, written by hand in `cgp::core::error` and `cgp::extra::runtime`. + +- **Old:** `#[cgp_type] pub trait HasScalarType { type Scalar; }` also generated `pub type ScalarOf = ::Scalar;`. +- **New:** the trait alone. A use of `ScalarOf` fails with ``cannot find type `ScalarOf` in this scope``. +- **What to do:** write `::Scalar`, or import the type with [`#[use_type(HasScalarType::Scalar)]`](/docs/reference/attributes/use_type) and name it `Scalar`. + +## New features + +### Functions + +- **`#[cgp_fn]` turns a function into a trait with one blanket impl** ([#197](https://github.com/contextgeneric/cgp/pull/197), [#198](https://github.com/contextgeneric/cgp/pull/198)). The function name in PascalCase names the trait, and `#[cgp_fn(CanGreet)]` names it otherwise. A generic parameter on the function lands on the trait and the impl, and a `where` clause lands on the impl alone. The trait takes the function's visibility, and the prelude exports the attribute. See [`#[cgp_fn]`](/docs/reference/macros/cgp_fn). +- **`#[implicit]` fills an argument from the context's field of the same name.** In `fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64`, a caller passes neither argument, and any struct that derives `HasField` and has the two fields can call `rectangle_area()` ([#197](https://github.com/contextgeneric/cgp/pull/197), [#198](https://github.com/contextgeneric/cgp/pull/198), [#201](https://github.com/contextgeneric/cgp/pull/201)). The attribute also works in the methods of a `#[cgp_impl]` block, which removes the getter trait that a provider needed to read a field. See [`#[implicit]`](/docs/reference/attributes/implicit). +- **An implicit argument is read according to its type.** An owned argument is cloned out of the field, so its type needs `Clone` and not `Copy`. A `&T` argument borrows the field, a `&str` argument borrows a `String` field, and a `&mut T` argument needs a `&mut self` receiver and is the function's only implicit argument. The function's first parameter must be `self`. + +### Dependencies + +- **`#[uses]` imports a trait that the body calls on `self`** ([#197](https://github.com/contextgeneric/cgp/pull/197), [#201](https://github.com/contextgeneric/cgp/pull/201)). `#[uses(RectangleArea)]` on a function `scaled_rectangle_area` adds `Self: RectangleArea` to its impl alone, so a function that imports `ScaledRectangleArea` cannot call `rectangle_area` through it. It works in `#[cgp_fn]` and in `#[cgp_impl]`. See [`#[uses]`](/docs/reference/attributes/uses). +- **`#[extend]` imports a trait and re-exports it** ([#197](https://github.com/contextgeneric/cgp/pull/197), [#202](https://github.com/contextgeneric/cgp/pull/202)). `#[extend(RectangleArea)]` on a function `scaled_rectangle_area` makes `RectangleArea` a supertrait of `ScaledRectangleArea`, so a function that imports `ScaledRectangleArea` with `#[uses]` can call `rectangle_area` as well. It works in `#[cgp_fn]`, `#[cgp_component]`, and the getter macros. `#[extend_where(...)]` adds a predicate to the `where` clauses of both the generated trait and its impl. See [`#[extend]`](/docs/reference/attributes/extend) and [`#[extend_where]`](/docs/reference/attributes/extend_where). +- **`#[use_provider]` completes the bound of an inner provider** ([#204](https://github.com/contextgeneric/cgp/pull/204), [#207](https://github.com/contextgeneric/cgp/pull/207), [#210](https://github.com/contextgeneric/cgp/pull/210)). `#[use_provider(Inner: AreaCalculator)]` adds `Inner: AreaCalculator`, inserting the `Self` argument that a hand-written bound needs, and several bounds on one provider join with `+`. It works in `#[cgp_impl]` and `#[cgp_fn]`. See [`#[use_provider]`](/docs/reference/attributes/use_provider). +- **`#[use_type]` imports an abstract type under a bare name** ([#197](https://github.com/contextgeneric/cgp/pull/197), [#200](https://github.com/contextgeneric/cgp/pull/200), [#201](https://github.com/contextgeneric/cgp/pull/201), [#202](https://github.com/contextgeneric/cgp/pull/202), [#203](https://github.com/contextgeneric/cgp/pull/203)). `#[use_type(HasScalarType::Scalar)]` lets the signature and body write `Scalar` for `Self::Scalar` and adds `HasScalarType` as a supertrait. The brace form takes an alias, `HasScalarType::{Scalar as S}`, and an equality, `HasScalarType::{Scalar = f64}`, which pins the abstract type to a concrete one. The form `@Types::HasScalarType::Scalar` imports a type from a context other than `Self`. + The attribute works in `#[cgp_fn]`, `#[cgp_impl]`, `#[cgp_component]`, and the getter macros. See [`#[use_type]`](/docs/reference/attributes/use_type). + +### Providers + +- **`#[cgp_impl(Self)]` writes an impl of a consumer trait for one concrete context** ([#206](https://github.com/contextgeneric/cgp/pull/206)). `#[cgp_impl(Self)] impl CanCalculateArea for Rectangle { … }` implements the consumer trait for `Rectangle` alone, and a `#[use_provider(RectangleArea: AreaCalculator)]` attribute may import a provider for its body. The impl names its context type. See [`#[cgp_impl]`](/docs/reference/macros/cgp_impl). + +### Wiring and checking + +- **`#[check_params(...)]` and `#[skip_check]` configure a `delegate_and_check_components!` key** ([#214](https://github.com/contextgeneric/cgp/pull/214)). `#[check_params(f64)]` before a key lists the generic arguments to check the component with, on one key or on a bracketed list of keys, and `#[skip_check]` leaves a key out of the check. See [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components). + +## Improvements + +- **A context that implements a provider trait for itself implements the consumer trait.** The blanket impl of a consumer trait requires `Context: Greeter`, where it required `Context: DelegateComponent` and `Context::Delegate: Greeter` ([#205](https://github.com/contextgeneric/cgp/pull/205)). A context that `delegate_components!` wires satisfies both forms in the same way. One that implements the provider trait by hand, as in `impl Greeter for App`, now implements `CanGreet` too. +- **A call without a receiver names its trait.** `App::make()` is ambiguous when the consumer trait and the provider trait are both in scope, and it fails with `E0034`. Write `::make()`. + +## Fixes + +- **`#[cgp_type]` with a self-referential bound:** a trait such as `type Scalar: Mul + Copy;` builds, where v0.6.1 failed with `E0275` on the `UseType` provider ([#208](https://github.com/contextgeneric/cgp/pull/208)). See [`#[cgp_type]`](/docs/reference/macros/cgp_type). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/cgp/v0-8-0.md b/docs/release-notes/cgp/v0-8-0.md new file mode 100644 index 00000000..ea1965c1 --- /dev/null +++ b/docs/release-notes/cgp/v0-8-0.md @@ -0,0 +1,439 @@ +--- +title: 'cgp v0.8.0 release notes' +sidebar_label: 'v0.8.0' +sidebar_position: 99200 +description: 'cgp v0.8.0 replaces presets with namespaces and component paths, trims the prelude to the names users write, and builds without std.' +slug: v0.8.0 +--- + +# cgp v0.8.0 + +Version 0.8.0 of `cgp`, the library for [Context-Generic Programming (CGP)](/docs/) that enables +pluggable trait implementations in Rust, lets a context select whole groups of implementations +through namespaces. This page lists every change a user can see and the steps that take a project +there from v0.7.0. + +Released on 2026-11-18. + +- **Release post:** [CGP v0.8.0 - cargo-cgp, new documentation, and namespaces](/blog/v0.8.0-release) +- **Crate:** [`cgp` 0.8.0 on crates.io](https://crates.io/crates/cgp/0.8.0) +- **Changes:** [v0.7.0...v0.8.0](https://github.com/contextgeneric/cgp/compare/v0.7.0...v0.8.0) + +## Summary + +Namespaces and component paths name groups of wiring that a context joins, in place of the +removed presets. The `open` statement chooses a provider per type in a context's own table, and the +`Struct!` and `Enum!` macros write a data shape as a declaration. The prelude now exports only the +names CGP code writes, and with its default features the library builds without `std` or an +allocator. + +## Compatibility + +- **Minimum Rust version:** 1.89, unchanged from v0.7.0. +- **Released together:** the workspace's 29 published crates, all at 0.8.0, and + [`cargo-cgp` v0.1.0](/docs/release-notes/cargo-cgp/v0.1.0), CGP's error toolchain, which is + released beside this version. +- **New crates:** `cgp-base-types`, `cgp-base`, and `cgp-base-extra`, the base layer below + `cgp-core`; `cgp-macro-core` and `cgp-macro-extra-core`, the shared cores of the macros; and + `cgp-macro-test-util` with `cgp-macro-test-util-lib`, the snapshot-testing macros the library's + own tests use. +- **Renamed crates:** `cgp-extra-macro` is now `cgp-macro-extra`, and `cgp-extra-macro-lib` is now + `cgp-macro-extra-lib`; see [the rename](#the-extra-feature-macro-crates-are-renamed). +- **Features:** the default features of `cgp`, `cgp-extra`, and `cgp-error-extra` are empty, and + `cgp` gains an `alloc` feature; see [the default features](#the-default-features-include-no-allocator). + +## Upgrading + +A project moving from v0.7.0 takes these steps, in this order: + +1. **Change the version** to `cgp = "0.8.0"`, adding `features = ["alloc"]` if the wiring uses + `DebugError` or `DisplayError`, per [the default features](#the-default-features-include-no-allocator). +2. **Rename a direct dependency** on `cgp-extra-macro` or `cgp-extra-macro-lib`, per + [the rename](#the-extra-feature-macro-crates-are-renamed). +3. **Replace each preset** with a configuration namespace or an aggregate provider, per + [the preset removal](#the-preset-system-is-removed). +4. **Rewrite the attribute forms** that changed: + [`#[use_type]`'s separator](#use_type-separates-the-trait-from-its-type-with-a-dot) and + [`derive_delegate`](#derive_delegate-is-an-attribute-of-its-own). +5. **Import each name the prelude dropped** from its module, writing the English name of each + type-level type, per [the prelude](#the-prelude-exports-only-the-names-users-write) and + [the Greek-letter names](#the-greek-letter-type-names-are-removed). +6. **Build the crate**, removing the imports the compiler reports as unused and qualifying an + ambiguous `Struct!` or `Enum!`, per [the handler macros](#the-handler-macros-generate-self-contained-code) + and [the shape macros](#struct-and-enum-join-the-prelude). +7. **Update tests that compare output**, such as a UI test's expected compiler messages or an + assertion on an error backend's report, per [the error messages](#the-core-traits-drop-their-custom-error-messages) + and [the error backends](#the-error-backends-change-their-output). + +## Breaking changes + +### The preset system is removed + +`cgp_preset!`, `#[cgp_inherit]`, `#[wrap_provider]`, `#[cgp::re_export_imports]`, `IsPreset`, and +the `replace_with!` macro the presets expanded through are removed +([#242](https://github.com/contextgeneric/cgp/pull/242)). A context could inherit only one preset, +while namespaces group wiring through the trait system and nest. + +- **Shared fixed choices:** a preset's provider choices become a configuration namespace, defined + with [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) and joined with a `namespace` + statement in the context's [`delegate_components!`](/docs/reference/macros/delegate_components#the-namespace-statements). +- **A selectable group:** a group that configurations swap becomes an + [aggregate provider](/docs/concepts/aggregate-providers), selected through an `@`-path key. +- **Migration:** the release post works one preset through to a namespace, with its component + checks, in [Replace presets with namespace configuration](/blog/v0.8.0-release#replace-presets-with-namespace-configuration). + +### The prelude exports only the names users write + +`use cgp::prelude::*` brings in the macros and derives, `PhantomData`, `HasErrorType`, +`CanRaiseError`, `CanWrapError`, `UseType`, `UseDelegate`, and `DefaultNamespace` +([#294](https://github.com/contextgeneric/cgp/pull/294)). The code the macros generate goes through +`cgp::macro_prelude`, a module of its own rather than an alias of the prelude, so the prelude no +longer carries the generated code's names. + +- **Old:** the glob also brought in the wiring traits, the field traits, the type-level types, + `HasType`, and the handler family. +- **New:** each dropped name is imported from its module: the wiring traits such as + `DelegateComponent` and `IsProviderFor` from `cgp::core::component`; the field-access, builder, + extractor, and shape traits from `cgp::core::field::traits`; `UseField` and the field-state markers + from `cgp::core::field::impls`; `Cons`, `Nil`, `Either`, `Void`, `Field`, `Index`, `Life`, `Chars`, + and `Symbol` from `cgp::core::field::types`; `HasType` and `TypeProvider` from `cgp::core::types`; + the handler traits, keys, and promotion bundles from `cgp::extra::handler`; and the value matchers + from `cgp::extra::dispatch`. +- **What to do:** add the import the compiler asks for. A derive still needs no import, so + `#[derive(HasField)]` works through the prelude while a `HasField` bound or a `.get_field()` call + imports `HasField`. A [`#[cgp_impl]`](/docs/reference/macros/cgp_impl#importing-the-component-key) + provider for a handler trait such as `Computer` imports `ComputerComponent` beside the trait. + +Raw compiler output names a dropped type through `cgp::macro_prelude`, such as +`cgp::macro_prelude::Chars` where v0.7.0 printed `cgp::prelude::Chars`. + +### `#[use_type]` separates the trait from its type with a dot + +[`#[use_type]`](/docs/reference/attributes/use_type) writes the associated type after a `.` +([#248](https://github.com/contextgeneric/cgp/pull/248)), and an import from another context names +that context after `in` ([#255](https://github.com/contextgeneric/cgp/pull/255)). + +- **Old:** `#[use_type(HasScalarType::Scalar)]`, `#[use_type(HasErrorType::{Error = AppError})]`, + and `#[use_type(@Types::HasScalarType::Scalar)]`. +- **New:** `#[use_type(HasScalarType.Scalar)]`, `#[use_type(HasErrorType.{Error = AppError})]`, + and `#[use_type(HasScalarType.Scalar in Types)]`. +- **What to do:** rewrite each attribute; the macro rejects the old separator. + +### `derive_delegate` is an attribute of its own + +A component that generates a `UseDelegate` provider writes +[`#[derive_delegate(...)]`](/docs/reference/attributes/derive_delegate) beneath `#[cgp_component]`, +one attribute per dispatch specification ([#241](https://github.com/contextgeneric/cgp/pull/241)). + +- **Old:** `#[cgp_component { provider: AreaCalculator, derive_delegate: UseDelegate }]`. +- **New:** `#[cgp_component(AreaCalculator)]` followed by `#[derive_delegate(UseDelegate)]`. +- **What to do:** move the key into the attribute. A new component dispatches per type with + [the `open` statement](#the-open-statement) instead. + +### The default features include no allocator + +The default features of `cgp`, `cgp-extra`, and `cgp-error-extra` are empty, and `cgp` gains an +`alloc` feature that turns on the providers needing an allocator, `DebugError` and `DisplayError` +([#287](https://github.com/contextgeneric/cgp/pull/287)). + +- **Old:** `cgp-extra`'s default `full` feature turned on `cgp-error-extra`'s `alloc`, so both + providers were always present. +- **New:** a crate that wires [`DebugError`](/docs/reference/providers/error/debug_error) or + [`DisplayError`](/docs/reference/providers/error/display_error) writes + `cgp = { version = "0.8.0", features = ["alloc"] }`. + +### The Greek-letter type names are removed + +The type-level types have only their English names +([#243](https://github.com/contextgeneric/cgp/pull/243)). + +- **Old:** v0.7.0 declared them under Greek letters with the English names as aliases, and the + prelude exported both: `π` for `Cons`, `ε` for `Nil`, `σ` for `Either`, `θ` for `Void`, `ζ` for + `Chars`, `ψ` for `Symbol`, `δ` for `Index`, and `ω` for `Field`. +- **New:** only [`Cons`](/docs/reference/types/cons), [`Nil`](/docs/reference/types/nil), + [`Either`](/docs/reference/types/either), [`Void`](/docs/reference/types/void), + [`Chars`](/docs/reference/types/chars), [`Symbol`](/docs/reference/macros/symbol), [`Index`](/docs/reference/types/index_type), and + [`Field`](/docs/reference/types/field) exist, and raw compiler output prints them by these names. +- **What to do:** replace a Greek name with its English name, imported from + `cgp::core::field::types`. + +### The extra-feature macro crates are renamed + +`cgp-extra-macro` and `cgp-extra-macro-lib`, which carry `#[cgp_computer]`, `#[cgp_producer]`, and +`#[cgp_auto_dispatch]`, are renamed `cgp-macro-extra` and `cgp-macro-extra-lib`, beside a new +`cgp-macro-extra-core` ([#274](https://github.com/contextgeneric/cgp/pull/274)). Code that reaches +the macros through `cgp::prelude` is unaffected; a crate that depends on the old crates directly +changes its manifest and its `cgp_extra_macro::` paths. + +### The handler macros generate self-contained code + +[`#[cgp_computer]`](/docs/reference/macros/cgp_computer), +[`#[cgp_producer]`](/docs/reference/macros/cgp_producer), and +[`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) emit their final code with every +name qualified, instead of nested `#[cgp_new_provider]`, `delegate_components!`, and +`#[cgp_computer]` invocations that resolved through the caller's imports +([#274](https://github.com/contextgeneric/cgp/pull/274)). + +- **Unused imports:** an import that existed only for the old expansion trips the `unused_imports` + lint; remove it. +- **Computer signatures:** the per-variant computers `#[cgp_auto_dispatch]` generates give each + elided argument lifetime its own name, so their impls are more general. +- **Rejected input:** `#[cgp_auto_dispatch]` rejects a typed receiver such as `self: Box`, + which miscompiled, and an attribute argument, which it ignored. +- **Helper names:** its private per-method helper is named `__compute_{method}__` + ([#273](https://github.com/contextgeneric/cgp/pull/273)), so code that called the undocumented + helper by the method's name stops compiling. + +### `Struct!` and `Enum!` join the prelude + +The prelude exports the [`Struct!`](/docs/reference/macros/struct) and +[`Enum!`](/docs/reference/macros/enum) macros ([#276](https://github.com/contextgeneric/cgp/pull/276)). +A module that glob-imports the prelude beside another crate exporting a macro of either name gets +an ambiguity error where it uses the name; qualify the call. + +### The core traits drop their custom error messages + +`DelegateComponent`, `IsProviderFor`, `HasField`, and `HasFieldMut` no longer carry +`#[diagnostic::on_unimplemented]` messages ([#257](https://github.com/contextgeneric/cgp/pull/257)). +Plain `cargo check` reports an unmet bound on them in rustc's own wording, and +[`cargo cgp check`](/docs/tooling/cargo-cgp/check) rewrites them. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. A test that +compares compiler output updates the messages it expects. + +### The error backends change their output + +The standalone error backends change behavior +([#269](https://github.com/contextgeneric/cgp/pull/269), +[#270](https://github.com/contextgeneric/cgp/pull/270)). + +- **`cgp-error-eyre`:** builds eyre with `auto-install`, so a report no longer panics when the + application has installed no hook with `eyre::set_hook`, and with `track-caller`, so a report's + location is the line that called `raise_error` or `wrap_error`. +- **`cgp-error-std`:** `WrapError` prints only its detail with `{}`, and the whole chain with `{:#}` + and `{:?}`, where v0.7.0 also printed the source inside `Display` and so repeated it when a + reporter walked `source()`. `RaiseBoxedStdError` gains an `ErrorWrapper` impl. +- **Dependencies:** the minimum versions rise to anyhow 1.0.104 and eyre 0.6.14. +- **What to do:** update assertions on a report's text or location. + +## New features + +### Namespaces and component paths + +A namespace names a group of component wirings that a context joins as a whole +([#219](https://github.com/contextgeneric/cgp/pull/219), +[#223](https://github.com/contextgeneric/cgp/pull/223), +[#224](https://github.com/contextgeneric/cgp/pull/224), +[#228](https://github.com/contextgeneric/cgp/pull/228)). The +[namespaces concept](/docs/concepts/namespaces) explains the model. + +- **`cgp_namespace!`** defines a namespace, optionally inheriting a parent's entries; a namespace + with no entries of its own may omit the braces, as `new AppNamespace: DefaultNamespace` + ([#265](https://github.com/contextgeneric/cgp/pull/265)). See + [`cgp_namespace!`](/docs/reference/macros/cgp_namespace). +- **`#[prefix(@path in Namespace)]`** registers a component under a hierarchical path in a + namespace. See [`#[prefix]`](/docs/reference/attributes/prefix). +- **The `namespace` statement** inside `delegate_components!` joins a namespace, and an `@`-path key + such as `@app.core: CoreComponents` delegates every component under the path to one provider. See + [the namespace statements](/docs/reference/macros/delegate_components#the-namespace-statements). +- **The `=>` operator** redirects a key's lookup along a path, and the `for` statement, + `for in Table { … }`, emits one mapping per entry of another lookup table, which is + how a context adopts a namespace's per-type defaults + ([#228](https://github.com/contextgeneric/cgp/pull/228)). See + [the operators](/docs/reference/macros/delegate_components#the-operators). +- **`#[default_impl(T in DefaultImpls1)]`** registers a `#[cgp_impl]` provider as a + namespace's default for one type ([#231](https://github.com/contextgeneric/cgp/pull/231)). See + [`#[default_impl]`](/docs/reference/attributes/default_impl) and + [`DefaultImpls1`](/docs/reference/traits/namespace/default_impls1). +- **`Path!`** writes a type-level path, and a path groups alternatives with braces or brackets, as + `@app.[FooComponent, BarComponent]` ([#241](https://github.com/contextgeneric/cgp/pull/241)). See + [`Path!`](/docs/reference/macros/path). +- **Generic path keys:** a path key and a check entry may carry the impl's generic parameters + ([#226](https://github.com/contextgeneric/cgp/pull/226)). +- **`RedirectLookup`** is the provider that re-routes a lookup along a path, and + [`DefaultNamespace`](/docs/reference/traits/namespace/default_namespace) is the built-in namespace, + in the prelude ([#219](https://github.com/contextgeneric/cgp/pull/219)). See + [`RedirectLookup`](/docs/reference/providers/redirect_lookup). +- **CGP's own components** register in `DefaultNamespace`: the error components under + `@cgp.core.error` and the handler components under `@cgp.extra.handler`. + +### The `open` statement + +`open AreaCalculatorComponent;` inside `delegate_components!` dispatches a generic component per +type with `@AreaCalculatorComponent.Rectangle: RectangleArea` entries, without a namespace or a +nested `UseDelegate` table ([#222](https://github.com/contextgeneric/cgp/pull/222), +[#248](https://github.com/contextgeneric/cgp/pull/248)). A key has one segment per type parameter +of the component, so `open` dispatches on a later parameter too. See +[the `open` statement](/docs/reference/macros/delegate_components#choosing-a-provider-per-type-the-open-statement). + +### Functions and providers + +- **`#[impl_generics(Param: Bound)]`** adds a bounded generic parameter to a `#[cgp_fn]`'s impl + alone, so a body can borrow a generic value without a trait parameter + ([#221](https://github.com/contextgeneric/cgp/pull/221)). See + [`#[impl_generics]`](/docs/reference/attributes/impl_generics). +- **`#[uses]` takes any trait bound**, such as `core::fmt::Debug` or a higher-ranked bound, where + v0.7.0 took only a trait name with optional generic arguments + ([#252](https://github.com/contextgeneric/cgp/pull/252)). See + [`#[uses]`](/docs/reference/attributes/uses). +- **A provider header names its key by path:** a `#[cgp_impl]`, `#[cgp_provider]`, or + `#[cgp_new_provider]` header that names its trait by path, as `impl crate::components::Greeter`, + derives its component key from the same path, so the module needs no import of the key + ([#296](https://github.com/contextgeneric/cgp/pull/296)). See + [importing the component key](/docs/reference/macros/cgp_impl#importing-the-component-key). +- **A `&str` implicit argument borrows any string field:** an `#[implicit] name: &str` argument reads + any field whose type implements `AsRef`, such as `String`, `Box`, or + `Cow<'static, str>`, and an `Option<&str>` argument reads any `Option` whose `U` implements + `AsRef`, through the new [`OptionAsRef`](/docs/reference/traits/field-access/option_as_ref) + trait; neither needs an allocator ([#288](https://github.com/contextgeneric/cgp/pull/288)). See + [`#[implicit]`](/docs/reference/attributes/implicit). + +### Data shapes and variants + +- **`Struct!` and `Enum!`** write a record or variant shape as the body of a struct or enum + declaration, and each is the same type `#[derive(HasFields)]` gives that body + ([#276](https://github.com/contextgeneric/cgp/pull/276), + [#277](https://github.com/contextgeneric/cgp/pull/277)). `cargo-cgp` prints shapes in this form, so + a shape read in a diagnostic can be copied into code. See [`Struct!`](/docs/reference/macros/struct) + and [`Enum!`](/docs/reference/macros/enum). +- **Fieldless variants:** [`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant), + `CgpData`, `ExtractField`, and `FromVariant` accept a variant written `Closed`, `Closed()`, or + `Closed {}`, with the payload `Nil`, where v0.7.0 rejected such a variant and the workaround was a + `()` payload ([#278](https://github.com/contextgeneric/cgp/pull/278)). The mutable extractor builds its + `&mut Nil` with `Box::leak`, so a `no_std` crate deriving it has `Box` in scope. + +### Building without `std` + +With its default features, `cgp` needs neither `std` nor `alloc`, and builds for a target such as +`x86_64-unknown-none` ([#287](https://github.com/contextgeneric/cgp/pull/287)). The `alloc` feature +turns on `DebugError` and `DisplayError`. The error backends keep their requirements: +`cgp-error-anyhow` and `cgp-error-std` need `alloc`, and `cgp-error-eyre` needs `std`. + +## Improvements + +### Documentation + +- **Generated items carry documentation:** every macro that declares a public item gives it a doc + line when the user wrote none, so a crate can enable `#![warn(missing_docs)]` + ([#286](https://github.com/contextgeneric/cgp/pull/286)). A user's own doc is kept, and a + `#[cgp_fn]` function's doc lands on the generated trait's method. +- **A provider trait names its key:** each provider trait's doc ends by naming its component key, + so an editor's hover on the trait shows the key a provider imports beside it + ([#296](https://github.com/contextgeneric/cgp/pull/296)). +- **Every crate is documented:** each published crate's docs.rs page says what the crate provides + and links the website's page for each construct, every public item has a doc comment, and docs.rs + builds each crate with every feature ([#284](https://github.com/contextgeneric/cgp/pull/284), + [#285](https://github.com/contextgeneric/cgp/pull/285), + [#289](https://github.com/contextgeneric/cgp/pull/289)). +- **Crate metadata:** each crate names its description, the project's homepage, five keywords, and + the `rust-patterns` and `no-std` categories on crates.io + ([#259](https://github.com/contextgeneric/cgp/pull/259), + [#267](https://github.com/contextgeneric/cgp/pull/267)). + +### Diagnostics + +- **Errors point at the code the user wrote:** an error about a data derive's generated impl, such + as a coherence conflict between two `#[derive(HasField)]` fields, points at the field or variant + ([#260](https://github.com/contextgeneric/cgp/pull/260)); a `->` entry's missing-key error points + at the entry rather than the whole `delegate_components!` block + ([#281](https://github.com/contextgeneric/cgp/pull/281)); and a provider header's missing key is + reported on the trait's name ([#296](https://github.com/contextgeneric/cgp/pull/296)). +- **Malformed input gets the macro's own message**, spanned on the input, where it used to fail + inside generated code or with an internal parse error + ([#273](https://github.com/contextgeneric/cgp/pull/273), + [#274](https://github.com/contextgeneric/cgp/pull/274), + [#281](https://github.com/contextgeneric/cgp/pull/281)): + - a `#[cgp_component]` `name:` parameter the trait does not declare, and a `const` generic in a + component's name; + - `#[uses]` on a component trait, with the `#[extend(...)]` form to write; + - a component method parameter written as `_` or a destructuring pattern; + - a `#[cgp_computer]` type or const parameter that only the return type uses; + - `impl Trait` in a `#[cgp_computer]` or `#[cgp_producer]` signature, and a one-argument + `Result` alias, with the `Result` form they require; + - an `Option<&[T]>` or `Option<&dyn Trait>` getter or implicit argument, with the sized field type + to read instead. +- **`#[use_type]` grounds every alias:** an imported alias resolves inside an equality pin's + right-hand side, in an expression path such as `Transaction::begin_from(pool)`, and in the + imported trait's own generic arguments; a pin on a generic trait builds a valid bound; and two + imports whose contexts resolve through each other are rejected, naming the cycle + ([#264](https://github.com/contextgeneric/cgp/pull/264)). +- **Fully qualified expansions:** every conversion and field read the macros emit is a fully + qualified trait call, so a local trait named like `AsRef` or `HasField` cannot capture it + ([#288](https://github.com/contextgeneric/cgp/pull/288)). + +### Errors + +- **`#[track_caller]` on raising and wrapping:** `CanRaiseError::raise_error` and + `CanWrapError::wrap_error` are `#[track_caller]`, and `#[cgp_component]` copies the attribute onto + the provider trait, so an error library that records `Location::caller()` sees the line that + called `raise_error` ([#270](https://github.com/contextgeneric/cgp/pull/270)). See + [`CanRaiseError`](/docs/reference/components/can_raise_error). + +## Fixes + +### Providers and components + +- **`Self::CONST` in a provider:** inside a `#[cgp_impl]` block, `Self::LIMIT` names a const the + block declares, and in a component's default body it names the trait's own const, where v0.7.0 + failed with `E0599` ([#281](https://github.com/contextgeneric/cgp/pull/281)). +- **`mut` parameters:** a component method may take a `mut` parameter or a `mut self` receiver, + which made v0.7.0's macro panic, and the forwarding impls drop the `mut` so the build raises no + `unused_mut` warning ([#281](https://github.com/contextgeneric/cgp/pull/281)). +- **`#[async_trait]` default bodies:** an `async fn` with a default body compiles, because the + macro wraps the body in `async move`, where v0.7.0 failed with ``E0277: `{integer}` is not a future`` + ([#281](https://github.com/contextgeneric/cgp/pull/281)). See + [`#[async_trait]`](/docs/reference/macros/async_trait). +- **`Self` in a provider header:** a `#[cgp_impl]` header such as `impl Comparer` reads + `Self` in the trait's arguments as the context, where v0.7.0 failed with `E0053` + ([#225](https://github.com/contextgeneric/cgp/pull/225)). +- **Unsized parameters:** a component used at an unsized parameter, such as `HasReference<'a, str>`, + resolves through `delegate_components!`, where a call through the context failed with `E0599` + ([#273](https://github.com/contextgeneric/cgp/pull/273)). + +### Wiring and checking + +- **`#[check_providers]` on a generic table:** a `check_components!` table such as ` Wrapper` + with `#[check_providers(...)]` compiles, where it failed with `E0425` and `E0207` + ([#273](https://github.com/contextgeneric/cgp/pull/273)). See + [`check_components!`](/docs/reference/macros/check_components). +- **`const` table parameters:** a table struct that `delegate_components!` declares, as a `new` + target or a nested table, keeps its `const` parameters + ([#273](https://github.com/contextgeneric/cgp/pull/273)). + +### Data derives + +- **Reserved variant names:** an enum may name a variant `Value`, `Remainder`, `Extractor`, + `ExtractorRef`, `ExtractorMut`, `Fields`, or `FieldsRef` and still derive the variant traits, where + v0.7.0 failed with an ambiguous associated item + ([#281](https://github.com/contextgeneric/cgp/pull/281)). +- **Helper attributes:** a type that combines the data derives with another derive's helper + attribute, such as `#[default]` or `#[serde(...)]`, builds, because the builder and extractor + companions keep only each field's and variant's documentation + ([#281](https://github.com/contextgeneric/cgp/pull/281)). + +- **Empty enums:** `#[derive(CgpData)]` on an enum with no variants compiles, where v0.7.0 failed + with `E0392` on an unused lifetime ([#250](https://github.com/contextgeneric/cgp/pull/250)). + +### Handler macros + +- **Without the prelude:** `#[cgp_computer]`, `#[cgp_producer]`, and `#[cgp_auto_dispatch]` work + when invoked by path in a module that imports nothing from `cgp`, and beside a local item named + like a CGP trait ([#274](https://github.com/contextgeneric/cgp/pull/274)). +- **`#[cgp_auto_dispatch]` lifetimes:** a named receiver lifetime, a trait lifetime parameter, a + reference nested in another type, and an argument outlived by the returned borrow compile, because + the macro names a method's elided lifetimes by the compiler's elision rules + ([#274](https://github.com/contextgeneric/cgp/pull/274)). +- **`#[cgp_auto_dispatch]` supertraits:** a dispatch trait with a supertrait compiles, and the + enum is required to implement the supertrait ([#274](https://github.com/contextgeneric/cgp/pull/274)). +- **`#[cgp_auto_dispatch]` names:** its generated function no longer collides with a module item + of the same name, and a method named with a raw identifier such as `r#type` no longer panics the + macro ([#273](https://github.com/contextgeneric/cgp/pull/273)). +- **`#[cgp_auto_dispatch]` beside `CanCompute`:** the generated method names the matcher's provider + trait, so a module that imports `CanCompute` no longer fails with `E0034` + ([#268](https://github.com/contextgeneric/cgp/pull/268)). +- **Raw function names:** `#[cgp_computer]` and `#[cgp_producer]` accept a function named with a + raw identifier, which made them panic ([#274](https://github.com/contextgeneric/cgp/pull/274)). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the library's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/hypershell/_category_.json b/docs/release-notes/hypershell/_category_.json new file mode 100644 index 00000000..2fbe02ef --- /dev/null +++ b/docs/release-notes/hypershell/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "hypershell", + "position": 4, + "link": { + "type": "generated-index", + "slug": "/release-notes/hypershell", + "description": "The release notes of Hypershell, a type-level DSL for shell-script-like programs built with Context-Generic Programming (CGP): one page per official release, newest first." + } +} diff --git a/docs/release-notes/hypershell/v0-1-0.md b/docs/release-notes/hypershell/v0-1-0.md new file mode 100644 index 00000000..affd199e --- /dev/null +++ b/docs/release-notes/hypershell/v0-1-0.md @@ -0,0 +1,97 @@ +--- +title: 'Hypershell v0.1.0 release notes' +sidebar_label: 'v0.1.0' +sidebar_position: 99900 +description: 'The first release of Hypershell: shell-script-like programs written as Rust types, run by handlers for commands, HTTP, JSON, hashing, and WebSockets.' +slug: v0.1.0 +--- + +# Hypershell v0.1.0 + +This page lists what the first release of Hypershell provides. Hypershell is a domain-specific +language for shell-script-like programs, built with +[Context-Generic Programming (CGP)](/docs/), a Rust library whose macros generate traits and their +wiring: a program is a Rust type, and the context that runs it chooses how each step is carried out. + +Released on 2025-06-13. + +- **Release post:** + [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release) +- **Crate:** [`hypershell` 0.1.0 on crates.io](https://crates.io/crates/hypershell/0.1.0) +- **Tag:** [v0.1.0](https://github.com/contextgeneric/hypershell/tree/v0.1.0) + +## Summary + +The `hypershell!` macro writes a program as a type, in a syntax with a pipe operator, bracketed +argument lists, and string literals. Each syntax type is a plain marker with no behavior, so the +crates that interpret it are separate: native commands through Tokio, HTTP through `reqwest`, JSON, +checksums, and WebSockets. Two contexts, `HypershellCli` and `HypershellHttp`, run a program, and +the presets they are built from let an application add its own syntax and handlers. + +## Compatibility + +- **Minimum Rust version:** 1.87, and the repository's toolchain file names the same stable release. +- **CGP version:** requires `cgp` 0.4.1, and `cgp-error-anyhow` 0.4.1 supplies the contexts' + `anyhow` error type. +- **Crates:** `hypershell`, `hypershell-components`, `hypershell-tokio-components`, + `hypershell-reqwest-components`, `hypershell-json-components`, `hypershell-hash-components`, + `hypershell-tungstenite-components`, and `hypershell-macro`, all at 0.1.0. + +## Upgrading + +This is the project's first release, so there is nothing to upgrade from. Add `hypershell` beside +`cgp` and an async runtime such as Tokio, and import `hypershell::prelude::*`. + +## New features + +### The language + +- **`hypershell!`**, in `hypershell-macro`, turns the program's shell-like syntax into a type: + `|` becomes `Pipe` over a `Product!` list, a bracketed list becomes the step's arguments, and a + bare string literal becomes a `Symbol!`. +- **Commands:** `SimpleExec` runs a command and returns its output, `StreamingExec` streams its + input and output, and `StaticArg`, `FieldArg`, `WithStaticArgs`, `WithArgs`, `FieldArgs`, + `JoinArgs`, and `UrlEncodeArg` build its arguments from literals and context fields. +- **HTTP:** `SimpleHttpRequest` and `StreamingHttpRequest`, with the methods `GetMethod`, + `PostMethod`, `PutMethod`, and `DeleteMethod`, and `Header` and `WithHeaders` for headers. +- **Streams and files:** `StreamToStdout`, `StreamToBytes`, `StreamToString`, `BytesToStream`, and + `BytesToString` convert between stream and value forms, and `ReadFile` and `WriteFile` read and + write files. `StreamToLines` has a handler, `HandleStreamToLines`, that no preset wires. +- **Data:** `EncodeJson` and `DecodeJson`, `ConvertTo` for a conversion between types, and + `Checksum` and `BytesToHex` in `hypershell-hash-components`. +- **Composition:** `Pipe` runs steps in sequence, passing each output to the next, and + `Use` hands its code to the handler `Provider` names; `WebSocket` connects to a + WebSocket endpoint. + +### Interpretation + +- **`hypershell-tokio-components`** runs commands as Tokio child processes and handles the stream + and file steps. +- **`hypershell-reqwest-components`** sends the HTTP steps with `reqwest`. +- **`hypershell-json-components`**, **`hypershell-hash-components`**, and + **`hypershell-tungstenite-components`** handle the JSON, checksum, and WebSocket steps, the last + through `tokio-tungstenite`. + +### Contexts and presets + +- **`HypershellCli`**, a context without fields, runs programs whose steps need nothing from the + context, such as commands, streams, files, and JSON. +- **`HypershellHttp`** has the same wiring and a `reqwest` `Client` in its `http_client` field, + which the HTTP steps read. +- **Presets:** the component crates other than `hypershell-hash-components` export `cgp_preset!` + presets of their handlers, such as `HypershellTokioPreset` and `HypershellReqwestPreset`, and + `HypershellPreset` combines them. An application builds its own preset on them to add syntax or + replace a handler, as `http_checksum_native` does to add the checksum handlers. + +### Examples + +The `hypershell-examples` crate, which is not published, holds the programs the release post walks +through, among them [`hello`](/docs/projects/hypershell/examples/hello), +[`hello_name`](/docs/projects/hypershell/examples/hello-name), and +[`http_checksum_native`](/docs/projects/hypershell/examples/http-checksum-native). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the project's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/hypershell/v0-2-0.md b/docs/release-notes/hypershell/v0-2-0.md new file mode 100644 index 00000000..297748f3 --- /dev/null +++ b/docs/release-notes/hypershell/v0-2-0.md @@ -0,0 +1,128 @@ +--- +title: 'Hypershell v0.2.0 release notes' +sidebar_label: 'v0.2.0' +sidebar_position: 99800 +description: 'Hypershell v0.2.0 moves to cgp v0.8.0, assembles its language from a namespace instead of presets, and fixes HTTP, command, and WebSocket defects.' +slug: v0.2.0 +--- + +# Hypershell v0.2.0 + +This page lists what Hypershell v0.2.0 changed. Hypershell is a domain-specific language for +shell-script-like programs, built with [Context-Generic Programming (CGP)](/docs/), a Rust library +whose macros generate traits and their wiring, and this release moves it from `cgp` 0.4.1 onto +[`cgp` v0.8.0](/docs/release-notes/cgp/v0.8.0). + +Released on 2026-11-18. + +- **Crate:** [`hypershell` 0.2.0 on crates.io](https://crates.io/crates/hypershell/0.2.0) +- **Compare:** + [v0.1.0...v0.2.0](https://github.com/contextgeneric/hypershell/compare/v0.1.0...v0.2.0) + +## Summary + +The language is assembled from `HypershellNamespace`, which a context joins with one line, in place +of the `cgp_preset!` presets that `cgp` 0.8.0 removed, and its handlers dispatch on their input type +through path keys. The release fixes buffered HTTP bodies that did not follow redirects, steps that +v0.1.0 left unwired or wired without the promotion they need, and failures that were lost or +panicked. Every published crate now has a README that is also its crate documentation. + +## Compatibility + +- **Minimum Rust version:** 1.90, where v0.1.0 needed 1.87. The library and a small program build + on stable Rust; the repository pins a nightly with the next-generation trait solver for its + largest examples. +- **CGP version:** built on `cgp` 0.8.0, released beside it, where v0.1.0 used `cgp` 0.4.1. A + program's crate depends on `cgp` itself, because the `hypershell!` expansion names it. +- **Crates:** `hypershell`, `hypershell-components`, `hypershell-tokio-components`, + `hypershell-reqwest-components`, `hypershell-json-components`, `hypershell-hash-components`, + `hypershell-tungstenite-components`, and `hypershell-macro`, all at 0.2.0. + +## Upgrading + +1. Move the project from `cgp` 0.4.1 to 0.8.0, following the `Upgrading` sections of the + [v0.5.0](/docs/release-notes/cgp/v0.5.0#upgrading), [v0.6.0](/docs/release-notes/cgp/v0.6.0#upgrading), + [v0.7.0](/docs/release-notes/cgp/v0.7.0#upgrading), and + [v0.8.0](/docs/release-notes/cgp/v0.8.0#upgrading) notes, and depend on `cgp` directly; see + [The `cgp` requirement is 0.8.0](#the-cgp-requirement-is-080). +2. Replace each custom context's `#[cgp_context(MyAppComponents: HypershellPreset)]` with a + `delegate_components!` block holding `namespace HypershellNamespace;`; see + [Presets are replaced by `HypershellNamespace`](#presets-are-replaced-by-hypershellnamespace). +3. Replace each preset that added syntax with a `cgp_namespace!` that inherits `HypershellNamespace` + and keys the new syntax's handlers under `@cgp.extra.handler.HandlerComponent`, and join that + namespace instead; see + [Handlers dispatch on paths](#handlers-dispatch-on-paths). +4. Change every Hypershell crate's requirement to `0.2.0`. + +## Breaking changes + +### The `cgp` requirement is 0.8.0 + +Every Hypershell crate requires `cgp` 0.8.0 where v0.1.0 required 0.4.1, so a project moves across +the breaking changes of `cgp` v0.5.0 to v0.8.0 with this release. Introduced in +[#5](https://github.com/contextgeneric/hypershell/pull/5). + +### Presets are replaced by `HypershellNamespace` + +The `presets` modules of `hypershell` and the five component crates that had one are gone, with +`HypershellPreset` and its re-export from `hypershell::prelude`. `hypershell::namespaces` exports +`HypershellNamespace`, a namespace inheriting CGP's `DefaultNamespace` that wires the whole +language, and each component crate other than `hypershell-hash-components` exports an aggregate +provider of its handlers, such as `HypershellTokioProvider`. `HypershellCli` and `HypershellHttp` +join the namespace, and a custom context does the same with `namespace HypershellNamespace;` in its +`delegate_components!` block. See +[the assembly page](/docs/projects/hypershell/architecture/assembly). Introduced in +[#5](https://github.com/contextgeneric/hypershell/pull/5). + +### Handlers dispatch on paths + +A handler is keyed by a path under `@cgp.extra.handler.HandlerComponent`, with one segment for the +syntax type and, where a step accepts several inputs, one for the input type, in place of the +`UseDelegate` and `UseInputDelegate` tables of v0.1.0. An extension registers its syntax in a +namespace that inherits `HypershellNamespace`, as the `http_checksum_native` example does for +`Checksum` and `BytesToHex`. See +[streams and input dispatch](/docs/projects/hypershell/architecture/streams-and-input-dispatch). +Introduced in [#5](https://github.com/contextgeneric/hypershell/pull/5). + +## New features + +- **`hypershell::prelude`** exports the handler traits and their keys, such as `Handler`, + `HandlerComponent`, and `Computer`, which `cgp` 0.8.0's prelude no longer carries. Introduced in + [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **`BoxHandler`**, in `hypershell-components`, runs a handler with its future boxed, + erasing the future's type. Introduced in + [#1](https://github.com/contextgeneric/hypershell/pull/1). +- **New examples:** `compare_and_branch` and `parallel_compare`, which add `Compare` and `If` + syntax in the unpublished examples crate. + +## Improvements + +- **Crate documentation:** each published crate's README is its crate documentation, so docs.rs and + crates.io show the same page, and `hypershell`'s runs the `hello` program as a doc test. + Introduced in [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **Package metadata:** each crate's `repository` names the Hypershell repository, where v0.1.0 + named `cgp`'s; each crate has a description of its own, a `homepage`, keywords, and categories; + and each package includes the license file. Introduced in + [#5](https://github.com/contextgeneric/hypershell/pull/5). + +## Fixes + +- **A streaming HTTP request with a `Vec` or `String` body** is sent buffered, so `reqwest` + follows a redirect; a streamed body still does not. Introduced in + [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **`PutMethod` and `DeleteMethod`** are wired for HTTP requests, where no v0.1.0 preset wired + either. Introduced in [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **`ConvertTo`** is wired with the promotion from its synchronous handler to an async one, which + v0.1.0's wiring lacked. Introduced in [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **A streamed command that exits with a failure** ends its output with an `io::Error` carrying a + `ChildExitError`, with the exit code and stderr; v0.1.0 never waited for the child, so its stream + ended as though the command had succeeded. Introduced in + [#5](https://github.com/contextgeneric/hypershell/pull/5). +- **A failed WebSocket connection** is raised as an error, where v0.1.0 panicked. Introduced in + [#5](https://github.com/contextgeneric/hypershell/pull/5). + +--- + +*An AI agent wrote this page from the release's source changes and the CGP knowledge base. Its +content was verified against the project's source at the release's tag. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/release-notes/index.md b/docs/release-notes/index.md new file mode 100644 index 00000000..fb5905c1 --- /dev/null +++ b/docs/release-notes/index.md @@ -0,0 +1,60 @@ +--- +title: 'Release notes for cgp, cargo-cgp, cgp-serde, and Hypershell' +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'What each official release of cgp, cargo-cgp, cgp-serde, and Hypershell changed, one dated page per release, with the steps to upgrade to it.' +--- + +# Release notes + +Each page in this section lists what one official release of +[Context-Generic Programming (CGP)](/docs/), a Rust library whose macros generate traits and their +wiring, or of a project built with it, changed for its users, and how a project upgrades to it. A page is dated and kept as it was +published, so it always describes the version it names. + +## The artifacts + +The notes cover four artifacts, which release on their own schedules: + +- **[cgp](/docs/release-notes/cgp):** the library, its facade crate, and the workspace crates + released with it. The newest release is [v0.8.0](/docs/release-notes/cgp/v0.8.0). +- **[cargo-cgp](/docs/release-notes/cargo-cgp):** CGP's error toolchain, which rewrites CGP's + compile errors and prints a crate's macro expansion. The newest release is [v0.1.0](/docs/release-notes/cargo-cgp/v0.1.0). +- **[cgp-serde](/docs/release-notes/cgp-serde):** Serde's `Serialize` and `Deserialize` rebuilt as + CGP components, so each application chooses how a type is encoded. The newest release is + [v0.3.0](/docs/release-notes/cgp-serde/v0.3.0), and the project is documented in + [its Projects pages](/docs/projects/cgp-serde/). +- **[hypershell](/docs/release-notes/hypershell):** a type-level DSL for shell-script-like programs, + written as Rust types and run by handlers that a context chooses. The newest release is + [v0.2.0](/docs/release-notes/hypershell/v0.2.0), and the project is documented in + [its Projects pages](/docs/projects/hypershell/). + +## Versioning + +`cgp` is a 0.x library, and Cargo treats the minor number as the one that may break code: a requirement such as `cgp = "0.7"` accepts every 0.7 release, and a move to the next minor number is a deliberate upgrade. Each minor release from [v0.2.0](/docs/release-notes/cgp/v0.2.0) to [v0.8.0](/docs/release-notes/cgp/v0.8.0) carries breaking changes, which its page lists under *Breaking changes* with the steps to take. + +A patch release is not always compatible either. [v0.4.1](/docs/release-notes/cgp/v0.4.1) and [v0.4.2](/docs/release-notes/cgp/v0.4.2) each changed an item that earlier code used, so a project that accepts patch releases automatically can meet a break there. [v0.3.1](/docs/release-notes/cgp/v0.3.1) raised the minimum Rust version and nothing else, and [v0.6.1](/docs/release-notes/cgp/v0.6.1) changed no existing item. Read the page of a patch release before accepting it. + +cgp-serde and Hypershell number their releases the same way. Each of their releases so far builds +on a newer `cgp` minor release: cgp-serde [v0.1.0](/docs/release-notes/cgp-serde/v0.1.0), +[v0.2.0](/docs/release-notes/cgp-serde/v0.2.0), and [v0.3.0](/docs/release-notes/cgp-serde/v0.3.0) +on `cgp` 0.6, 0.7, and 0.8, and Hypershell [v0.1.0](/docs/release-notes/hypershell/v0.1.0) and +[v0.2.0](/docs/release-notes/hypershell/v0.2.0) on `cgp` 0.4 and 0.8. That move alone breaks code, +because an application must wire a project's components with the `cgp` release the project was +built on, so it upgrades `cgp` and the project together. Neither project has had a patch release. + +## Reading a page + +A page opens with the release's date, its links, and a summary of its main changes. *Compatibility* +gives the minimum Rust version and the versions released beside it, and *Upgrading* gives the +ordered steps for a project moving from the previous release, each linking the breaking change it +carries out. The changes follow, grouped as breaking changes, deprecations, new features, +improvements, fixes, and security fixes, with an empty group left out. + +A release's post on the [blog](/blog) tells the story of its main feature, and its notes page lists +every change. Each links the other. + +--- + +*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/resources.md b/docs/resources.md deleted file mode 100644 index e2020fd6..00000000 --- a/docs/resources.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -sidebar_position: 8 ---- - -# Resources - -This page lists some resources related to CGP. More resources will be added as the project continues to develop. - -## Crates - -- [`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. - -## Tutorials - -- [Hello World Tutorial](/docs/tutorials/hello) -- [Area Calculation Tutorial](/docs/tutorials/area-calculation/) - -## Videos - -### RustLab 2025 Presentation - -

- -

- -[Read the full transcript here](/blog/rustlab-2025-coherence) - -## Books - -- [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/) - The main book for learning CGP and understand various design patterns for CGP. - -## 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. diff --git a/docs/resources/_category_.json b/docs/resources/_category_.json new file mode 100644 index 00000000..63190a03 --- /dev/null +++ b/docs/resources/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Resources", + "position": 11, + "link": { + "type": "doc", + "id": "resources/index" + } +} diff --git a/docs/resources/community.md b/docs/resources/community.md new file mode 100644 index 00000000..19bd7d0b --- /dev/null +++ b/docs/resources/community.md @@ -0,0 +1,45 @@ +--- +title: 'Community around Context-Generic Programming' +sidebar_label: 'Community' +sidebar_position: 2 +description: 'Where to ask questions about Context-Generic Programming, discuss it with other users, and follow news of its development.' +--- + +# Community + +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust. As you +learn it, or use it in your own code, you may run into a question the documentation does not +answer. This page lists where to ask it, where to talk with other users, and where to follow news of +CGP's development. + +## Ask a question or start a discussion + +Each channel suits a different kind of conversation, so pick the one that fits yours: + +- **[Discord server](https://discord.gg/Hgk3rCw6pQ):** quick questions and informal chat, beginner + questions included, while you work through a tutorial or your own code. +- **[GitHub Discussions](https://github.com/orgs/contextgeneric/discussions):** longer threads that + other readers can find later, such as a design question, an idea for CGP, or a suggestion for what + the documentation should cover next. +- **[r/cgp](https://www.reddit.com/r/cgp/):** the subreddit, for public discussion of CGP and of + what people write about it. + +If a page confuses you or contradicts the code, the Contribute page's +[Report a problem](/docs/contribute#report-a-problem) says where to report it. + +## Follow CGP's news + +News of CGP's development appears on Bluesky, at +[@contextgeneric.dev](https://bsky.app/profile/contextgeneric.dev). Release announcements and longer +articles appear on the [blog](/blog), which you can also follow through its +[RSS feed](https://contextgeneric.dev/blog/rss.xml). + +## Help with CGP + +If you want to do more than talk about CGP, [Contribute](/docs/contribute) lists the ways to help, +from reporting a problem to publishing components of your own. + +--- + +*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/resources/index.md b/docs/resources/index.md new file mode 100644 index 00000000..eeebcae4 --- /dev/null +++ b/docs/resources/index.md @@ -0,0 +1,44 @@ +--- +title: 'Resources about Context-Generic Programming' +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'This section collects material about Context-Generic Programming beyond the documentation, from recorded talks to the places where you can discuss it.' +--- + +# Resources + +The rest of this site's documentation explains [Context-Generic Programming (CGP)](/docs/), which +enables pluggable trait implementations in Rust. Sometimes, though, you want to meet CGP another +way: in a talk you can watch, in a conversation with other users, or through the crate's API as +rustdoc shows it. This section gathers that material from outside the documentation, and the places +where people discuss CGP. + +## Videos + +If you would rather watch than read, start with the [Videos](/docs/resources/videos) page. It holds +the RustLab 2025 talk *How to stop fighting with coherence*, which explains why Rust's coherence +rules exist and then shows how CGP works within them. The talk's transcript is on the blog, so you +can also read it at your own pace. + +## Community + +If you have a question, want to talk with other users, or want to follow CGP's news, the +[Community](/docs/resources/community) page says where to go. It covers the Discord server, GitHub +Discussions, the r/cgp subreddit, and CGP's Bluesky account, with what each one is for. + +## API documentation + +When you want the API itself, the `cgp` crate's documentation is on [docs.rs](https://docs.rs/cgp), +which lists its traits and macros. Rustdoc cannot show the code a macro generates, though, so for +what each construct does, the [Reference](/docs/reference) is more complete. + +## More to come + +For now, this section holds videos, the community channels, and the API documentation. More kinds +of resources, such as events, will be added in the future, each on a page of its own, so the links +you find here keep working as the section grows. + +--- + +*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/resources/videos.md b/docs/resources/videos.md new file mode 100644 index 00000000..d50e7bde --- /dev/null +++ b/docs/resources/videos.md @@ -0,0 +1,29 @@ +--- +title: 'Videos about Context-Generic Programming' +sidebar_label: 'Videos' +sidebar_position: 1 +description: "Recorded talks about Context-Generic Programming, starting with the RustLab 2025 talk on how CGP works within Rust's coherence rules." +--- + +# Videos + +Some ideas are easier to follow when someone talks you through them. The talks on this page +introduce [Context-Generic Programming (CGP)](/docs/), which enables pluggable trait +implementations in Rust, and each comes with a note on what it covers and a link to its transcript +where one exists. + +## RustLab 2025: How to stop fighting with coherence + +

+ +

+ +Rust's coherence rules let a trait have only one implementation for any given type, so the +compiler always knows which one to use. The talk explains why the rules exist, then shows how CGP +works within them. If you prefer to read, its [full transcript](/blog/rustlab-2025-coherence) is on +the blog. + +--- + +*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/tooling/_category_.json b/docs/tooling/_category_.json new file mode 100644 index 00000000..d58c47e7 --- /dev/null +++ b/docs/tooling/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Tooling", + "position": 7, + "link": { + "type": "doc", + "id": "tooling/index" + } +} diff --git a/docs/tooling/cargo-cgp/_category_.json b/docs/tooling/cargo-cgp/_category_.json new file mode 100644 index 00000000..582a2ae5 --- /dev/null +++ b/docs/tooling/cargo-cgp/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "cargo-cgp", + "position": 1, + "link": { + "type": "doc", + "id": "tooling/cargo-cgp/index" + } +} diff --git a/docs/tooling/cargo-cgp/check.md b/docs/tooling/cargo-cgp/check.md new file mode 100644 index 00000000..9d13e8f6 --- /dev/null +++ b/docs/tooling/cargo-cgp/check.md @@ -0,0 +1,229 @@ +--- +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 + +When an error in code written with [Context-Generic Programming (CGP)](/docs/) 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), CGP's error toolchain: + +```sh +cargo cgp check +``` + +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 +cargo cgp check --workspace +cargo cgp check -p my-crate +cargo cgp check --all-targets +``` + +## Try it on a deliberate mistake + +A missing context field provides a small example you can try. Create a library package to hold it: + +```sh +cargo new --lib area-demo +cd area-demo +``` + +Then add CGP to its `Cargo.toml`: + +```toml +[dependencies] +cgp = "0.8.0" +``` + +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::*; + +#[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()); +} +``` + +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] missing field `height` on `Rectangle` + --> src/lib.rs:28:30 + | +28 | println!("{}", rectangle.area()); + | ^^^^ + | + = 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` + +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, +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 + +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! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +The check now reports the same cause at the entry that asserted it: + +```text +error[E0277]: [CGP-E001] missing field `height` on `Rectangle` + --> src/lib.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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` + +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 +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` +``` + +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 + +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. +- **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. + +A check also orders its output differently. It prints errors in the order of the code they point +at: by file, then by position, with an error on an expression ahead of one on the expression around +it. The pinned nightly checks your code on several threads, through the +[parallel front end](https://blog.rust-lang.org/2026/11/16/enabling-parallel-frontend-on-nightly/), so it +can find the errors in a different order each time, but a check sorts them first and prints the same +output on every run. `cargo check` prints them in the order the compiler finds them, so the same +error can sit in another place in its output. When one mistake breaks several places, such as a +`check_components!` entry and a call, `cargo cgp check` reports it once, at the +`check_components!` entry if there is one. If a check's output does change between runs, +[Troubleshooting](./troubleshooting.md#a-check-hangs-or-prints-different-output-between-runs) shows +how to run it on one thread. + +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 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 + +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. + +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 + +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 + +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. + +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). + +--- + +*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/tooling/cargo-cgp/command-reference.md b/docs/tooling/cargo-cgp/command-reference.md new file mode 100644 index 00000000..f4dcf9fc --- /dev/null +++ b/docs/tooling/cargo-cgp/command-reference.md @@ -0,0 +1,161 @@ +--- +title: 'cargo-cgp command reference: commands, options, variables' +sidebar_label: 'Command reference' +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.' +--- + +# Command reference + +This page collects the commands, options, environment variables, files, and exit statuses of +[`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 + +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. | +| `-V`, `--version` | Prints the version of the tool, as `cargo-cgp 0.1.0`. | + +## Commands + +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 | +|---|---|---| +| `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 version its release channel allows | [Installation](./installation.md#updating) | + +### `check` + +```sh +cargo cgp check [CARGO CHECK ARGS]... +``` + +`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 `:** 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` + +```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`. | + +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` + +```sh +cargo cgp setup +``` + +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` + +```sh +cargo cgp update +``` + +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 + +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 | +|---|---| +| `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. 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. | + +During `check` and `expand`, the tool passes the following environment to cargo so it uses the +driver and matching compiler libraries: + +| 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, 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. On macOS the tool sets `DYLD_FALLBACK_LIBRARY_PATH` instead, and on Windows it prepends to `PATH`. | + +## Files and directories + +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 | +|---|---| +| `~/.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, inside the project's target directory. | + +## Exit status + +`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 + +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. | + +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. + +--- + +*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/tooling/cargo-cgp/editor-integration.md b/docs/tooling/cargo-cgp/editor-integration.md new file mode 100644 index 00000000..f6f7169f --- /dev/null +++ b/docs/tooling/cargo-cgp/editor-integration.md @@ -0,0 +1,193 @@ +--- +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 + +You can have rust-analyzer run `cargo cgp check` when you save, bringing the rewritten errors of +[Context-Generic Programming (CGP)](/docs/) code 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 and +confirm that `cargo cgp check` works in a terminal inside your project. + +## Set it up + +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 +{ + "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`:** 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 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 + +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. + +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 + +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` +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` +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. +[Reading the output](./reading-output.md) explains each part. + +## Importing a component key + +A provider written in another module than its component imports the component's key beside its +provider trait, as [`#[cgp_impl]`](/docs/reference/macros/cgp_impl#importing-the-component-key) +explains. The header names that key without writing it, so rust-analyzer's own import assist has +nothing to offer on the header. With the override in place, `cargo cgp check` reports the missing key +as [`[CGP-E041]`](./error-codes.md#cgp-e041) on the provider trait's name and attaches the import as +a fix. The quick-fix menu on that name, and on a wiring key that names a component the module does +not import, offers it under the title *import the component*, followed by the `use` line it inserts. +rust-analyzer marks it as the preferred fix when only one path imports the key. +[`[CGP-E070]`](./error-codes.md#cgp-e070)'s fix, which names in the attribute a key the header cannot +derive, appears on the trait's name the same way. + +The plain check behaves differently. The compiler's own import suggestion, when it makes one, appears +as a quick fix only on the module's first `use` line, not on the header, and stable Rust suggests no +import for a component from a library. Two things help under either check. rust-analyzer's import +assist offers to import a key written in the source, such as a wiring entry's key or the key in +`#[cgp_impl(new RectangleArea: AreaCalculatorComponent)]`. And hovering a provider trait in a `use` +line shows its documentation, which names the key a provider imports beside it. + +## What changes when the editor runs the tool + +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 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. + +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"`. + +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. + +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 + +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 + +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))): +error: toolchain `nightly-2026-11-16` is not available: + + error: toolchain 'nightly-2026-11-16-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-11-16-x86_64-unknown-linux-gnu` to install it + +help: run `cargo cgp setup` +``` + +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 +``` + +If the warning instead ends with cargo's `no such command` error, the editor cannot find the tool: + +```text +error: no such command: `cgp` +``` + +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 +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 + +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. + +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. On a crate with providers missing +their keys, the quick-fix menus held the import fixes described above. 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. + +--- + +*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/tooling/cargo-cgp/error-codes.md b/docs/tooling/cargo-cgp/error-codes.md new file mode 100644 index 00000000..511d47eb --- /dev/null +++ b/docs/tooling/cargo-cgp/error-codes.md @@ -0,0 +1,876 @@ +--- +title: 'cargo-cgp error codes: every CGP-E code explained' +sidebar_label: 'Error codes' +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.' +--- + +# Error codes + +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 + +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 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. + +## A trait the context cannot use + +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 + +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` +``` + +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 + +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 `` +``` + +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 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] the trait `` is not implemented for context `` +``` + +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-E004] field `` on `` has type ``, but `` is required +``` + +When the required type is written in terms of an abstract type, the message shows both the written form and what +it resolves to: + +```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. + +### 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-E005] abstract type `` of `` on `` is ``, but `` is required +``` + +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. + +## 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. + +```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. + +```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. + +```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. + +```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. + +```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. +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-E015 + +A `check_components!` table lists one entry twice. + +```text +[CGP-E015] `check_components!` checks `` twice for `` +``` + +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 + +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 `` +``` + +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 + +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. + +```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. + +```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 + +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 `()` +``` + +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. + +### CGP-E061 + +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 `` +``` + +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 +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`. + +```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 + +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 (``, …) +``` + +### CGP-E022 + +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 `` +``` + +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 ownership requirement. + +## 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 +`help` line. + +### CGP-E030 + +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 +``` + +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 + +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 +``` + +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. + +```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 + +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 +``` + +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). + +```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). + +```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 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 +``` + +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. + +```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 + +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 +``` + +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 + +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]` +``` + +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 + +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 + +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 +``` + +Replace the trait with the component marker named by the `help` line. + +### CGP-E041 + +The component exists, but the code that names it cannot see it. A wiring table names it as a key, +as `ErrorTypeProviderComponent`, which needs an explicit import because the prelude does not +export it. A `#[cgp_impl]` or `#[cgp_provider]` header names it too, without writing it: the macro +derives `GreeterComponent` from `impl Greeter`, so a provider in another module imports the key +beside the trait, and the error sits on the trait's name: + +```text +[CGP-E041] the component `` is not in scope +``` + +To fix it, add the `use` line the `help` line gives, which an editor can apply from the trait's +name or the key. A header that names the trait by its path +derives the key through the same path, so one written through a module that re-exports the trait +without its key reads `` the component `` is not in module `` ``; name the trait +through the module the `help` line gives, or re-export the key beside the trait. + +### CGP-E042 + +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 +``` + +To fix it, name the component the `help` line gives. + +### CGP-E043 + +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 +``` + +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 + +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 +``` + +## Extensible data + +### CGP-E050 + +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` +``` + +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. + +## Mistakes in what a macro was given, continued + +### CGP-E070 + +A `#[cgp_impl]` or `#[cgp_provider]` header derives its component from the trait's name as written, +and that name is not the component's. The trait may be imported under another name, so +`use …::Greeter as G;` and `impl G` derive `GComponent`, or the component's `name:` may rename its +key or give it parameters: + +```text +[CGP-E070] the header derives the component `` from the trait name ``, but the component of `` is `` +``` + +To fix it, name the component in the attribute, as the fix under the `help` line does, such as +`#[cgp_impl(new UnitArea: AreaComponent)]` or `#[cgp_provider(GreeterComponent)]`; a key with +parameters takes the header's arguments, as `AreaCalculatorComponent`. When the module does +not import the key, the same fix adds its `use` line, and an editor offers the fix on the trait's +name. When a renamed import sits beside an import of the key, the `note` explains why the +compiler calls that import unused. + +## 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 + +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 `` +``` + +### CGP-E102 + +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 `` +``` + +### 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 + +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. +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. + +```text +[CGP-E110] missing field `` on `` +``` + +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 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 `` +``` + +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 + +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-E112] field `` on `` has type ``, but `` is required +``` + +### CGP-E113 + +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 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 `` +``` + +To fix it, add the entry to that provider's table, or pass it a type the table +covers. + +### CGP-E115 + +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 `` +``` + +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 + +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-E116] abstract type `` of `` on `` is ``, but `` is required +``` + +### CGP-E117 + +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 +``` + +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 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 +``` + +To fix it, drop the second setting. + +### CGP-E119 + +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 +``` + +To fix it, set them first. + +### CGP-E120 + +An enum conversion cannot find a compatible variant, or construction uses a tag absent from +the target enum: + +```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 + +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 +``` + +To fix it, handle the variant. + +### CGP-E122 + +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 +``` + +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. + +```text +[CGP-E123] `` does not implement `` +``` + +To fix it, add the derive the `help` line names. + +### CGP-E124 + +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 +``` + +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. + +```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 + +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 `` +``` + +To fix it, call the method the `help` line names, such as `downcast_fields`. + +### CGP-E127 + +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 `` +``` + +To fix it, wire a provider for those arguments, or change the type that disagrees. + +### CGP-E128 + +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 +``` + +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. + +```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 +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. + +--- + +*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/tooling/cargo-cgp/expand.md b/docs/tooling/cargo-cgp/expand.md new file mode 100644 index 00000000..c35692da --- /dev/null +++ b/docs/tooling/cargo-cgp/expand.md @@ -0,0 +1,261 @@ +--- +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` 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: + +```sh +cargo cgp expand --lib +``` + +## When to use it + +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:** 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 + +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::*; + +#[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 +``` + +```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 + } +} +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; +} +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for Rectangle +where + RectangleArea: IsProviderFor, +{} +impl __CheckRectangle for Rectangle {} +``` + +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` + +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: + +```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::shapes` and `--item shapes` are the same request. + +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. + +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` +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 + +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 +cargo cgp expand --bin my-app +cargo cgp expand -p my-crate --lib +``` + +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 +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 | 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, so for cargo's target-selection options, run `cargo rustc --help`. + +## Why not `cargo-expand` + +[`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. + +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, + ::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` 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, a derived field list reads +[`Struct! { width: f64, height: f64 }`](/docs/reference/macros/struct), and a namespace key reads +`Path!(@app.GreeterComponent)`. + +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 + +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. + +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. + +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 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. + +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. + +--- + +*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/tooling/cargo-cgp/index.md b/docs/tooling/cargo-cgp/index.md new file mode 100644 index 00000000..b67bb9ae --- /dev/null +++ b/docs/tooling/cargo-cgp/index.md @@ -0,0 +1,214 @@ +--- +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` helps you understand compile errors and macro expansions in +[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 +you need help understanding an error or a macro expansion. + +## The problem it solves + +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. + +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::*; + +#[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()); +} +``` + +Plain `cargo check` on stable Rust reports the call to `area`: + +```text +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 + | + 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 + | + 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`. +``` + +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: + +```text +error[E0599]: [CGP-E001] missing field `height` on `Rectangle` + --> src/lib.rs:28:30 + | +28 | println!("{}", rectangle.area()); + | ^^^^ + | + = 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` + +For more information about this error, try `rustc --explain E0599`. +``` + +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 + +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 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 + +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. + +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 + +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. + +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. + +[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 + +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. + +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. + +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) 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. + +## Where to go next + +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): 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. +- [Error codes](./error-codes.md) and [Command reference](./command-reference.md): to look something + up. + +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, 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/tooling/cargo-cgp/installation.md b/docs/tooling/cargo-cgp/installation.md new file mode 100644 index 00000000..126eb109 --- /dev/null +++ b/docs/tooling/cargo-cgp/installation.md @@ -0,0 +1,228 @@ +--- +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 + +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. +Setup chooses that nightly for you. It is used for the tool's checks without changing your +project's toolchain. + +## Which path to use + +Match what your machine already has to the path for it: + +| You have | Use | What it does | +|---|---|---| +| 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 + +Install the front end, then let it prepare the matching driver and nightly: + +```sh +cargo install --locked cargo-cgp +cargo cgp setup +``` + +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. + +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. + +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. + +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 + +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 +``` + +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: + +```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 installing anything, run the flake's default app from that +project's directory. Everything after `--` is passed to the tool, so this runs `cargo cgp check`: + +```sh +cd /path/to/your/project +nix run github:contextgeneric/cargo-cgp/v0.1.0 -- check +``` + +## Neither rustup nor Nix + +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 + +To confirm the front end is in place, ask it for its version: + +```sh +cargo cgp --version +``` + +```text +cargo-cgp 0.1.0 +``` + +`cargo cgp --help` prints the same line first, followed by the list of commands. + +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 +``` + +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 +``` + +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, the driver prints three lines: + +```text +cargo-cgp-driver 0.1.0 +pinned-toolchain: nightly-2026-11-16 +built-against-rustc: rustc 1.102.0-nightly (5f4effd57 2026-11-13) +``` + +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. + +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 + +On the cargo path, one command updates the tool: + +```sh +cargo cgp update +``` + +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 + +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. + +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 + +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 +``` + +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 +``` + +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 + +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 +git clone https://github.com/contextgeneric/cargo-cgp +cd cargo-cgp +cargo build +``` + +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 \ + CARGO_CGP_DRIVER=/path/to/cargo-cgp/target/debug/cargo-cgp-driver \ + /path/to/cargo-cgp/target/debug/cargo-cgp check +``` + +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. + +## 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. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/tooling/cargo-cgp/reading-output.md b/docs/tooling/cargo-cgp/reading-output.md new file mode 100644 index 00000000..ca1df7f0 --- /dev/null +++ b/docs/tooling/cargo-cgp/reading-output.md @@ -0,0 +1,380 @@ +--- +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 + +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 + +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] missing field `height` on `Rectangle` + --> src/lib.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = 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` + +For more information about this error, try `rustc --explain E0277`. +``` + +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` + still applies. +- **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. + +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 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 + +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)] +pub struct Rectangle { + pub length: f64, +} +``` + +```text +error[E0277]: [CGP-E001] missing fields `width` and `height` on `Rectangle` + --> src/lib.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root causes: + - [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-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`. +``` + +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. + +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 + +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! { + App { + GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, + FarewellComponent, + } +} +``` + +```text +error[E0277]: [CGP-E001] missing wiring for `FarewellComponent` on `App` + --> src/lib.rs:31:9 + | +31 | 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-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`. +``` + +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 + +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)] +pub struct Rectangle { + pub width: f64, + pub height: u32, +} +``` + +```text +error[E0271]: [CGP-E004] field `height` on `Rectangle` has type `u32`, but `f64` is required + --> 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-E112] field `height` on `Rectangle` has type `u32`, but `f64` is required + +For more information about this error, try `rustc --explain E0271`. +``` + +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 + +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)] +#[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` + └─ [CGP-E117] the trait bound `f64: Eq` is not satisfied + +For more information about this error, try `rustc --explain E0277`. +``` + +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 +``` + +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 + +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! { + App { + GreeterComponent: GreetHello, + GreeterComponent: GreetGoodbye, + } +} +``` + +```text +error[E0119]: [CGP-E010] conflicting wiring: `App` wires component `GreeterComponent` twice + --> 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`. +``` + +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 + +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] +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-E030] 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`. +``` + +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-E039]` similarly +identify a mistake in a macro's input and offer a specific correction. + +Some fixes go one step further and come as an edit the tool attaches to the error. A provider whose +module imports its provider trait but not the trait's component key is one case: + +```rust +mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } +} + +mod providers { + use cgp::prelude::*; + + use crate::components::AreaCalculator; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } +} +``` + +```text +error[E0425]: [CGP-E041] the component `AreaCalculatorComponent` is not in scope + --> src/main.rs:16:10 + | +16 | impl AreaCalculator { + | ^^^^^^^^^^^^^^ + | +help: import the component + | +11 + use crate::components::AreaCalculatorComponent; + | +``` + +The `help` shows the line it would insert, marked `+`, rather than describing it. Because the edit +travels with the error, an editor running `cargo cgp check` offers it as a quick fix on the trait's +name, as [Editor integration](./editor-integration.md#importing-a-component-key) describes. +[`[CGP-E070]`](./error-codes.md#cgp-e070)'s fix, which names a component in the provider's attribute, +works the same way. + +## 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: + +- **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:** 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). +- **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. + +--- + +*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/tooling/cargo-cgp/troubleshooting.md b/docs/tooling/cargo-cgp/troubleshooting.md new file mode 100644 index 00000000..e8a990cc --- /dev/null +++ b/docs/tooling/cargo-cgp/troubleshooting.md @@ -0,0 +1,328 @@ +--- +title: 'Troubleshooting cargo-cgp' +sidebar_label: 'Troubleshooting' +sidebar_position: 7 +description: 'Match a cargo-cgp error to its cause and fix: the setup check, a driver that will not load or cannot be found, wrong invocations, and slow or varying checks.' +--- + +# Troubleshooting + +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 +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 + +Find the distinctive part of your error in the left column, then read the section it points to. + +| Error fragment | Cause | Section | +|---|---|---| +| `toolchain … is not available` | the pinned nightly is not installed | [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) | +| `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` | 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) | +| `` 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) | +| `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) | +| no error: a check never finishes, or its errors change between runs | a bug under the compiler's parallel front end | [A check hangs or prints different output between runs](#a-check-hangs-or-prints-different-output-between-runs) | + +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 + +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: + +```sh +cargo cgp check -v +``` + +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 + +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 examples name `nightly-2026-11-16`; 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-11-16` is not available: + + error: toolchain 'nightly-2026-11-16-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-11-16-x86_64-unknown-linux-gnu` to install it + +help: run `cargo cgp setup` +``` + +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 +error: rustup was not found on PATH, and cargo-cgp installs and selects its toolchain `nightly-2026-11-16` through rustup + +help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup +``` + +The [Nix flake](./installation.md#with-nix) runs the front end without the preflight. + +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-11-16` (it was likely built against a different nightly): + + /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` +``` + +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) + +help: run `cargo cgp setup` +``` + +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-11-16` provides `rustc 1.102.0-nightly (5f4effd57 2026-11-13)` + +help: run `cargo cgp setup` +``` + +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) + +help: run `cargo cgp setup` +``` + +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 + +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-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 +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. + +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 +``` + +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. + +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) +--- stderr +…/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 +the active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the Nix flake also handles it. + +## The driver cannot be found + +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) + +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: + +```text +error: could not execute process `/path/to/cargo-cgp-driver …/stable-…/bin/rustc -vV` (never executed) + +Caused by: + No such file or directory (os error 2) +``` + +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 + +Some failures happen before the driver is involved. An unknown command is reported with the list the tool accepts: + +```text +error: no such command: `frobnicate` + +help: the commands are `check`, `expand`, `setup`, and `update` +``` + +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` +``` + +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 +``` + +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 + Installing toolchain `nightly-2026-11-16` with rustc-dev and llvm-tools +error: rustup was not found on PATH, and `cargo cgp setup` installs the toolchain `nightly-2026-11-16` through rustup + +help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup +``` + +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` + +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 + +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 + +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 +``` + +A wrapper given through `RUSTC_WRAPPER`, such as `sccache`, does keep running alongside the driver. + +## A check hangs or prints different output between runs + +The pinned nightly checks your code on several threads by default. The Rust project calls this the +parallel front end and explains it in +[Enabling the parallel frontend on nightly](https://blog.rust-lang.org/2026/11/16/enabling-parallel-frontend-on-nightly/). +A check is meant to print the same output on every run, however many threads the compiler uses, so +a check that never finishes, or that prints different errors from one run to the next, may have met +a bug in that parallel code. You can rule it out by running the check on one thread: + +```sh +RUSTFLAGS="-Zunstable-options --jobs-frontend=1" cargo cgp check +``` + +The tool passes these flags to the compiler unchanged. Set them in the environment, as here, rather +than in your project's `.cargo/config.toml`: a setting there also reaches your ordinary builds, and +stable Rust rejects `-Z` flags. Because cargo rebuilds whenever `RUSTFLAGS` changes, the first check +with the flags recompiles your dependencies, and later checks reuse that build. + +One difference is expected, so look for it before reporting anything. The compiler can describe a +cycle error from a different starting point on each run, and a check keeps that error as the +compiler wrote it. + +If the problem goes away on one thread, the next question is whether the compiler has it too. +Run plain `cargo +nightly-YYYY-MM-DD check` without the flags, using the pinned nightly that the +driver's `--version` names, [run as shown above](#the-driver-cannot-load-the-compiler). If that check also +hangs or crashes, the bug is in the compiler, and the blog post says where to report it. If it does +not, please report the problem on the +[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues) with the output of both runs of +`cargo cgp check`. A plain check that lists its errors in a different order on each run is no sign +of a bug: the post describes that as expected under the parallel front end. + +## Still stuck + +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`, +`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, 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/tooling/index.md b/docs/tooling/index.md new file mode 100644 index 00000000..de1ec5f3 --- /dev/null +++ b/docs/tooling/index.md @@ -0,0 +1,38 @@ +--- +title: 'Tooling for Context-Generic Programming' +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'These pages cover the optional programs you run beside the cgp library, starting with cargo-cgp for reading CGP compile errors and macro expansions.' +--- + +# Tooling + +[Context-Generic Programming (CGP)](/docs/) is a Rust library, so the cargo commands you already +use build, check, and test CGP code as they do any other Rust code. Now and then, though, you need +more than those commands give you. CGP's macros generate ordinary Rust traits, so a compile error +may name that generated code while leaving the failed requirement unclear, or you may want to read +the code a macro produced. The programs in this section help at those moments. None of them is +required, because CGP compiles on stable Rust without them. + +## cargo-cgp + +[`cargo-cgp`](/docs/tooling/cargo-cgp) helps with both. When an error is hard to read, run +`cargo cgp check` in place of `cargo check`. `cargo cgp check` leads with the root cause for the +classes it recognizes, and the tool does not yet reshape every class. When you want to see the code +behind a macro, [`cargo cgp expand`](/docs/tooling/cargo-cgp/expand) prints the Rust that CGP's macros +generate. + +To start using it, follow the [installation guide](/docs/tooling/cargo-cgp/installation), then try it on a +project with [the check page](/docs/tooling/cargo-cgp/check). Once the tool reports an error, +[reading the output](/docs/tooling/cargo-cgp/reading-output) explains each part of it, and +[the error-codes page](/docs/tooling/cargo-cgp/error-codes) explains each code it prints. + +## More tools to come + +For now, `cargo-cgp` is the only program in this section. More tooling for CGP will be added here +in the future. + +--- + +*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/tutorials/_category_.json b/docs/tutorials/_category_.json index 9a4cef89..e899f5c3 100644 --- a/docs/tutorials/_category_.json +++ b/docs/tutorials/_category_.json @@ -1,7 +1,8 @@ { "label": "Tutorials", - "position": 3, + "position": 4, "link": { - "type": "generated-index" + "type": "generated-index", + "description": "Guided walkthroughs that build working Context-Generic Programming (CGP) programs, from a first greeting to choosing an application's storage backend and debugging a wiring mistake." } } diff --git a/docs/tutorials/area-calculation/checking.md b/docs/tutorials/area-calculation/checking.md new file mode 100644 index 00000000..7b014962 --- /dev/null +++ b/docs/tutorials/area-calculation/checking.md @@ -0,0 +1,250 @@ +--- +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.' +--- + +# 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. +[Context-Generic Programming](/docs/) (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 --locked cargo-cgp +cargo cgp setup +``` + +The [installation page](/docs/tooling/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] missing fields `width` and `height` on `PlainCircle` + --> src/main.rs:61:9 + | +61 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root causes: + - [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-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 +fields `width` and `height`. The tree beneath shows how the requirement arrived — through +`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 +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 tree 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. + +To see the same constructs at work in a program rather than on a shape, +[Swap a Storage Backend per Application](/docs/tutorials/storage-backend) builds an application +context, gives its tests their own storage backend, and checks both wirings. + +--- + +*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/context-generic-functions.md b/docs/tutorials/area-calculation/context-generic-functions.md index 8c574d79..f4eb8ba8 100644 --- a/docs/tutorials/area-calculation/context-generic-functions.md +++ b/docs/tutorials/area-calculation/context-generic-functions.md @@ -1,16 +1,19 @@ --- +title: 'Context-generic functions: read fields as arguments' +sidebar_label: 'Context-Generic Functions' sidebar_position: 1 +description: 'Use #[cgp_fn] and #[implicit] to turn plain Rust functions into ones that read their arguments from the fields of any struct that has them.' --- # Context-Generic Functions -In the previous part of this tutorial, we identified two problems with plain Rust code: explicit function parameters accumulate quickly as call chains grow longer, and grouping fields into a concrete context struct creates tight coupling between implementations and a specific type. In this tutorial, we will address both of these problems at once using `#[cgp_fn]` — CGP's mechanism for defining functions that accept **implicit arguments** extracted automatically from any conforming context. +In the previous part of this tutorial, we identified two problems with plain Rust code: explicit function parameters accumulate quickly as call chains grow longer, and grouping fields into a concrete context struct creates tight coupling between implementations and a specific type. In this tutorial, we will address both of these problems at once using `#[cgp_fn]` — the mechanism [Context-Generic Programming](/docs/) (CGP) provides for defining functions that accept **implicit arguments** extracted automatically from any conforming context. By the end of this tutorial, we will have defined `rectangle_area`, `scaled_rectangle_area`, and `print_rectangle_area` as context-generic functions, and seen how `#[cgp_fn]` and `#[implicit]` arguments work together to let a single function definition run cleanly on any context that contains the required fields — without any manual forwarding or boilerplate. ## 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] @@ -41,7 +44,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 +73,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: @@ -179,7 +182,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. @@ -189,7 +192,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: @@ -222,7 +225,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 +284,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 +294,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..e17bb487 100644 --- a/docs/tutorials/area-calculation/index.md +++ b/docs/tutorials/area-calculation/index.md @@ -1,6 +1,12 @@ +--- +title: 'Area calculation: from plain Rust functions to providers' +sidebar_label: 'Area Calculation Tutorial' +description: 'A Rust tutorial series that grows an area calculation from plain functions to context-generic functions, providers, and checked wiring.' +--- + # Area Calculation Tutorial -In this tutorial series, we will explore CGP — Context-Generic Programming — through a concrete, hands-on example: computing the area of different shapes. We will start with familiar plain Rust code, identify its limitations, and progressively introduce the CGP tools that address them. No prior knowledge of CGP is required, though a basic familiarity with Rust traits will be helpful. +In this tutorial series, we will explore [Context-Generic Programming](/docs/) (CGP) through a concrete, hands-on example: computing the area of different shapes. We will start with familiar plain Rust code, identify its limitations, and progressively introduce the CGP tools that address them. No prior knowledge of CGP is required, though a basic familiarity with Rust traits will be helpful. ## Plain Functions and Explicit Dependencies @@ -83,4 +89,9 @@ 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. + +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 2795fd65..b8d95c01 100644 --- a/docs/tutorials/area-calculation/static-dispatch.md +++ b/docs/tutorials/area-calculation/static-dispatch.md @@ -1,12 +1,15 @@ --- +title: 'Static dispatch: give one trait several implementations' +sidebar_label: 'Static Dispatch' sidebar_position: 2 +description: 'Hit the coherence error that rejects two blanket impls of one trait, then fix it with components, named providers, wiring, and higher-order providers.' --- # Static Dispatch 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 the `#[cgp_component]` macro of [Context-Generic Programming](/docs/) (CGP) 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 @@ -234,7 +237,7 @@ impl AreaCalculator { } ``` -When we write blanket implementations that are generic over the context type, we can omit the generic parameter and just refer to the generic context as `Self`. +When we write blanket implementations that are generic over the context type, we can omit the generic parameter and just refer to the generic context as `Self`. This shorter form, with `#[uses]` in place of the `where` clause, is the one to write in your own code; the longer form above shows what it stands for. `#[cgp_impl]` also supports the same shorthand as `#[cgp_fn]`, so we can use `#[uses]` to import the CGP functions `RectangleArea` and `CircleArea` to be used in our implementations. @@ -607,7 +610,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 +618,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/docs/tutorials/hello.md b/docs/tutorials/hello.md index 109905ec..0a715c4e 100644 --- a/docs/tutorials/hello.md +++ b/docs/tutorials/hello.md @@ -1,17 +1,20 @@ --- +title: 'Hello World: one function for many structs' +sidebar_label: 'Hello World Tutorial' sidebar_position: 2 +description: 'Write your first Context-Generic Programming code in Rust: a greet function that reads a name from a field and works on two different structs.' --- # Hello World Tutorial -In this tutorial, we will build a small working program that greets people by name, using CGP's core features. Along the way we will encounter CGP functions, implicit arguments, struct-based contexts, and `HasField` derivation. By the end you will have seen a complete working example and will understand at a high level how CGP leverages Rust's trait system to let you write highly reusable code without any runtime overhead. +In this tutorial, we will build a small working program that greets people by name, using the core features of [Context-Generic Programming](/docs/) (CGP). Along the way we will encounter CGP functions, implicit arguments, struct-based contexts, and `HasField` derivation. By the end you will have seen a complete working example and will understand at a high level how CGP leverages Rust's trait system to let you write highly reusable code without any runtime overhead. ## Using the `cgp` crate 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 @@ -50,7 +53,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: @@ -113,7 +116,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: @@ -136,7 +139,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: @@ -158,7 +161,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. @@ -170,7 +173,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/docs/tutorials/storage-backend.md b/docs/tutorials/storage-backend.md new file mode 100644 index 00000000..0975258f --- /dev/null +++ b/docs/tutorials/storage-backend.md @@ -0,0 +1,410 @@ +--- +title: 'Swap a Storage Backend per Application' +sidebar_label: 'Swap a Storage Backend' +sidebar_position: 3 +description: 'A Rust tutorial: a profile-picture lookup that reads from a folder in the app and from memory in tests, each choice wired and checked at compile time.' +--- + +# Swap a Storage Backend per Application + +Most applications reach a point where one operation needs a different backend in different +places. A deployment reads its files from disk, for example, while its tests would rather not touch +the disk at all. [Context-Generic Programming](/docs/) (CGP) is a library for that kind of choice. +It enables pluggable trait implementations in Rust, so each application type can choose, at compile +time, which implementation it uses. + +In this tutorial, we will build a working profile-picture lookup and link out to the details as we +go. By the end, one lookup function will read pictures from a folder in the application and from +memory in a test, and the compiler will check that each choice is complete. The tutorial assumes +you know Rust, including async functions, and can add a dependency. It assumes no CGP, though the +[Hello World tutorial](/docs/tutorials/hello) is a shorter first look at the same starting point. + +## Set up the project + +Start a new binary project with `cargo new profile-pictures`, then add three dependencies to its +`Cargo.toml`: `cgp` itself, `anyhow` for errors, and `tokio`, because the lookup is async and reads +files through Tokio: + +```toml title="Cargo.toml" +[dependencies] +cgp = "0.8.0" +anyhow = "1" +tokio = { version = "1", features = ["fs", "macros", "rt-multi-thread"] } +``` + +Every module that uses CGP imports its prelude. The program fits in one file, so these imports go +at the top of `src/main.rs`: + +```rust title="src/main.rs" +use std::collections::HashMap; +use std::path::Path; + +use anyhow::anyhow; +use cgp::prelude::*; +``` + +## The application context + +The lookup needs two pieces of data: a table of users, and somewhere to keep their pictures. Each +user may have a picture, stored under an object ID: + +```rust +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct UserId(pub u64); + +#[derive(Clone)] +pub struct User { + pub name: String, + pub profile_picture_object_id: Option, +} +``` + +The application itself is a struct called `App`. CGP calls a type like this a **context**: a type +that stands for this application, which is where its choices live. A context can be an empty +struct, but this one has fields that hold the values its operations need. Its `database` is a +`HashMap` standing in for a real database, so the tutorial runs without a server, and its +`local_dir` names the folder that holds the pictures: + +```rust +#[derive(HasField)] +pub struct App { + pub database: HashMap, + pub local_dir: String, +} +``` + +The `#[derive(HasField)]` line lets CGP code read those fields by name, and the next step relies on +it. + +## Read the application's data with functions + +The lookup has two steps: find the user, then load the picture. We write each one as a function +marked `#[cgp_fn]`, and mark the arguments that should come from the application's fields with +`#[implicit]`: + +```rust +#[cgp_fn] +#[async_trait] +pub async fn get_user( + &self, + #[implicit] database: &HashMap, + user_id: &UserId, +) -> anyhow::Result { + database + .get(user_id) + .cloned() + .ok_or_else(|| anyhow!("no user with ID {}", user_id.0)) +} + +#[cgp_fn] +#[async_trait] +pub async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, +) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) +} +``` + +Notice that callers never pass `database` or `local_dir`. `#[cgp_fn]` turns each function into a +method on any type whose fields match the implicit arguments by name and type, so `App` gains +`get_user` and `fetch_storage_object` without an `impl` block of its own. The match allows a +borrowed form, too: the `local_dir` argument is a `&str`, and it reads `App`'s `String` field. + +Both functions are async, so each also carries `#[async_trait]`. Without it, Rust would warn about +the `async fn` in the public trait that `#[cgp_fn]` generates. + +To try them, `main` writes a picture into a `pictures` folder, builds an `App` with one user, and +calls both methods: + +```rust +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tokio::fs::create_dir_all("pictures").await?; + tokio::fs::write("pictures/alice.png", b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: "pictures".to_owned(), + }; + + let user = app.get_user(&UserId(1)).await?; + let picture = app.fetch_storage_object("alice.png").await?; + println!("{} has a {}-byte picture", user.name, picture.len()); + + Ok(()) +} +``` + +Running `cargo run` prints `Alice has a 16-byte picture`. The bytes are not a real image, but the +program never decodes them, so any bytes will do. + +## Combine the steps + +The two steps belong together, so the next function calls both. Because `get_user` and +`fetch_storage_object` are now methods, the new function calls them on `self`, and declares that it +needs them with `#[uses]`: + +```rust +#[cgp_fn] +#[async_trait] +#[uses(GetUser, FetchStorageObject)] +pub async fn get_user_profile_picture( + &self, + user_id: &UserId, +) -> anyhow::Result>> { + let user = self.get_user(user_id).await?; + + match user.profile_picture_object_id { + Some(object_id) => Ok(Some(self.fetch_storage_object(&object_id).await?)), + None => Ok(None), + } +} +``` + +The names in `#[uses(GetUser, FetchStorageObject)]` are the traits `#[cgp_fn]` generated from the +two functions: a function called `get_user` becomes a trait called `GetUser`. Declaring them there, +rather than as bounds in the signature, keeps the function's interface to a user ID alone. It also +means that `get_user_profile_picture` exists only on a type that has every field both steps read. A +context with a `database` but no `local_dir` would still have `get_user`, but a call to +`get_user_profile_picture` on it would fail to compile. + +Replace the last lines of `main`, from `let user` onwards, with a call to the combined function: + +```rust + match app.get_user_profile_picture(&UserId(1)).await? { + Some(picture) => println!("Found a {}-byte picture", picture.len()), + None => println!("No picture"), + } + + Ok(()) +} +``` + +`cargo run` now prints `Found a 16-byte picture`. + +## Add a backend for tests + +So far there is one way to fetch a picture, and it reads the disk. A test of +`get_user_profile_picture` should keep its pictures in memory instead, which needs a second way to +fetch them, chosen by the test's own context. But a `#[cgp_fn]` function has exactly one +implementation, so the storage step needs something that can have several. + +That something is a CGP **component**. We replace the `fetch_storage_object` function with a +trait marked `#[cgp_component]`: + +```rust +#[async_trait] +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} +``` + +Code calls `CanFetchStorageObject` as an ordinary trait, while `StorageObjectFetcher` names the +trait each implementation targets. An implementation is called a **provider**, and we write one +with `#[cgp_impl]`, giving it a name. The disk-reading provider, `FetchLocalObject`, takes over the +old function's body and still reads `local_dir` as an implicit argument: + +```rust +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) + } +} +``` + +The combined function now depends on the component rather than on the removed function, so its +`#[uses]` names the trait that callers use: + +```rust +#[cgp_fn] +#[async_trait] +#[uses(GetUser, CanFetchStorageObject)] +pub async fn get_user_profile_picture( + &self, + user_id: &UserId, +) -> anyhow::Result>> { + let user = self.get_user(user_id).await?; + + match user.profile_picture_object_id { + Some(object_id) => Ok(Some(self.fetch_storage_object(&object_id).await?)), + None => Ok(None), + } +} +``` + +A provider does nothing until a context chooses it. `App` makes its choice with +`delegate_components!`, which works like a lookup table from each component to the provider that +implements it for this context: + +```rust +delegate_components! { + App { + StorageObjectFetcherComponent: FetchLocalObject, + } +} +``` + +The key, `StorageObjectFetcherComponent`, is a name `#[cgp_component]` generates for the +component. Rust resolves the table at compile time, so `app.fetch_storage_object(...)` becomes a +direct call to `FetchLocalObject`, without a runtime lookup. `cargo run` prints the same line as +before. + +Now for the test. Its context, `TestApp`, has the same `database` field and keeps its pictures in an +`objects` map instead of a folder. A second provider, `FetchMemoryObject`, reads that map, and +`TestApp` chooses it in its own table. All of this goes in a test module at the end of +`src/main.rs`: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[derive(HasField)] + pub struct TestApp { + pub database: HashMap, + pub objects: HashMap>, + } + + #[cgp_impl(new FetchMemoryObject)] + impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] objects: &HashMap>, + object_id: &str, + ) -> anyhow::Result> { + objects + .get(object_id) + .cloned() + .ok_or_else(|| anyhow!("no object named {object_id}")) + } + } + + delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchMemoryObject, + } + } + + #[tokio::test] + async fn fetches_the_picture_from_memory() -> anyhow::Result<()> { + let app = TestApp { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + objects: HashMap::from([("alice.png".to_owned(), b"fake image".to_vec())]), + }; + + let picture = app.get_user_profile_picture(&UserId(1)).await?; + assert_eq!(picture, Some(b"fake image".to_vec())); + + Ok(()) + } +} +``` + +Run `cargo test`, and the test passes without touching the disk. Neither +`get_user_profile_picture` nor `get_user` changed to make that possible. Each context chose its +storage backend in one line of its table, and the same lookup ran against a folder in the +application and against memory in the test. Adding a third backend, such as a cloud bucket, would +be one more provider and one more table entry. The [Overview](/docs/overview) shows providers for +Amazon S3 and Google Cloud Storage, written against a synchronous version of this component. + +## Check the wiring + +Wiring is lazy: adding a table entry does not check that the context has what the provider needs. +The check happens when the component is used, and if something is missing, the error points at the +place it was used, which may be far from the table that caused it. CGP's `check_components!` moves +that check next to the table, so add one for each context, `App`'s after its table and `TestApp`'s +inside the test module: + +```rust +check_components! { + App { + StorageObjectFetcherComponent, + } +} +``` + +```rust + check_components! { + TestApp { + StorageObjectFetcherComponent, + } + } +``` + +To see what the check catches, delete the `local_dir` field from `App`, along with the line in +`main` that sets it. `FetchLocalObject` still needs the field, so `cargo check` now fails at the +check. The compiler's message is long, and it spells the missing field's name as a nested type. +Shortened, it begins like this: + +```text +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied +... +help: the trait `HasField>>>>>>>>>>` is not implemented for `App` +``` + +[cargo-cgp](/docs/tooling/cargo-cgp), CGP's error toolchain, explains the same failure more +directly. After [installing it](/docs/tooling/cargo-cgp/installation), run `cargo cgp check` in +place of `cargo check`. It names the missing field first, then the chain of requirements that led to +it. The compiler reports the mistake twice, at the check and again at the call to +`get_user_profile_picture` in `main`, and `cargo cgp check` shows it once, keeping the check's +report. Here it is, without the source excerpt that points at the check: + +```text +error[E0277]: [CGP-E001] missing field `local_dir` on `App` + = note: root cause: [CGP-E110] missing field `local_dir` on `App` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanFetchStorageObject` for context `App` + └─ [CGP-E102] provider trait impl `StorageObjectFetcher` with context `App` for provider `FetchLocalObject` + └─ [CGP-E110] missing field `local_dir` on `App` + = help: add the field `local_dir` to `App` +``` + +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not +yet reshape every class. Put the field back, and both checks pass. + +## Where to go next + +You now have a lookup whose storage backend each application chooses, checked at compile time. To +go further: + +- **See how each construct is built:** the [area-calculation tutorials](/docs/tutorials/area-calculation) + derive `#[cgp_fn]`, components, providers, and wiring step by step from plain Rust, and end with + a longer look at checking. +- **Understand the mechanism:** [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) + explains how a call reaches the chosen provider, and + [Implicit arguments](/docs/concepts/implicit-arguments) how fields become arguments. +- **Let each context choose its error type too:** the Overview's + [Abstract Over Every Dependency](/docs/overview#abstract-over-every-dependency) replaces + `anyhow::Result` in a synchronous version of this component. +- **Write generic code over structs and enums:** for framework and library authors, + [Extensible records](/docs/concepts/extensible-records) and + [Extensible variants](/docs/concepts/extensible-variants) show code that works over any type's + fields or variants. + +--- + +*An AI agent wrote this page using the CGP knowledge base, and its examples were verified by +compiling them. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 50bc1d27..b24073cc 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -1,14 +1,56 @@ -import {themes as prismThemes} from 'prism-react-renderer'; +import {lightTheme as prismLight, darkTheme as prismDark} from './src/prism/themes'; import type {Config} from '@docusaurus/types'; import type * as Preset from '@docusaurus/preset-classic'; // This runs in Node.js - Don't use client-side code here (browser APIs, JSX...) +// The site's fonts, declared here rather than in src/css/custom.css: a url() in that stylesheet is +// copied to a hashed file name, which the preload below could not name, so the browser would fetch +// the preloaded file and then the hashed one. These rules name the files under static/fonts/. +const FONT_FACES = [ + ['Inter', '/fonts/inter/inter-latin.woff2', 'normal'], + ['Inter', '/fonts/inter/inter-latin-italic.woff2', 'italic'], + ['JetBrains Mono', '/fonts/jetbrains-mono/jetbrains-mono-latin.woff2', 'normal'], +] + .map( + ([family, url, style]) => + `@font-face{font-family:'${family}';src:url('${url}') format('woff2');font-weight:400 700;font-style:${style};font-display:swap}`, + ) + .join(''); + const config: Config = { - title: 'Context-Generic Programming', - tagline: 'Modular programming paradigm for Rust', + title: 'CGP — Context-Generic Programming', + tagline: 'A language extension for Rust, with pluggable trait implementations at compile-time', favicon: 'img/favicon.png', + // The upright Inter face is preloaded, because every page's text and titles use it. The SVG favicon switches to a + // lighter red on a dark browser tab; the PNG stays as the fallback. + // The theme-color tags match a phone's address bar to the navbar, using the values of `--cgp-bg` + // in src/css/custom.css. Both follow the operating system's colour scheme, which is also the site's + // default. + headTags: [ + {tagName: 'style', attributes: {}, innerHTML: FONT_FACES}, + {tagName: 'link', attributes: {rel: 'icon', type: 'image/svg+xml', href: '/img/favicon.svg'}}, + { + tagName: 'link', + attributes: { + rel: 'preload', + href: '/fonts/inter/inter-latin.woff2', + as: 'font', + type: 'font/woff2', + crossorigin: 'anonymous', + }, + }, + { + tagName: 'meta', + attributes: {name: 'theme-color', media: '(prefers-color-scheme: light)', content: '#fdfaf7'}, + }, + { + tagName: 'meta', + attributes: {name: 'theme-color', media: '(prefers-color-scheme: dark)', content: '#0e0c0c'}, + }, + ], + // Future flags, see https://docusaurus.io/docs/api/docusaurus-config#future future: { v4: true, // Improve compatibility with the upcoming Docusaurus v4 @@ -26,6 +68,18 @@ 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 + // `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 @@ -35,6 +89,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 +112,12 @@ const config: Config = { docs: { showLastUpdateTime: true, sidebarPath: './sidebars.ts', + // The `cgp-skills` submodule is checked out at the repository root, and + // each skill's pages under `docs/ai/skills//` are symlinks into it. + // 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: @@ -74,16 +150,17 @@ const config: Config = { ], themeConfig: { - image: 'img/cgp-logo.png', + image: 'img/social-card.jpg', colorMode: { respectPrefersColorScheme: true, }, announcementBar: { id: 'announcement', content: - '🚀 New Release: Supercharge Rust functions with implicit arguments using CGP v0.7.0 🚀', - backgroundColor: '#fcefe1', - textColor: '#5D0705', + '🚀 New Release: Group components with namespaces and paths in CGP v0.8.0 🚀', + // The bar's colours follow the theme through the tokens in src/css/custom.css. + backgroundColor: 'var(--cgp-announce-bg)', + textColor: 'var(--cgp-announce-text)', isCloseable: true, }, navbar: { @@ -91,6 +168,9 @@ const config: Config = { logo: { alt: 'Context-Generic Programming Logo', src: 'img/cgp-logo.svg', + // The logo's red reaches only about 2:1 on the dark navbar, so the dark theme shows a lighter + // tint. + srcDark: 'img/cgp-logo-dark.svg', }, items: [ {to: '/docs/tutorials/hello', label: 'Tutorials', position: 'left'}, @@ -114,6 +194,14 @@ const config: Config = { label: 'Introduction', to: '/docs', }, + { + label: 'Quickstart', + to: '/docs/quickstart', + }, + { + label: 'Overview', + to: '/docs/overview', + }, { label: 'Tutorials', to: '/docs/category/tutorials', @@ -135,6 +223,10 @@ const config: Config = { label: 'Reddit', href: 'https://www.reddit.com/r/cgp/', }, + { + label: 'Bluesky', + href: 'https://bsky.app/profile/contextgeneric.dev', + }, ], }, { @@ -154,8 +246,12 @@ const config: Config = { copyright: `Licensed by MaybeVoid under a Creative Commons Attribution-ShareAlike 4.0 International License.`, }, prism: { - theme: prismThemes.github, - darkTheme: prismThemes.dracula, + theme: prismLight, + darkTheme: prismDark, + // Prism's default bundle lacks these, so their fenced blocks would render as plain text. The + // grammars ship in the `prismjs` package Docusaurus already installs. Scala extends Java's + // grammar, so Java comes first. + additionalLanguages: ['toml', 'bash', 'ebnf', 'haskell', 'ocaml', 'java', 'scala'], }, } satisfies Preset.ThemeConfig, }; 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..4c2229cd --- /dev/null +++ b/example-code/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "cgp-website-example-code" +version = "0.0.0" +edition = "2024" +publish = false +description = "Compiled counterparts of the code shown on contextgeneric.dev. Not part of the site." + +[dependencies] +# The `cgp` release the site documents. +cgp = { version = "0.8.0", features = ["alloc"] } + +[dev-dependencies] +anyhow = "1.0.104" +cap-std = "3.4.6" +futures = "0.3.34" +serde = { version = "1.0.229", features = ["derive"] } +tokio = { version = "1.54.1", features = ["fs", "macros", "rt-multi-thread"] } +trybuild = "1.0.125" diff --git a/example-code/README.md b/example-code/README.md new file mode 100644 index 00000000..116caaf8 --- /dev/null +++ b/example-code/README.md @@ -0,0 +1,156 @@ +# 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 assumed +correct. + +Run it from this directory: + +```sh +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. + +CI runs the same suite with the compile-fail snapshots skipped +(`cargo test -- --skip rejected_snippets_do_not_compile`). Run the full command locally. + +## 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/tooling/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) +- `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`, `tests/overview.rs` answers `docs/overview.md`, and `tests/front_page.rs` answers the front page. 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 | +|---|---| +| `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/tooling/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, and `storage-backend.md`, one module per step assembled from the page's blocks, with its deliberate mistake at `tests/compile_fail/tutorials/`; the rest is filled in lazily | +| `docs/quickstart.md` | complete — `tests/quickstart.rs`, a standalone binary rather than a section tree | +| `blog/2026-11-18-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 (`src/pages/index.tsx`) | complete — `tests/front_page.rs`, a standalone binary for the hero's CGP block, with the hero's rejected block at `tests/compile_fail/front_page/`; the text between each `front-page:` marker pair is exactly what the page shows, the rejected block starts at its fixture's first line so the page's quoted `E0119` names the lines the page numbers, and a test compares that quote with the fixture's snapshot | +| `docs/overview.md` | complete — `tests/overview.rs`, a standalone binary with one module per key feature and stand-ins for the storage clients and the database pool the page names; the type-safe-wiring section's missing-field program is at `tests/compile_fail/overview/` | +| 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 +`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. + +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, 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 +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 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. + +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 +``` + +A snapshot that quotes a line from `cgp` writes its path as `$CARGO/…`, the registry source trybuild +normalizes, just as the crate's own files and the standard library are written as `tests/…` and +`$RUST/…`, so no snapshot depends on where the checkout lives. 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, 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 + +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`**, 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 + +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 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 + +The crate checks the pages against the `cgp` release the site documents, pinned from crates.io as +`cgp = "0.8.0"`, the same pin the Quickstart and the tutorials show. The `.stderr` files quote that +release's sources through trybuild's `$CARGO` path, so they do not depend on the machine. At the next +release, change the pin with the pages' pins and re-bless the snapshots, since quoted line numbers +can move. 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], + } +} 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, + } +} diff --git a/example-code/rust-toolchain.toml b/example-code/rust-toolchain.toml new file mode 100644 index 00000000..db243db2 --- /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.100.0" +profile = "minimal" 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..b8cadb6c --- /dev/null +++ b/example-code/tests/blog/v0_8_0_release.rs @@ -0,0 +1,1444 @@ +//! Compiled counterparts of `blog/2026-11-18-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_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: AiUserCensor, + SpamMessageDetectorComponent: AiSpamMessageDetector, + } + } + + #[derive(HasField)] + pub struct TestApp { + pub database: PostgresDb, + } + + delegate_and_check_components! { + TestApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } + } +} + +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, + } + } + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + namespace DefaultAppComponents; + + @app.extra.content_filter: AiContentFilterComponents, + } + } + 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 } } +} + +mod import_the_component_key { + mod components { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + } + + mod providers { + use cgp::prelude::*; + + use super::components::{Greeter, GreeterComponent}; + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } + } + } + + // The header names the trait by its path, so the key follows that path without an import. + mod path_providers { + use cgp::prelude::*; + + #[cgp_impl(new GreetByPath)] + impl super::components::Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } + } + } + + mod contexts { + use cgp::prelude::*; + + use super::components::GreeterComponent; + use super::path_providers::GreetByPath; + use super::providers::GreetHello; + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_and_check_components! { + Person { + GreeterComponent: GreetHello, + } + } + + #[derive(HasField)] + pub struct Robot { + pub name: Box, + } + + delegate_and_check_components! { + Robot { + GreeterComponent: GreetByPath, + } + } + } +} + +mod import_what_the_prelude_no_longer_exports { + use cgp::core::component::DelegateComponent; + use cgp::core::field::traits::HasField; + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[cgp_impl(new Double)] + impl Computer { + type Output = u64; + + fn compute(&self, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: Double, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + fn uses_the_table>() {} + + fn read_count>(context: &Context) -> u64 { + *context.get_field(PhantomData) + } + + #[test] + fn the_imported_names_resolve() { + uses_the_table::(); + } +} + +mod use_type_in_another_context { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + #[cgp_fn] + #[use_type(HasScalarType.Scalar in Types)] + pub fn rectangle_area( + &self, + #[implicit] width: Scalar, + #[implicit] height: Scalar, + ) -> Scalar + where + Scalar: Mul + Copy, + { + width * height + } +} + +mod derive_delegate_attribute { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } +} + +mod alloc_feature { + // The crate's manifest turns on `cgp`'s `alloc` feature, which these providers need. + #[allow(unused_imports)] + use cgp::extra::error::{DebugError, DisplayError}; +} + +mod borrow_any_string_field { + use std::borrow::Cow; + + use cgp::prelude::*; + + #[cgp_fn] + pub fn label(&self, #[implicit] name: &str, #[implicit] nickname: Option<&str>) -> String { + match nickname { + Some(nickname) => format!("{name} ({nickname})"), + None => name.to_owned(), + } + } + + #[derive(HasField)] + pub struct Account { + pub name: Cow<'static, str>, + pub nickname: Option>, + } + + #[test] + fn reads_cow_and_optional_box_fields() { + let account = Account { + name: Cow::Borrowed("Ada"), + nickname: Some("ada".into()), + }; + assert_eq!(account.label(), "Ada (ada)"); + } +} 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/cargo_cgp/check.rs b/example-code/tests/cargo_cgp/check.rs new file mode 100644 index 00000000..13d25d05 --- /dev/null +++ b/example-code/tests/cargo_cgp/check.rs @@ -0,0 +1,12 @@ +//! Code from `docs/tooling/cargo-cgp/check.md` — *Check*. +//! +//! Both programs on the page are broken on purpose, so both are `trybuild` fixtures: +//! +//! - *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. +//! +//! The page's repaired program, with `height` restored, is the one [`super::expand`] carries. diff --git a/example-code/tests/cargo_cgp/expand.rs b/example-code/tests/cargo_cgp/expand.rs new file mode 100644 index 00000000..82410164 --- /dev/null +++ b/example-code/tests/cargo_cgp/expand.rs @@ -0,0 +1,52 @@ +//! Code from `docs/tooling/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/tests/cargo_cgp/mod.rs b/example-code/tests/cargo_cgp/mod.rs new file mode 100644 index 00000000..ac8e7d44 --- /dev/null +++ b/example-code/tests/cargo_cgp/mod.rs @@ -0,0 +1,19 @@ +//! Code from the pages under `docs/tooling/cargo-cgp/`. +//! +//! 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 +//! `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` and the imported key that `reading-output.md` gives as the fixes for `[CGP-E030]` +//! and `[CGP-E041]`. +//! +//! 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..efc7b32c --- /dev/null +++ b/example-code/tests/cargo_cgp/reading_output.rs @@ -0,0 +1,95 @@ +//! Code from `docs/tooling/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 programs here are the two fixes it gives +//! under *A fix in a help line*: adding `#[uses(PersonName)]` to `greeting`, and importing +//! `AreaCalculatorComponent` beside `AreaCalculator`, as the `[CGP-E041]` fix does. + +/// *A fix in a `help` line* — each program with the fix its help names applied. +pub mod a_fix_in_a_help_line { + /// The attribute the `[CGP-E030]` help names. + pub mod declared_dependency { + 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!"); + } + } + + /// The import the `[CGP-E041]` fix inserts. The fixture + /// `reading_output_a_fix_in_a_help_line_import.rs` is the program without it. + pub mod imported_key { + pub mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + } + + pub mod providers { + use cgp::prelude::*; + + use super::components::{AreaCalculator, AreaCalculatorComponent}; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + } + + use cgp::prelude::*; + + use components::{AreaCalculatorComponent, CanCalculateArea}; + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: providers::RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn the_imported_key_wires_the_provider() { + let rect = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rect.area(), 12.0); + } + } +} diff --git a/example-code/tests/cargo_cgp_tests.rs b/example-code/tests/cargo_cgp_tests.rs new file mode 100644 index 00000000..8b251bef --- /dev/null +++ b/example-code/tests/cargo_cgp_tests.rs @@ -0,0 +1,10 @@ +//! Runnable checks for the code shown on the `docs/tooling/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/comparisons/algebraic_effects.rs b/example-code/tests/comparisons/algebraic_effects.rs new file mode 100644 index 00000000..fbcdd731 --- /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 declare operations; providers implement them +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 } } + } +} + +/// ## Context fields supply an environment value +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 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; + 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..fe05dcf0 --- /dev/null +++ b/example-code/tests/comparisons/capabilities.rs @@ -0,0 +1,98 @@ +//! Code from `docs/comparisons/capabilities.md` — *Capabilities*. + +/// ## Providers declare requirements on a context +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..4b1089f1 --- /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 declare what an implementation needs +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 selects implementations for an application +/// ## Checking validates the declared dependencies +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..c31b42e5 --- /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*. + +/// ## Provider code calls methods on a generic receiver +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!"); + } +} + +/// ## 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::*; + + #[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 share bindings and leave paths for contexts to fill +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..2781be50 --- /dev/null +++ b/example-code/tests/comparisons/implicit_parameters.rs @@ -0,0 +1,111 @@ +//! Code from `docs/comparisons/implicit-parameters.md` — *Implicit parameters*. + +/// ## Implicit arguments read named context fields +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 determined by the context +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] + #[prefix(@cgp.core.error in DefaultNamespace)] + pub trait HasErrorType { + type Error: Debug; + } +} + +/// ## Components and wiring make instance selection explicit +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..87c95fe9 --- /dev/null +++ b/example-code/tests/comparisons/ml_modules.rs @@ -0,0 +1,132 @@ +//! 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] + #[prefix(@cgp.core.error in DefaultNamespace)] + pub trait HasErrorType { + type Error: Debug; + } +} + +/// ## `delegate_components!` records the assembly choices +pub mod delegate_components_replaces_functor_application { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + /// Stand-in for the AWS SDK's S3 client, which the page names as `aws_sdk_s3::Client`. + pub mod aws_sdk_s3 { + pub struct Client; + } + + // The page wires this component and provider without declaring them; the declarations + // follow the site's object-storage example. + #[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // The page elides the body; the stand-in returns the object's address instead. + let _ = storage_client; + Ok(format!("s3://{bucket_id}/{object_id}").into_bytes()) + } + } + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + ErrorTypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + check_components! { App { StorageObjectFetcherComponent, ErrorTypeProviderComponent } } + } + + #[test] + fn the_table_is_resolved_in_any_order() { + let app = App { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + assert_eq!( + app.fetch_storage_object("alice.png").unwrap(), + b"s3://pictures/alice.png" + ); + } +} 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..76ebbb6a --- /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); + } +} + +/// ## Providers access the context without an inheritance cast +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..e307cda8 --- /dev/null +++ b/example-code/tests/comparisons/reflection.rs @@ -0,0 +1,125 @@ +//! 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 +//! `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 { + use cgp::core::field::traits::HasFields; + use cgp::core::field::types::Field; + 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::(); + } +} + +/// ## Serializing through the trait system +pub mod reflection_driven_serialization { + use core::fmt::Debug; + + use cgp::core::field::traits::HasField; + use cgp::core::field::traits::HasFields; + use cgp::core::field::traits::StaticString; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Field; + use cgp::core::field::types::Nil; + 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..b5f2df99 --- /dev/null +++ b/example-code/tests/comparisons/row_polymorphism.rs @@ -0,0 +1,119 @@ +//! 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::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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..5dd3e61f --- /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 `with` clause becomes a context field +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..f88a40d5 --- /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 providers need no specificity rule +/// ## Incoherent choices made explicit 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/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..321fd486 --- /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) 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..5d82b5f7 --- /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/tooling/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_the_wiring_where_you_write_it.stderr b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr new file mode 100644 index 00000000..2d3ebe49 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:31:9 + | +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_the_wiring_where_you_write_it.rs:19:9 + | +19 | pub width: f64, + | ^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.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/check_check_the_wiring_where_you_write_it.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/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..312dd714 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs @@ -0,0 +1,33 @@ +// From docs/tooling/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..15fdbd95 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs @@ -0,0 +1,33 @@ +// From docs/tooling/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/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..72120a1c --- /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/tooling/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_a_field_with_the_wrong_type.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs new file mode 100644 index 00000000..712a206e --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs @@ -0,0 +1,35 @@ +// From docs/tooling/cargo-cgp/reading-output.md, A field with the wrong type. + +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: u32, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} 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..dd182e6e --- /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/tooling/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..1d868908 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr @@ -0,0 +1,26 @@ +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__: 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: + | +10 | #[cgp_fn]: PersonName + | ++++++++++++ diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.rs new file mode 100644 index 00000000..c9fd4fb8 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.rs @@ -0,0 +1,23 @@ +mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } +} + +mod providers { + use cgp::prelude::*; + + use crate::components::AreaCalculator; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.stderr new file mode 100644 index 00000000..9f9d1675 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.stderr @@ -0,0 +1,10 @@ +error[E0425]: cannot find type `AreaCalculatorComponent` in this scope + --> tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line_import.rs:16:10 + | +16 | impl AreaCalculator { + | ^^^^^^^^^^^^^^ not found in this scope + | +help: consider importing this struct + | +11 + use crate::components::AreaCalculatorComponent; + | 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..8124a1db --- /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/tooling/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..bf79dbe6 --- /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/tooling/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) + | 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..8793e53f --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs @@ -0,0 +1,34 @@ +// From docs/tooling/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..514cfcf9 --- /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..9593abaa --- /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/tooling/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` 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 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..f5c9ca85 --- /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 `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..8c270b07 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } +} + +// The mistake: `BrokenApp` has no `local_dir` field, though `FetchLocalObject` reads one. +#[derive(HasField)] +pub struct BrokenApp { + pub bucket_id: String, +} + +delegate_components! { BrokenApp { StorageObjectFetcherComponent: FetchLocalObject } } + +fn main() { + let app = BrokenApp { + bucket_id: "pictures".to_owned(), + }; + // The hidden failure: `E0599` at the call site, naming nothing about the missing field. + let _ = app.fetch_storage_object("alice.png"); +} 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..7595f17b --- /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 `fetch_storage_object` exists for struct `BrokenApp`, but its trait bounds were not satisfied + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:32:17 + | +21 | pub struct BrokenApp { + | -------------------- method `fetch_storage_object` not found for this struct because it doesn't satisfy `BrokenApp: CanFetchStorageObject` or `BrokenApp: StorageObjectFetcher` +... +32 | let _ = app.fetch_storage_object("alice.png"); + | ^^^^^^^^^^^^^^^^^^^^ 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 `StorageObjectFetcher` + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:5:5 + | + 5 | fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: trait bound `BrokenApp: StorageObjectFetcher` was not satisfied + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:3:1 + | + 3 | #[cgp_component(StorageObjectFetcher)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanFetchStorageObject { + | ^^^^^^^^^^^^^^^^^^^^^ +note: the trait `StorageObjectFetcher` must be implemented + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:4:1 + | + 4 | / pub trait CanFetchStorageObject { + 5 | | fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + 6 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanFetchStorageObject` defines an item `fetch_storage_object`, perhaps you need to implement it + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:4:1 + | + 4 | pub trait CanFetchStorageObject { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = 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 + | +32 - let _ = app.fetch_storage_object("alice.png"); +32 + let _ = BrokenApp::fetch_storage_object("alice.png"); + | 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..9ef5014e --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs @@ -0,0 +1,34 @@ +use cgp::prelude::*; + +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } +} + +// The mistake: `BrokenApp` has no `local_dir` field, though `FetchLocalObject` reads one. +#[derive(HasField)] +pub struct BrokenApp { + pub bucket_id: String, +} + +delegate_components! { BrokenApp { StorageObjectFetcherComponent: FetchLocalObject } } + +// The check forces the failure to the wiring site and names the missing field. +check_components! { + BrokenApp { + StorageObjectFetcherComponent, + } +} + +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..43041c62 --- /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:30:9 + | +30 | StorageObjectFetcherComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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:22:9 + | +22 | pub bucket_id: String, + | ^^^^^^^^^ +note: required for `FetchLocalObject` to implement `IsProviderFor` + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:8:1 + | + 8 | #[cgp_impl(new FetchLocalObject)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = 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:28:1 + | +28 | / check_components! { +29 | | BrokenApp { +30 | | StorageObjectFetcherComponent, +31 | | } +32 | | } + | |_^ required by this bound in `__CheckBrokenApp` + = 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/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..9fcdd472 --- /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 CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +pub trait HasS3Client {} +pub trait HasLocalDir {} + +impl CanFetchStorageObject for T { fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Vec::new()) } } +impl CanFetchStorageObject for T { fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Vec::new()) } } // 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..c3db64a8 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.stderr @@ -0,0 +1,21 @@ +error[E0119]: conflicting implementations of trait `CanFetchStorageObject` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:9:1 + | +8 | impl CanFetchStorageObject for T { fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Ve... + | ------------------------------------------------ first implementation here +9 | impl CanFetchStorageObject for T { fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Ve... + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation + +warning: unused variable: `object_id` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:8:83 + | +8 | ...h_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Vec::new()) } } + | ^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_object_id` + | + = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default + +warning: unused variable: `object_id` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:9:83 + | +9 | ...h_storage_object(&self, object_id: &str) -> anyhow::Result> { Ok(Vec::new()) } } // error[E0119] + | ^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_object_id` 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..718600f2 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs @@ -0,0 +1,21 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{FinalizeBuild, HasBuilder}; +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..772cfc9c --- /dev/null +++ b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.stderr @@ -0,0 +1,14 @@ +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:20:10 + | + 6 | pub struct App { + | -------------- method `finalize_build` not found for this struct +... +18 | let _app: App = App::builder() +19 | .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) +20 | .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: `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..eff05efb --- /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/front_page/rust_accepts_only_one.rs b/example-code/tests/compile_fail/front_page/rust_accepts_only_one.rs new file mode 100644 index 00000000..f9805abc --- /dev/null +++ b/example-code/tests/compile_fail/front_page/rust_accepts_only_one.rs @@ -0,0 +1,21 @@ +// Rust allows only one of these. `String` is both `Display` and +// `AsRef<[u8]>`, so the compiler has no principled way to choose. +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +impl CanEncode for T { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +impl> CanEncode for T { // error[E0119] + fn encode(&self) -> Vec { self.as_ref().to_vec() } +} +// front-page:rejected-block:end + +// The front page's rejected block: the encoder pair without CGP. Everything above the end marker is +// exactly what the page shows, starting at line 1, so the line numbers in the compiler's error match +// the numbered block on the page. The import and `fn main` it omits come after it, which Rust allows. +use core::fmt::Display; + +fn main() {} diff --git a/example-code/tests/compile_fail/front_page/rust_accepts_only_one.stderr b/example-code/tests/compile_fail/front_page/rust_accepts_only_one.stderr new file mode 100644 index 00000000..719419ee --- /dev/null +++ b/example-code/tests/compile_fail/front_page/rust_accepts_only_one.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `CanEncode` + --> tests/compile_fail/front_page/rust_accepts_only_one.rs:11:1 + | + 7 | impl CanEncode for T { + | -------------------------------- first implementation here +... +11 | impl> CanEncode for T { // error[E0119] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation diff --git a/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.rs b/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.rs new file mode 100644 index 00000000..57f4719c --- /dev/null +++ b/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.rs @@ -0,0 +1,55 @@ +//! `docs/overview.md`, *Type-Safe Wiring*: `App` lacks the `bucket_id` field `FetchS3Object` reads, +//! so the check rejects the wiring. The S3 client is a stand-in, and the provider's body, which the +//! page elides, is filled in. + +use cgp::prelude::*; + +pub mod aws_sdk_s3 { + pub struct Client; + + impl Client { + pub fn get_object( + &self, + bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(format!("s3://{bucket_id}/{object_id}").into_bytes()) + } + } +} + +#[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + storage_client.get_object(bucket_id, object_id) + } +} + +#[derive(HasField)] +pub struct App { + pub storage_client: aws_sdk_s3::Client, +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +check_components! { + App { + StorageObjectFetcherComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.stderr b/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.stderr new file mode 100644 index 00000000..3b83aa17 --- /dev/null +++ b/example-code/tests/compile_fail/overview/type_safe_wiring_missing_field.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied + --> tests/compile_fail/overview/type_safe_wiring_missing_field.rs:51:9 + | +51 | StorageObjectFetcherComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>>>>` is not implemented for `App` + but trait `HasField>>>>>>>>>>>>>>>` is implemented for it + --> tests/compile_fail/overview/type_safe_wiring_missing_field.rs:40:9 + | +40 | pub storage_client: aws_sdk_s3::Client, + | ^^^^^^^^^^^^^^ +note: required for `FetchS3Object` to implement `IsProviderFor` + --> tests/compile_fail/overview/type_safe_wiring_missing_field.rs:26:1 + | +26 | #[cgp_impl(new FetchS3Object)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/overview/type_safe_wiring_missing_field.rs:49:1 + | +49 | / check_components! { +50 | | App { +51 | | StorageObjectFetcherComponent, +52 | | } +53 | | } + | |_^ 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/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..72721925 --- /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::macro_prelude::IsProviderFor>>>>, cgp::macro_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..6d57e4f0 --- /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` + --> $CARGO/cgp-component-$VERSION/src/namespaces.rs + | + | pub trait DefaultImpls1 { + | ^^^^^^^^^^^^^ - ---------- 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/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..9fbf1210 --- /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__: 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] + | ^^^^^^^^^^^^^^^^^^ + 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..7242a08c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr @@ -0,0 +1,45 @@ +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 `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)] + 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__: 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] + | ^^^^^^^^^^^^^^^^^^ + 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..d10b974b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.stderr @@ -0,0 +1,36 @@ +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 + | +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 + | + 5 | #[cgp_fn] + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale::scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | +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..636f2384 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.stderr @@ -0,0 +1,38 @@ +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 + | +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 + | + 5 | #[cgp_fn] + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale::scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | +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_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..7823f0cd --- /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) -> String { + "Hello!".to_owned() +} + +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/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..e9a9f522 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr @@ -0,0 +1,45 @@ +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 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 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 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[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ 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/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..effb451a --- /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 new file mode 100644 index 00000000..551da8f6 --- /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(@greeting 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..fd4405dd --- /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/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..4649ea20 --- /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)] + | ^^^^^^^^^^^^ + | +note: similarly named attribute macro `cgp_provider` defined here + --> $CARGO/cgp-macro-$VERSION/src/lib.rs + | + | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +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..3a58e92f --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr @@ -0,0 +1,24 @@ +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> { + | ^^^^ not found in `HasErrorType` + | +note: similarly named associated type `Error` defined here + --> $CARGO/cgp-error-$VERSION/src/traits/has_error_type.rs + | + | type Error: Debug; + | ^^^^^^^^^^^^^^^^^ +note: associated type `Error` defined here + --> $CARGO/cgp-error-$VERSION/src/traits/has_error_type.rs + | + | type Error: Debug; + | ^^^^^^^^^^^^^^^^^ +help: an associated type with a similar name exists + | +16 | pub fn fail(&self) -> Result<(), Error> { + | + +help: maybe you meant this associated type + | +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..b18ac7bc --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr @@ -0,0 +1,5 @@ +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)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ 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/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_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()); + | 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/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..2a9775e1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs @@ -0,0 +1,26 @@ +use core::marker::PhantomData; + +use cgp::extra::handler::CanCompute; +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 + } +} + +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..9f1dc7ba --- /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:25:18 + | +25 | 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 `Computer` for the type `__Provider__` +help: use fully-qualified syntax to disambiguate + | +25 - let _ = App::compute(&App, PhantomData::<()>, 21); +25 + let _ = ::compute(&App, PhantomData::<()>, 21); + | +25 - let _ = App::compute(&App, PhantomData::<()>, 21); +25 + 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..623b6db4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs @@ -0,0 +1,31 @@ +use core::marker::PhantomData; + +use cgp::extra::handler::ComputerComponent; +use cgp::extra::handler::PromoteRef; +use cgp::extra::handler::{Computer, ComputerRefComponent}; +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..480b4292 --- /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:27:9 + | +27 | 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:9:54 + | + 9 | 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> 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:25:1 + | +25 | / check_components! { +26 | | App { +27 | | ComputerRefComponent: ((), 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 `for<'a> Double: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:27:9 + | +27 | 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:9:1 + | + 9 | impl Computer for Double { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `u64`, found `&'a u64` + = note: required for `Double` to implement `for<'a> 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:25:1 + | +25 | / check_components! { +26 | | App { +27 | | ComputerRefComponent: ((), 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/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..3bebef56 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs @@ -0,0 +1,33 @@ +use core::marker::PhantomData; + +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::ComputerComponent; +use cgp::extra::handler::PromoteComputer; +use cgp::extra::handler::{Computer, HandlerComponent}; +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..0e4da1c9 --- /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:29:9 + | +29 | 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:10:54 + | +10 | impl Computer for Double { + | ^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteComputer + PromoteProducer + PromoteTryComputer + = note: required for `Double` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `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:27:1 + | +27 | / check_components! { +28 | | App { +29 | | HandlerComponent: ((), u64), +30 | | } +31 | | } + | |_^ 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:29:9 + | +29 | 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:10:1 + | +10 | impl Computer for Double { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `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 `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:27:1 + | +27 | / check_components! { +28 | | App { +29 | | HandlerComponent: ((), u64), +30 | | } +31 | | } + | |_^ 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..07230113 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs @@ -0,0 +1,33 @@ +use core::marker::PhantomData; + +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::ProducerComponent; +use cgp::extra::handler::PromoteProducer; +use cgp::extra::handler::{ComputerComponent, Producer, TryComputerComponent}; +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..a8e84d59 --- /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:29:29 + | +29 | [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:10:49 + | +10 | impl Producer for MagicNumber { + | ^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + App + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteProducer + = note: required for `MagicNumber` to implement `Computer` + = note: required for `Promote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `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:27:1 + | +27 | / check_components! { +28 | | App { +29 | | [ComputerComponent, TryComputerComponent]: ((), ()), +30 | | } +31 | | } + | |_^ 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:29:29 + | +29 | [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:10:1 + | +10 | impl Producer for MagicNumber { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `ProducerComponent`, found `ComputerComponent` + = note: required for `MagicNumber` to implement `Computer` + = note: required for `Promote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `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:27:1 + | +27 | / check_components! { +28 | | App { +29 | | [ComputerComponent, TryComputerComponent]: ((), ()), +30 | | } +31 | | } + | |_^ 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/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..6533d38c --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs @@ -0,0 +1,29 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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..bc27c488 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr @@ -0,0 +1,12 @@ +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:26:10 + | +26 | .build_from(source) + | ^^^^^^^^^^ 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:6:1 + | + 6 | 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..09a309c1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs @@ -0,0 +1,15 @@ +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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..8f40aa65 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.stderr @@ -0,0 +1,14 @@ +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:14:10 + | + 5 | pub struct Person { + | ----------------- method `finalize_build` not found for this struct +... +12 | let person: Person = Person::builder() +13 | .build_field(PhantomData::, "Alice".to_owned()) +14 | .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: `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..63d7fcc4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs @@ -0,0 +1,16 @@ +use cgp::core::field::traits::{BuildField, HasBuilder, HasField}; +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..9c6ef0eb --- /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:15:31 + | +15 | let _ = partial.get_field(PhantomData::); + | --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `10`, found `9` + | | + | arguments to this method are incorrect + | + = note: expected struct `PhantomData>>>>>>>>>>>` + found struct `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_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_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..6f26cb28 --- /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, 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_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_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_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..536a3e05 --- /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, 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_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..701806d1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs @@ -0,0 +1,27 @@ +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::core::field::traits::{ExtractField, HasExtractor}; +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..92674fac --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -0,0 +1,20 @@ +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:26:10 + | +14 | pub enum Shape { + | -------------- doesn't satisfy `__PartialShape: FinalizeExtract` +... +23 | let _ = shape +24 | .to_extractor() +25 | .extract_field(PhantomData::) +26 | .finalize_extract_result(); + | ^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called on `Result>` due to unsatisfied trait bounds + | + = 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..b8224063 --- /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, 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_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_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..cffee306 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs @@ -0,0 +1,24 @@ +use cgp::core::field::traits::FromVariant; +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..5444dad9 --- /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:23:33 + | +23 | 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::macro_prelude::FromVariant<_>` found + --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs:15:5 + | +15 | Circle(Circle), + | ^^^^^^ +16 | Rectangle(Rectangle), + | ^^^^^^^^^ +help: consider specifying a concrete type for the type parameter `T` + | +23 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 2.0 }); + | ++++++++++++++ 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..fccf1813 --- /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, 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_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..e652c81e --- /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::macro_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::macro_prelude::HasField for Context + where ::Target == Target, >::Value == Value, Context: cgp::cgp_core::cgp_field::traits::has_field::DerefMap, Target: cgp::macro_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..a6bd439c --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs @@ -0,0 +1,17 @@ +use cgp::core::field::traits::HasFieldMut; +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..c7f5d9ba --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.stderr @@ -0,0 +1,25 @@ +error[E0521]: borrowed data escapes outside of function + --> tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs:14:13 + | +13 | pub fn rename<'a>(boxed: &mut Box>) { + | -- ----- `boxed` is only valid in the function body + | | + | lifetime `'a` defined here +14 | let _ = boxed.get_field_mut(PhantomData::); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `boxed` escapes the function body here + | argument requires that `'a` must outlive `'static` + | +note: `'static` lifetime requirement from `>::get_field_mut` introduced here + --> $CARGO/cgp-field-$VERSION/src/traits/has_field_mut.rs + | + | impl HasFieldMut for Context +... + | Target: HasFieldMut + 'static, + | ^^^^^^^ lifetime requirement introduced here + | { + | fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value { + = 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_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/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..e60965bf --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.rs @@ -0,0 +1,40 @@ +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] missing field `name` on `Person` +// root cause: [CGP-E110] 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..b64c18be --- /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:36:9 + | +36 | 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:23:9 + | +23 | pub age: u8, + | ^^^ +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:34:1 + | +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/errors_the_fix_2.rs b/example-code/tests/compile_fail/reference/errors_the_fix_2.rs new file mode 100644 index 00000000..a3b98f22 --- /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, + } +} + +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 new file mode 100644 index 00000000..adca7d9a --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr @@ -0,0 +1,41 @@ +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 + | +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 + | + = 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(); + | 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..c2b42ddf --- /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_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.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..0d2e46ca --- /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..4789869a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr @@ -0,0 +1,10 @@ +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:21:11 + | +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::macro_prelude::IsProviderFor` for type `cgp::macro_prelude::MatchWithValueHandlersRef` in future versions 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.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..ac2fc215 --- /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: HasExtractor` +... +36 | shape.area() + | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds + | + ::: $CARGO/cgp-dispatch-$VERSION/src/providers/matchers/match_with_field_handlers.rs + | + | 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: 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 `HasExtractor` must be implemented + --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | 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..52abaca1 --- /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 + | + ::: $CARGO/cgp-dispatch-$VERSION/src/providers/matchers/match_with_field_handlers.rs + | + | 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: 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 + | +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..1d106d49 --- /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_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..9040fd71 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -0,0 +1,22 @@ +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 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_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..993bca74 --- /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::macro_prelude::HasField>>>>>` + `<&Person as cgp::macro_prelude::HasField>>>>>>::Value = String` + `>>>>>>::Value = String` + `Person: cgp::macro_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::macro_prelude::HasField` must be implemented + --> $CARGO/cgp-field-$VERSION/src/traits/has_field.rs + | + | 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..5c114619 --- /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*: the macro rejects `Option<&[T]>`, since the field it would read cannot exist. + +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..c361fbf8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr @@ -0,0 +1,5 @@ +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]>; + | ^^^^^^^^^^^^^ 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_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..96aca140 --- /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 is rejected as a parameter the trait does not declare. + +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..fe18aa19 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr @@ -0,0 +1,5 @@ +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 }] + | ^^^^^^^^^^^^^^ 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..0fd13128 --- /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 rejected by name. + +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..9d6d8603 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr @@ -0,0 +1,5 @@ +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)] + | ^^^^^^^^^^^^^^^^ 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..652f5e02 --- /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*: the macro rejects a `name:` +//! parameter the trait does not declare. + +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..68482b76 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr @@ -0,0 +1,5 @@ +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 }] + | ^ 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..c58b769a --- /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*: the macro rejects a `_` method +//! parameter, 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..19d51afa --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr @@ -0,0 +1,5 @@ +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_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.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..6390b672 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -0,0 +1,56 @@ +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::macro_prelude::TryComputer::try_compute` + --> $CARGO/cgp-handler-$VERSION/src/components/try_compute.rs + | + | #[cgp_component(TryComputer)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` +... + | pub trait CanTryCompute { +... + | fn try_compute(&self, _code: PhantomData, input: Input) -> Result; + = 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` + --> $CARGO/cgp-handler-$VERSION/src/providers/try_promote.rs + | + | / impl TryComputer + | | for TryPromote + | | where + | | Context: HasErrorType, + | | 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/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..55335425 --- /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` + --> $CARGO/cgp-handler-$VERSION/src/providers/promote.rs + | + | / impl TryComputer for Promote + | | where + | | Context: HasErrorType, + | | ------------ + | | | + | | unsatisfied requirement introduced here: `App: HasErrorType` + | | unsatisfied requirement introduced here: `App: HasErrorType` + | | Provider: Computer, + | |______________________________________________________________^ + = note: required for `Add` to implement `TryComputer` 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..54fbb11e --- /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 rejected, since the generated impl cannot determine it. + +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..3aa4fc5f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr @@ -0,0 +1,5 @@ +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 { + | ^ 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..a141276f --- /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..4e3715b9 --- /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 is +//! rejected, because the macro selects the fallible bundle only for `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..ec062d23 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr @@ -0,0 +1,5 @@ +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_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_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..92edb328 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs @@ -0,0 +1,28 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: the field must have the type the return type calls for. + +use cgp::core::field::impls::UseField; +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..bebdc550 --- /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:24:9 + | +24 | 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:13:21 + | +13 | pub first_name: &'static str, + | ^^^^^^^^^^^^ +note: required for `UseField>>>>>>>>>>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs:6:1 + | + 6 | #[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:22:1 + | +22 | / check_components! { +23 | | Person { +24 | | NameGetterComponent, +25 | | } +26 | | } + | |_^ 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..a2bc346e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs @@ -0,0 +1,30 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: a multi-method trait gets no `UseField` provider. + +use cgp::core::field::impls::UseField; +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..cbed7cc3 --- /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 `UseField>>>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs:26:9 + | +26 | DimensionsGetterComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `UseField>>>>>>` +help: the following other types implement trait `IsProviderFor` + --> $CARGO/cgp-field-$VERSION/src/impls/use_field.rs + | + | / impl IsProviderFor + | | for UseField + | | where + | | Context: HasField, + | |_______________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/async_computer.rs + | + | / impl AsyncComputer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/computer.rs + | + | / impl Computer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanCompute, + | |_____________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-runtime-$VERSION/src/traits/has_runtime.rs + | + | #[cgp_getter] + | ^^^^^^^^^^^^^ `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:24:1 + | +24 | / check_components! { +25 | | Rectangle { +26 | | DimensionsGetterComponent, +27 | | } +28 | | } + | |_^ 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_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_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_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/compile_fail/reference/macros/cgp_impl_importing_the_component_key.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.rs new file mode 100644 index 00000000..c9fd4fb8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.rs @@ -0,0 +1,23 @@ +mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } +} + +mod providers { + use cgp::prelude::*; + + use crate::components::AreaCalculator; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.stderr new file mode 100644 index 00000000..10bd9d6b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.stderr @@ -0,0 +1,10 @@ +error[E0425]: cannot find type `AreaCalculatorComponent` in this scope + --> tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.rs:16:10 + | +16 | impl AreaCalculator { + | ^^^^^^^^^^^^^^ not found in this scope + | +help: consider importing this struct + | +11 + use crate::components::AreaCalculatorComponent; + | 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..5047ccff --- /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_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..b0e06b65 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// 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 new file mode 100644 index 00000000..2e5652ea --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr @@ -0,0 +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:4:25 + | +4 | cgp_namespace! { new A: A {} } + | ^ 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_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..f53cfabe --- /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/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/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..6b1467fc --- /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_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.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..442b3d78 --- /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/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/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..6e9fcbcb --- /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 `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_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..364bf875 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.stderr @@ -0,0 +1,11 @@ +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) 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..86f571e6 --- /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..330391af --- /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::macro_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::macro_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_common_mistakes_braced_group_then_path.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.rs new file mode 100644 index 00000000..9de60170 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.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 `:`, on the dot after the closing brace +delegate_components! { + App { + open FooProviderComponent; + + @FooProviderComponent.{String, u32}.bool: DummyFoo, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr new file mode 100644 index 00000000..61c9f170 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr @@ -0,0 +1,5 @@ +error: expected `:` + --> 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_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..fe13587d --- /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::macro_prelude::IsProviderFor` for type `cgp::macro_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..f4f7908e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs @@ -0,0 +1,34 @@ +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; +// writing `new ArrayTable` keeps the kind +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..71ba20cb --- /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:28:66 + | +28 | 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 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/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/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/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..bbacd3ed --- /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, 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/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..5ea4895a --- /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::macro_prelude::Symbol<_, _> {cgp::macro_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::macro_prelude::Symbol<_, _> {cgp::macro_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/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..bd3151a9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs @@ -0,0 +1,51 @@ +use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::extra::handler::ComputerRefComponent; +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..9762ac6c --- /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:47:9 + | +47 | ComputerRefComponent: ((), ()), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `BuildWithHandlers, Cons, Nil>>>` +help: `BuildWithHandlers` implements trait `IsProviderFor` + --> $CARGO/cgp-dispatch-$VERSION/src/providers/with_handlers/build_with_handlers.rs + | + | / impl Computer + | | for BuildWithHandlers + | | where + | | Output: HasBuilder, + | | PipeHandlers: Computer, + | | Res: FinalizeBuild, + | |________________________________________^ `IsProviderFor` +... + | / impl TryComputer + | | for BuildWithHandlers + | | where + | | Context: HasErrorType, + | | Output: HasBuilder, + | | PipeHandlers: TryComputer, + | | Res: FinalizeBuild, + | |________________________________________^ `IsProviderFor` +... + | / impl Handler + | | for BuildWithHandlers + | | where + | | Context: HasErrorType, + | | Output: HasBuilder, + | | PipeHandlers: Handler, + | | 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:45:1 + | +45 | / check_components! { +46 | | AppBuilder { +47 | | ComputerRefComponent: ((), ()), +48 | | } +49 | | } + | |_^ 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..d9e86c5d --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs @@ -0,0 +1,56 @@ +use cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; +use cgp::extra::handler::{Computer, ComputerComponent}; +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..2743c8ac --- /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:52:9 + | +52 | 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:6:1 + | + 6 | pub struct App { + | ^^^^^^^^^^^^^^ +help: the trait `FinalizeBuild` is implemented for `__PartialApp` + --> tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs:6:12 + | + 6 | 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:50:1 + | +50 | / check_components! { +51 | | AppBuilder { +52 | | ComputerComponent: ((), ()), +53 | | } +54 | | } + | |_^ 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/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/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/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/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..411656d2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs @@ -0,0 +1,60 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::extra::handler::ComputerComponent; +use cgp::extra::handler::{Computer, HandlerComponent}; +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..0515eaeb --- /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:56:9 + | +56 | HandlerComponent: ((), Shape), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` +help: `MatchWithHandlers` implements trait `IsProviderFor` + --> $CARGO/cgp-dispatch-$VERSION/src/providers/with_handlers/match_with_handlers.rs + | + | / impl Computer + | | for MatchWithHandlers + | | where + | | Input: HasExtractor, + | | DispatchMatchers: + | | Computer>, + | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` +... + | / impl AsyncComputer + | | for MatchWithHandlers + | | where + | | Input: HasExtractor, + | | DispatchMatchers: + | | AsyncComputer>, + | | 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:54:1 + | +54 | / check_components! { +55 | | App { +56 | | HandlerComponent: ((), Shape), +57 | | } +58 | | } + | |_^ 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..80b5b261 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs @@ -0,0 +1,56 @@ +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::extra::handler::{Computer, ComputerComponent}; +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..41aaa463 --- /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:52:9 + | +52 | 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:15:1 + | +15 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: the trait `FinalizeExtract` is implemented for `__PartialShape` + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs:15:10 + | +15 | 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:50:1 + | +50 | / check_components! { +51 | | App { +52 | | ComputerComponent: ((), Shape), +53 | | } +54 | | } + | |_^ 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..bf7ae64f --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs @@ -0,0 +1,56 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::dispatch::MatchWithValueHandlersRef; +use cgp::extra::handler::ComputerComponent; +use cgp::extra::handler::{Computer, HandlerComponent}; +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..1498fd9d --- /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:52:9 + | +52 | 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` + --> $CARGO/cgp-dispatch-$VERSION/src/providers/with_handlers/match_with_handlers_ref.rs + | + | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer + | | for MatchWithHandlersRef + | | where + | | Input: HasExtractorRef, + | | DispatchMatchers: + | | Computer, Output = Result>, + | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` +... + | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> AsyncComputer + | | for MatchWithHandlersRef + | | where + | | Input: HasExtractorRef, + | | DispatchMatchers: + | | AsyncComputer, Output = Result>, + | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `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:50:1 + | +50 | / check_components! { +51 | | App { +52 | | HandlerComponent: <'a> ((), &'a Shape), +53 | | } +54 | | } + | |_^ 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:52:9 + | +52 | 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 + MatchWithValueHandlersRef + PipeMonadic + PromoteAsyncComputer + PromoteComputer + 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 `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:50:1 + | +50 | / check_components! { +51 | | App { +52 | | HandlerComponent: <'a> ((), &'a Shape), +53 | | } +54 | | } + | |_^ 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..7d33ed75 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs @@ -0,0 +1,53 @@ +use cgp::extra::dispatch::MatchWithValueHandlers; +use cgp::extra::handler::{Computer, ComputerComponent}; +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..9d7120ab --- /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<_>: Computer` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:49:9 + | +49 | ComputerComponent: ((), Scene), + | ^^^^^^^^^^^^^^^^^ the trait `Computer` is not implemented for `MatchWithHandlers<_>` + | +help: the trait `Computer` is conditionally implemented for `MatchWithHandlers` + --> $CARGO/cgp-dispatch-$VERSION/src/providers/with_handlers/match_with_handlers.rs + | + | / impl Computer + | | for MatchWithHandlers + | | where + | | Input: HasExtractor, + | | ------------ unsatisfied requirement introduced here: `Scene: HasExtractor` + | | DispatchMatchers: + | | Computer>, + | | 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:47:1 + | +47 | / check_components! { +48 | | App { +49 | | ComputerComponent: ((), Scene), +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 `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:49:9 + | +49 | 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` + --> $CARGO/cgp-dispatch-$VERSION/src/providers/matchers/to_field_handlers.rs + | + | / impl ToFieldHandlers for Either, RestFields> + | | where + | | M: MapFieldHandler, + | | RestFields: ToFieldHandlers, + | |___________________________________^ `Either, RestFields>` implements `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` +... + | 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:47:1 + | +47 | / check_components! { +48 | | App { +49 | | ComputerComponent: ((), Scene), +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 `Scene: HasExtractor` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:49:9 + | +49 | 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:34:1 + | +34 | 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:47:1 + | +47 | / check_components! { +48 | | App { +49 | | ComputerComponent: ((), Scene), +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/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..c5f4ec3c --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs @@ -0,0 +1,34 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::ComputerComponent; +use cgp::extra::handler::PromoteTryComputer; +use cgp::extra::handler::{Computer, HandlerComponent}; +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..91f4b6b1 --- /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:30:9 + | +30 | 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:8:54 + | + 8 | impl Computer for CheckedDouble + | ^^^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteComputer + PromoteProducer + PromoteTryComputer + = note: required for `CheckedDouble` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `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:28:1 + | +28 | / check_components! { +29 | | App { +30 | | HandlerComponent: ((), u64), +31 | | } +32 | | } + | |_^ 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:30:9 + | +30 | 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:8:1 + | + 8 | / impl Computer for CheckedDouble + 9 | | where +10 | | Context: HasErrorType, + | |__________________________________________^ + = help: for that trait implementation, expected `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 `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:28:1 + | +28 | / check_components! { +29 | | App { +30 | | HandlerComponent: ((), u64), +31 | | } +32 | | } + | |_^ 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/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..5e61792f --- /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` + --> $CARGO/cgp-error-extra-$VERSION/src/impls/raise_from.rs + | + | / impl ErrorRaiser for RaiseFrom + | | where + | | Context: HasErrorType, + | | 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/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..8f151ac2 --- /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::macro_prelude::IsProviderFor` for type `cgp::macro_prelude::RedirectLookup>>>, cgp::macro_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..1dd8c0fc --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs @@ -0,0 +1,25 @@ +use cgp::core::component::UseContext; +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..d86521e3 --- /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:21:9 + | +21 | EncoderComponent: u32, + | ^^^^^^^^^^^^^^^^ + | +note: required for `App` to implement `Encoder` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:4:1 + | + 4 | #[cgp_component(Encoder)] + | _^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 | | pub trait CanEncode { + | |__________________________^ +note: required for `App` to implement `CanEncode` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:4:1 + | + 4 | #[cgp_component(Encoder)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 | pub trait CanEncode { + | ^^^^^^^^^^^^^^^^ +note: required for `UseContext` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:4:1 + | + 4 | #[cgp_component(Encoder)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 | 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:19:1 + | +19 | / check_components! { +20 | | App { +21 | | EncoderComponent: u32, +22 | | } +23 | | } + | |_^ 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..17eebff8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.stderr @@ -0,0 +1,51 @@ +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)] +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)] +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..79ab4e25 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs @@ -0,0 +1,28 @@ +use cgp::core::field::impls::UseField; +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..bfe12bab --- /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 `UseField>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs:24:9 + | +24 | FooBarGetterComponent, + | ^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `UseField>>>>` +help: the following other types implement trait `IsProviderFor` + --> $CARGO/cgp-field-$VERSION/src/impls/use_field.rs + | + | / impl IsProviderFor + | | for UseField + | | where + | | Context: HasField, + | |_______________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/async_computer.rs + | + | / impl AsyncComputer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/computer.rs + | + | / impl Computer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanCompute, + | |_____________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-runtime-$VERSION/src/traits/has_runtime.rs + | + | #[cgp_getter] + | ^^^^^^^^^^^^^ `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:22:1 + | +22 | / check_components! { +23 | | App { +24 | | FooBarGetterComponent, +25 | | } +26 | | } + | |_^ 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/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..5ac4697e --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs @@ -0,0 +1,26 @@ +use cgp::core::field::impls::UseField; +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..1c8c0bb7 --- /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 `UseField>>>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs:22:9 + | +22 | WidthTypeProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `UseField>>>>>>` +help: the following other types implement trait `IsProviderFor` + --> $CARGO/cgp-field-$VERSION/src/impls/use_field.rs + | + | / impl IsProviderFor + | | for UseField + | | where + | | Context: HasField, + | |_______________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/async_computer.rs + | + | / impl AsyncComputer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-handler-$VERSION/src/components/computer.rs + | + | / impl Computer for UseField + | | where + | | Context: HasField, + | | Context::Value: CanCompute, + | |_____________________________________________________________^ `UseField` implements `IsProviderFor` + | + ::: $CARGO/cgp-runtime-$VERSION/src/traits/has_runtime.rs + | + | #[cgp_getter] + | ^^^^^^^^^^^^^ `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:20:1 + | +20 | / check_components! { +21 | | Rectangle { +22 | | WidthTypeProviderComponent, +23 | | } +24 | | } + | |_^ 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..7a918909 --- /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` + --> $CARGO/cgp-field-$VERSION/src/impls/use_ref.rs + | + | 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 `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` + --> $CARGO/cgp-field-$VERSION/src/impls/use_ref.rs + | + | 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.rs b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs new file mode 100644 index 00000000..af10bdd9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs @@ -0,0 +1,15 @@ +use cgp::core::field::traits::{BuildField, HasBuilder}; +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..448e8e16 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr @@ -0,0 +1,13 @@ +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` + --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:14:10 + | +14 | .build_field(PhantomData::, "Bob".to_owned()); + | ^^^^^^^^^^^ 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:4:10 + | + 4 | #[derive(BuildField)] + | ^^^^^^^^^^ + = note: required for `__PartialPerson` to implement `cgp::macro_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_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..8bb0be31 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs @@ -0,0 +1,30 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{FinalizeBuild, HasBuilder}; +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..9410618d --- /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:28:10 + | +28 | .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:17:10 + | +17 | #[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..c2a35246 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs @@ -0,0 +1,25 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{FinalizeBuild, HasBuilder}; +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..c3bf7914 --- /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:20:10 + | +20 | .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:13:1 + | +13 | pub struct Employee { + | ^^^^^^^^^^^^^^^^^^^ +help: the following other types implement trait `UpdateField` + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs:14:9 + | +14 | pub first_name: String, + | ^^^^^^^^^^ `__PartialEmployee<__M1__, __F1__>` implements `UpdateField>>>>>>>>>>, __M2__>` +15 | 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_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..ba2a212a --- /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..028139b1 --- /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_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..56453f72 --- /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..c65ce714 --- /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 + --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | 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_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..f695f1db --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs @@ -0,0 +1,18 @@ +use cgp::core::field::traits::{BuildField, HasBuilder}; +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..ce3211b0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr @@ -0,0 +1,34 @@ +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:17: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::builder() +16 | .build_field(PhantomData::, "localhost".to_owned()) +17 | .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 + --> $CARGO/cgp-field-$VERSION/src/traits/transform_map.rs + | + | 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..454d197f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr @@ -0,0 +1,35 @@ +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 + --> $CARGO/cgp-field-$VERSION/src/traits/transform_map.rs + | + | 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_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..6569e7a4 --- /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..7c90521e --- /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/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..727a31b1 --- /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::macro_prelude::IsProviderFor>>>>, cgp::macro_prelude::PathCons>>, _, _>` for type `ShowString` + = note: downstream crates may implement trait `cgp::macro_prelude::IsProviderFor>>>>, cgp::macro_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..3f9ff7cf --- /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::macro_prelude::IsProviderFor` for type `cgp::macro_prelude::RedirectLookup>>>>, cgp::macro_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/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..bbcf0c67 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs @@ -0,0 +1,25 @@ +use cgp::core::component::DelegateComponent; +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..d1310cda --- /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:24:17 + | +16 | pub struct App; + | -------------- method `greet` not found for this struct because it doesn't satisfy `App: CanGreet` or `App: Greeter` +... +24 | 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:6:5 + | + 6 | 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:4:1 + | + 4 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 5 | pub trait CanGreet { + | ^^^^^^^^ +note: the trait `Greeter` must be implemented + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:5:1 + | + 5 | / pub trait CanGreet { + 6 | | fn greet(&self) -> String; + 7 | | } + | |_^ + = 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:5:1 + | + 5 | 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 + | +24 - let _ = App.greet(); +24 + 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/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..afbf6da4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs @@ -0,0 +1,28 @@ +use cgp::core::field::traits::{ExtractField, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(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..3d6dd294 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr @@ -0,0 +1,62 @@ +error[E0369]: binary operation `==` cannot be applied to type `Result>` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:24:5 + | +24 | / assert_eq!( +25 | | shape.to_extractor().extract_field(PhantomData::), +26 | | Ok(Circle { radius: 1.0 }) +27 | | ); + | | ^ + | | | + | |_____Result> + | Result> + | +note: an implementation of `PartialEq` might be missing for `__PartialShape` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:16:1 + | +16 | pub enum Shape { + | ^^^^^^^^^^^^^^ must implement `PartialEq` +help: consider annotating `__PartialShape` with `#[derive(PartialEq)]` + | +16 + #[derive(PartialEq)] +17 | pub enum Shape { + | + +error[E0277]: `__PartialShape` doesn't implement `Debug` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:24:5 + | +24 | / assert_eq!( +25 | | shape.to_extractor().extract_field(PhantomData::), +26 | | Ok(Circle { radius: 1.0 }) +27 | | ); + | |_____^ the trait `Debug` is not implemented for `__PartialShape` + | +help: the trait `Debug` is conditionally implemented for `Result` + --> $RUST/core/src/result.rs + ::: $RUST/core/src/result.rs + | + = note: unsatisfied requirement introduced here: `__PartialShape: Debug` +help: consider annotating `__PartialShape` with `#[derive(Debug)]` + | +16 + #[derive(Debug)] +17 | pub enum Shape { + | + +error[E0277]: `__PartialShape` doesn't implement `Debug` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:24:5 + | +24 | / assert_eq!( +25 | | shape.to_extractor().extract_field(PhantomData::), +26 | | Ok(Circle { radius: 1.0 }) +27 | | ); + | |_____^ the trait `Debug` is not implemented for `__PartialShape` + | +help: the trait `Debug` is conditionally implemented for `Result` + --> $RUST/core/src/result.rs + ::: $RUST/core/src/result.rs + | + = note: unsatisfied requirement introduced here: `__PartialShape: Debug` +help: consider annotating `__PartialShape` with `#[derive(Debug)]` + | +16 + #[derive(Debug)] +17 | 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..33ccfa6c --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs @@ -0,0 +1,27 @@ +use cgp::core::field::traits::{ExtractField, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +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..f4149641 --- /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:25:41 + | +25 | let _ = remainder.extract_field(PhantomData::); + | ------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `9`, found `6` + | | + | arguments to this method are incorrect + | + = note: expected struct `PhantomData>>>>>>>>>>` + found struct `PhantomData>>>>>>>` +note: method defined here + --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | fn extract_field(self, _tag: PhantomData) -> Result; + | ^^^^^^^^^^^^^ 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..f34bf9dd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs @@ -0,0 +1,45 @@ +use cgp::core::field::traits::FieldGetter; +use cgp::core::field::traits::HasField; +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..86cb8ab9 --- /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:41:9 + | +41 | 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:19:1 + | +19 | 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:39:1 + | +39 | / check_components! { +40 | | Account { +41 | | NameGetterComponent, +42 | | } +43 | | } + | |_^ 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/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..fe262409 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs @@ -0,0 +1,28 @@ +use cgp::core::field::traits::{ExtractField, FinalizeExtract, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +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..7353ae64 --- /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:26:37 + | +16 | pub enum Shape { + | -------------- method `finalize_extract` not found for this enum +... +26 | Err(remainder) => remainder.finalize_extract(), + | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` + | +note: the method `finalize_extract` exists on the type `::Map` + --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | 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: `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..8c2499b7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs @@ -0,0 +1,27 @@ +use cgp::core::field::traits::{ExtractField, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), +} + +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..94c123cc --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr @@ -0,0 +1,19 @@ +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:26:10 + | +23 | let _circle = shape +24 | .to_extractor() +25 | .extract_field(PhantomData::) +26 | .finalize_extract_result(); + | ^^^^^^^^^^^^^^^^^^^^^^^ method not found in `Result>` + | + ::: $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | 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..a89d998a --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs @@ -0,0 +1,29 @@ +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::core::field::traits::{ExtractField, HasExtractor}; +use cgp::prelude::*; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +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..e57b4446 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr @@ -0,0 +1,20 @@ +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:28:10 + | +17 | pub enum Shape { + | -------------- doesn't satisfy `__PartialShape: FinalizeExtract` +... +25 | let _rect = shape +26 | .to_extractor() +27 | .extract_field(PhantomData::) +28 | .finalize_extract_result(); + | ^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called due to unsatisfied trait bounds + | + = 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/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..af5c03c8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs @@ -0,0 +1,14 @@ +use cgp::core::field::traits::HasBuilder; +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..fa5a588a --- /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:13:32 + | + 6 | pub struct Context { + | ------------------ method `finalize_optional` not found for this struct +... +13 | 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/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..af965251 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs @@ -0,0 +1,28 @@ +use cgp::core::field::traits::FromVariant; +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..d4a8dc6f --- /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::macro_prelude::FromVariant>>>>>>>` for type `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs:15:5 + | +15 | Circle(Circle), + | ^^^^^^ conflicting implementation for `Shape` +... +20 | 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..82bac1b4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs @@ -0,0 +1,24 @@ +use cgp::core::field::traits::FromVariant; +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..80c14fb2 --- /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::macro_prelude::FromVariant>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:23:13 + | +23 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ^^^^^ unsatisfied trait bound + | +help: the trait `cgp::macro_prelude::FromVariant>>>>>>>` is not implemented for `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:16:1 + | +16 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: `Shape` implements trait `cgp::macro_prelude::FromVariant` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:17:5 + | +17 | Circle(Circle), + | ^^^^^^ `cgp::macro_prelude::FromVariant>>>>>>>` +18 | Rectangle(Rectangle), + | ^^^^^^^^^ `cgp::macro_prelude::FromVariant>>>>>>>>>>` + +error[E0277]: the trait bound `Shape: cgp::macro_prelude::FromVariant>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:23:67 + | +23 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::macro_prelude::FromVariant>>>>>>>` is not implemented for `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:16:1 + | +16 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: `Shape` implements trait `cgp::macro_prelude::FromVariant` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:17:5 + | +17 | Circle(Circle), + | ^^^^^^ `cgp::macro_prelude::FromVariant>>>>>>>` +18 | Rectangle(Rectangle), + | ^^^^^^^^^ `cgp::macro_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..1d4bf3b5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs @@ -0,0 +1,24 @@ +use cgp::core::field::traits::FromVariant; +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..a7585c69 --- /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:23:33 + | +23 | 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::macro_prelude::FromVariant<_>` found + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs:17:5 + | +17 | Circle(Circle), + | ^^^^^^ +18 | Rectangle(Rectangle), + | ^^^^^^^^^ +help: consider specifying a concrete type for the type parameter `T` + | +23 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ++++++++++++++ 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..2a52de19 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs @@ -0,0 +1,22 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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..7e1f858d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `FooBar: HasFields` is not satisfied + --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:19:10 + | +19 | .build_from(FooBar { foo: 1 }) + | ^^^^^^^^^^ 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:6:1 + | + 6 | 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..09a309c1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs @@ -0,0 +1,15 @@ +use cgp::core::field::traits::{BuildField, FinalizeBuild, HasBuilder}; +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..c54ebd90 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.stderr @@ -0,0 +1,14 @@ +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:14:10 + | + 5 | pub struct Person { + | ----------------- method `finalize_build` not found for this struct +... +12 | let person: Person = Person::builder() +13 | .build_field(PhantomData::, "Alice".to_owned()) +14 | .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: `FinalizeBuild` 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..8883cec6 --- /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::macro_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::macro_prelude::HasField for Context + where ::Target == Target, >::Value == Value, Context: cgp::cgp_core::cgp_field::traits::has_field::DerefMap, Target: cgp::macro_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..39c50018 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs @@ -0,0 +1,23 @@ +use cgp::core::field::traits::HasField; +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..6d628ee3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr @@ -0,0 +1,19 @@ +error[E0277]: the trait bound `Person: cgp::macro_prelude::HasField>>>>>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:22:29 + | +22 | 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:15:9 + | +15 | pub firstName: String, + | ^^^^^^^^^ +note: required by a bound in `read_first_name` + --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:6:14 + | + 4 | pub fn read_first_name(context: &Context) -> &String + 5 | where + 6 | 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..4913f7f6 --- /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..df0fe162 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs @@ -0,0 +1,32 @@ +use cgp::core::component::IsProviderFor; +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..434de1f4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.stderr @@ -0,0 +1,42 @@ +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:26:5 + | +26 | 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:15:1 + | +15 | / impl AreaCalculator { +16 | | fn area(&self, rectangle: &Rectangle) -> f64 { +17 | | rectangle.width * rectangle.height +18 | | } +19 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `(Rectangle,)` + +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:31:5 + | +31 | 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:15:1 + | +15 | / impl AreaCalculator { +16 | | fn area(&self, rectangle: &Rectangle) -> f64 { +17 | | rectangle.width * rectangle.height +18 | | } +19 | | } + | |_^ + = 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:26:20 + | +24 | fn assert_provider() +25 | where +26 | 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..cc08a5d4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs @@ -0,0 +1,15 @@ +use cgp::core::field::traits::HasField; +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..51d4465f --- /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:10:5 + | + 5 | pub fn inner_name(context: &Context) -> &String + | -------- the parameter type `Inner` must be valid for the anonymous lifetime defined here... +... +10 | / context +11 | | .get_field(PhantomData::) + | |___________________________________________________^ ...so that the type `Inner` will meet its required lifetime bounds + | +help: consider adding an explicit lifetime bound + | + 5 ~ pub fn inner_name<'a, Context, Inner>(context: &'a Context) -> &'a String + 6 | where + 7 | Context: HasField, + 8 ~ 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:10:5 + | + 5 | pub fn inner_name(context: &Context) -> &String + | -------- the parameter type `Inner` must be valid for the anonymous lifetime defined here... +... +10 | / context +11 | | .get_field(PhantomData::) +12 | | .get_field(PhantomData::) + | |__________________________________________________^ ...so that the type `Inner` will meet its required lifetime bounds + | +help: consider adding an explicit lifetime bound + | + 5 ~ pub fn inner_name<'a, Context, Inner>(context: &'a Context) -> &'a String + 6 | where + 7 | Context: HasField, + 8 ~ Inner: HasField + 'a, + | 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..da29acb1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs @@ -0,0 +1,8 @@ +use cgp::core::field::impls::IsPresent; +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..8b9e1c3f --- /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:6:64 + | +6 | pub type Mapped = >::Output; + | ^^^^^^ not found in `MapFields` + | +note: associated type `Mapped` defined here + --> $CARGO/cgp-field-$VERSION/src/traits/map_fields.rs + | + | type Mapped; + | ^^^^^^^^^^^ +help: maybe you meant this associated type + | +6 - pub type Mapped = >::Output; +6 + pub type Mapped = >::Mapped; + | 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..2e4026cd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs @@ -0,0 +1,14 @@ +use cgp::core::field::traits::HasBuilder; +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..9673b630 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr @@ -0,0 +1,29 @@ +error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:13:32 + | +13 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); + | ^^^ 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:5:10 + | + 5 | #[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:13:32 + | +13 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); + | ^^^ 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:5:10 + | + 5 | #[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/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..876ad65e --- /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::core::field::types::Nil; + +// 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..f4e29df0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr @@ -0,0 +1,17 @@ +error[E0277]: the trait bound `cgp::macro_prelude::Chars<'a', 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; + | ^^^^^^^^^^^^^^^ the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::macro_prelude::Chars<'a', Nil>` + | +help: the following other types implement trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` + --> $CARGO/cgp-field-$VERSION/src/traits/static_string.rs + | + | / impl StaticBytes for Symbol + | | where + | | Chars: MaybeChars, + | |______________________^ `Symbol` +... + | impl StaticBytes for Nil { + | ^^^^^^^^^^^^^^^^^^^^^^^^ `Nil` + = note: required for `cgp::macro_prelude::Chars<'a', Nil>` to implement `StaticString` 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..01c087a2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs @@ -0,0 +1,14 @@ +use cgp::core::field::traits::HasBuilder; +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..0397aa6b --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr @@ -0,0 +1,13 @@ +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` + --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:13:31 + | +13 | let _ = Person::builder().take_field(PhantomData::); + | ^^^^^^^^^^ 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:5:10 + | + 5 | #[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..52592c61 --- /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 + --> $CARGO/cgp-field-$VERSION/src/traits/transform_map.rs + | + | 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/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..65e6da18 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs @@ -0,0 +1,25 @@ +use cgp::core::field::impls::IsNothing; +use cgp::core::field::impls::IsPresent; +use cgp::core::field::traits::{BuildField, HasBuilder}; +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..d5103003 --- /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:24:79 + | +24 | 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 `IsNothing` + --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:16:10 + | +16 | #[derive(CgpData)] + | ^^^^^^^ + = note: required for `Cons>>>>, u16>, Cons>>>>>>>, bool>, Nil>>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialConfig, OnlyAbsent, 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:24:13 + | +24 | 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:10:1 + | +10 | impl TransformMap for OnlyAbsent { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `IsNothing`, found `IsPresent` + = note: required for `Cons>>>>, u16>, Cons>>>>>>>, bool>, Nil>>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialConfig, OnlyAbsent, 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..95b91dd5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs @@ -0,0 +1,22 @@ +use cgp::core::field::impls::IsPresent; +use cgp::core::field::traits::IntoBuilder; +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..71cc9d9b --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr @@ -0,0 +1,50 @@ +error[E0283]: type annotations needed for `__PartialPoint<_>` + --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:21:9 + | +21 | 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 + IsPresent + IsVoid + ToBuildAndMergeHandler + TryPromoteProviders + = 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:15:12 + | +15 | 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 + | +21 | 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:21:43 + | +21 | 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:8:1 + | + 8 | 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 + | +21 - let _ = Point { x: 1 }.into_builder().transform_map_fields(); +21 + let _ = <__PartialPoint as TransformMapFields>::transform_map_fields(Point { x: 1 }.into_builder()); + | 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..6813c32a --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs @@ -0,0 +1,15 @@ +use cgp::core::field::traits::HasBuilder; +use cgp::core::field::traits::UpdateField; +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..2dbe5011 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr @@ -0,0 +1,22 @@ +error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` + --> tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs:13:9 + | +13 | let (_old, _partial) = + | ^^^^^^^^^^^^^^^^ +14 | Person::builder().update_field(PhantomData::, "Alice".to_owned()); + | ------------ 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` + --> $CARGO/cgp-field-$VERSION/src/traits/update_field.rs + | + | pub trait UpdateField { + | ^^^^^^^ required by this bound in `UpdateField::update_field` +... + | fn update_field( + | +help: consider giving this pattern a type, where the type for type parameter `M` is specified + | +13 | let (_old, _partial): (_, __PartialPerson) = + | ++++++++++++++++++++++++++++ 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..9c5ad503 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs @@ -0,0 +1,13 @@ +use cgp::core::field::traits::{BuildField, HasBuilder}; +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..9e0ca1fd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr @@ -0,0 +1,19 @@ +error[E0277]: the trait bound `__PartialPerson: UpdateField>>>, IsPresent>` is not satisfied + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:12:31 + | +12 | let _ = Person::builder().build_field(PhantomData::, 42_u8); + | ^^^^^^^^^^^ 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:5:1 + | + 5 | pub struct Person { + | ^^^^^^^^^^^^^^^^^ +help: the following other types implement trait `UpdateField` + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:6:9 + | + 6 | pub first_name: String, + | ^^^^^^^^^^ `__PartialPerson<__M1__, __F1__>` implements `UpdateField>>>>>>>>>>, __M2__>` + 7 | pub last_name: String, + | ^^^^^^^^^ `__PartialPerson<__F0__, __M1__>` implements `UpdateField>>>>>>>>>, __M2__>` + = note: required for `__PartialPerson` to implement `cgp::macro_prelude::BuildField>>>>` 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..c62e1f12 --- /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..25e40f7f --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs @@ -0,0 +1,15 @@ +// 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::core::field::traits::HasField; +use cgp::core::field::types::Index; +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..0782834f --- /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::macro_prelude::HasField>` is not satisfied + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:12:12 + | +12 | *point.get_field(PhantomData::>) + | ^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::macro_prelude::HasField>` is not implemented for `Point` + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:9:1 + | + 9 | pub struct Point(pub f64, pub f64, pub f64); + | ^^^^^^^^^^^^^^^^ +help: `Point` implements trait `cgp::macro_prelude::HasField` + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:9:18 + | + 9 | pub struct Point(pub f64, pub f64, pub f64); + | ^^^ ^^^ ^^^ `cgp::macro_prelude::HasField>` + | | | + | | `cgp::macro_prelude::HasField>` + | `cgp::macro_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..9e9cd31f --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs @@ -0,0 +1,14 @@ +// 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::core::field::traits::HasField; +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..864ea900 --- /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::macro_prelude::HasField>>` is not satisfied + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:11:11 + | +11 | *pair.get_field(PhantomData::) + | ^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::macro_prelude::HasField>>` is not implemented for `Pair` + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:8:1 + | + 8 | pub struct Pair(pub u32, pub String); + | ^^^^^^^^^^^^^^^ +help: `Pair` implements trait `cgp::macro_prelude::HasField` + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:8:17 + | + 8 | pub struct Pair(pub u32, pub String); + | ^^^ ^^^ `cgp::macro_prelude::HasField>` + | | + | `cgp::macro_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_definition_invariant.rs b/example-code/tests/compile_fail/reference/types/life_definition_invariant.rs new file mode 100644 index 00000000..ee7a0930 --- /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::core::field::types::Life; + +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..cf51eb1a --- /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 `Life<'_>`, which makes the generic argument `'_` invariant + = note: the struct `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..9fc5f092 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.rs @@ -0,0 +1,25 @@ +// 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::core::field::types::Life; +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..3bde65e8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr @@ -0,0 +1,46 @@ +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 `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 +note: required because it appears within the type `Life<'static>` + --> $CARGO/cgp-field-$VERSION/src/types/life.rs + | + | 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:20:20 + | +20 | 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:24:20 + | +24 | 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 +note: required because it appears within the type `Life<'static>` + --> $CARGO/cgp-field-$VERSION/src/types/life.rs + | + | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); + | ^^^^ +note: required because it appears within the type `PhantomData>` + --> $RUST/core/src/marker.rs +note: required because it appears within the type `GetName<'static>` + --> tests/compile_fail/reference/types/life_definition_not_send.rs:13:16 + | +13 | #[cgp_impl(new GetName<'b>)] + | ^^^^^^^ required by this field +note: required by a bound in `require_send` + --> tests/compile_fail/reference/types/life_definition_not_send.rs:20:20 + | +20 | 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..c8088eb4 --- /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::core::field::types::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..e5cbf0d6 --- /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:57 + | +9 | fn greeting(&self) -> cgp::core::field::types::MRef<'_, String>; + | ^^ `'_` is a reserved lifetime name 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/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..9aa9e634 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs @@ -0,0 +1,19 @@ +// `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::core::field::traits::HasField; +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..efd9ebdb --- /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:15:33 + | +15 | 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` + | +15 | let name = person.get_field(PhantomData::); + | ++++++++++++++ + +error[E0283]: type annotations needed + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs:15:33 + | +15 | 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::macro_prelude::HasField<_>` found + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs:10:9 + | +10 | pub name: String, + | ^^^^ +11 | pub age: u8, + | ^^^ +help: consider specifying a concrete type for the type parameter `T` + | +15 | 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..17ad6f8b --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs @@ -0,0 +1,17 @@ +// 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::core::field::types::Either; +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..194b80b2 --- /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: `&Either::Right(Either::Right(_))` not covered + --> tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs:11:11 + | +11 | match token { + | ^^^^^ pattern `&Either::Right(Either::Right(_))` not covered + | +note: `Either>` defined here + --> $CARGO/cgp-field-$VERSION/src/types/sum.rs + | + | pub enum Either { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +... + | Right(Tail), + | ----- + | | + | not covered + | not covered + = note: the matched value is of type `&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 + | +13 ~ Either::Right(Either::Left(flag)) => format!("flag {flag}"), +14 ~ &Either::Right(Either::Right(_)) => todo!(), + | 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..a3392961 --- /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/compile_fail/tutorials/storage_backend_missing_field.rs b/example-code/tests/compile_fail/tutorials/storage_backend_missing_field.rs new file mode 100644 index 00000000..67cdd3d3 --- /dev/null +++ b/example-code/tests/compile_fail/tutorials/storage_backend_missing_field.rs @@ -0,0 +1,161 @@ +use std::collections::HashMap; +use std::path::Path; + +use anyhow::anyhow; +use cgp::prelude::*; + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct UserId(pub u64); + +#[derive(Clone)] +pub struct User { + pub name: String, + pub profile_picture_object_id: Option, +} + +#[derive(HasField)] +pub struct App { + pub database: HashMap, +} + +#[cgp_fn] +#[async_trait] +pub async fn get_user( + &self, + #[implicit] database: &HashMap, + user_id: &UserId, +) -> anyhow::Result { + database + .get(user_id) + .cloned() + .ok_or_else(|| anyhow!("no user with ID {}", user_id.0)) +} + +#[async_trait] +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +#[cgp_impl(new FetchLocalObject)] +impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) + } +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tokio::fs::create_dir_all("pictures").await?; + tokio::fs::write("pictures/alice.png", b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + }; + + match app.get_user_profile_picture(&UserId(1)).await? { + Some(picture) => println!("Found a {}-byte picture", picture.len()), + None => println!("No picture"), + } + + Ok(()) +} + +#[cgp_fn] +#[async_trait] +#[uses(GetUser, CanFetchStorageObject)] +pub async fn get_user_profile_picture( + &self, + user_id: &UserId, +) -> anyhow::Result>> { + let user = self.get_user(user_id).await?; + + match user.profile_picture_object_id { + Some(object_id) => Ok(Some(self.fetch_storage_object(&object_id).await?)), + None => Ok(None), + } +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchLocalObject, + } +} + +check_components! { + App { + StorageObjectFetcherComponent, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(HasField)] + pub struct TestApp { + pub database: HashMap, + pub objects: HashMap>, + } + + #[cgp_impl(new FetchMemoryObject)] + impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] objects: &HashMap>, + object_id: &str, + ) -> anyhow::Result> { + objects + .get(object_id) + .cloned() + .ok_or_else(|| anyhow!("no object named {object_id}")) + } + } + + delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchMemoryObject, + } + } + + check_components! { + TestApp { + StorageObjectFetcherComponent, + } + } + + #[tokio::test] + async fn fetches_the_picture_from_memory() -> anyhow::Result<()> { + let app = TestApp { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + objects: HashMap::from([("alice.png".to_owned(), b"fake image".to_vec())]), + }; + + let picture = app.get_user_profile_picture(&UserId(1)).await?; + assert_eq!(picture, Some(b"fake image".to_vec())); + + Ok(()) + } +} + +// `docs/tutorials/storage-backend.md`, *Check the wiring*: the page's finished `src/main.rs` with the +// `local_dir` field deleted from `App` and from `main`, as the page asks. `FetchLocalObject` still +// reads the field, so the check rejects `App`'s wiring. The comment sits at the end so the file's +// line numbers match the reader's. diff --git a/example-code/tests/compile_fail/tutorials/storage_backend_missing_field.stderr b/example-code/tests/compile_fail/tutorials/storage_backend_missing_field.stderr new file mode 100644 index 00000000..4f35d4c0 --- /dev/null +++ b/example-code/tests/compile_fail/tutorials/storage_backend_missing_field.stderr @@ -0,0 +1,60 @@ +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:98:9 + | + 98 | StorageObjectFetcherComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>>>>` is not implemented for `App` + but trait `HasField>>>>>>>>>` is implemented for it + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:18:9 + | + 18 | pub database: HashMap, + | ^^^^^^^^ +note: required for `FetchLocalObject` to implement `IsProviderFor` + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:40:1 + | + 40 | #[cgp_impl(new FetchLocalObject)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:96:1 + | + 96 | / check_components! { + 97 | | App { + 98 | | StorageObjectFetcherComponent, + 99 | | } +100 | | } + | |_^ 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[E0599]: the method `get_user_profile_picture` exists for struct `App`, but its trait bounds were not satisfied + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:67:15 + | +17 | pub struct App { + | -------------- method `get_user_profile_picture` not found for this struct because it doesn't satisfy `App: CanFetchStorageObject` or `App: GetUserProfilePicture` +... +67 | match app.get_user_profile_picture(&UserId(1)).await? { + | ^^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called on `App` due to unsatisfied trait bounds + | +note: trait bound `App: CanFetchStorageObject` was not satisfied + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:77:17 + | +75 | #[cgp_fn] + | --------- +76 | #[async_trait] +77 | #[uses(GetUser, CanFetchStorageObject)] + | ^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound introduced here +78 | pub async fn get_user_profile_picture( + | ------------------------ +note: the trait `CanFetchStorageObject` must be implemented + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:36:1 + | +36 | pub trait CanFetchStorageObject { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `GetUserProfilePicture` defines an item `get_user_profile_picture`, perhaps you need to implement it + --> tests/compile_fail/tutorials/storage_backend_missing_field.rs:75:1 + | +75 | #[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_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/tests/concepts/abstract_types.rs b/example-code/tests/concepts/abstract_types.rs new file mode 100644 index 00000000..46d636ca --- /dev/null +++ b/example-code/tests/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 trait +/// 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/tests/concepts/aggregate_providers.rs b/example-code/tests/concepts/aggregate_providers.rs new file mode 100644 index 00000000..e2c2910b --- /dev/null +++ b/example-code/tests/concepts/aggregate_providers.rs @@ -0,0 +1,219 @@ +//! 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. It is in the module +/// body below, since it compiles. +/// +/// The loud one. `RectangleArea` needs fields, and the check demands them of the bundle: +/// +/// 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 +/// +/// `#[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/tests/concepts/check_traits.rs b/example-code/tests/concepts/check_traits.rs new file mode 100644 index 00000000..51b7c48e --- /dev/null +++ b/example-code/tests/concepts/check_traits.rs @@ -0,0 +1,157 @@ +//! Code from `docs/concepts/check-traits.md` — *Checking your wiring*. + +/// ## A context can be wrong and still compile +/// +/// `FetchLocalObject` needs a `local_dir` 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 cgp::prelude::*; + + #[cgp_component(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } + } + + #[derive(HasField)] + pub struct BrokenApp { + pub bucket_id: String, + } + + // Accepted. The table records a choice; it does not verify one. + delegate_components! { BrokenApp { StorageObjectFetcherComponent: FetchLocalObject } } +} + +/// ## Where the failure surfaces instead +/// +/// 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`. +/// +/// A check placed beside the wiring forces the same question at a line you chose. This one fails, +/// which is the point of it: +/// +/// 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 +/// +/// 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(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } + } + + #[derive(HasField)] + pub struct App { + pub local_dir: String, + } + + delegate_components! { App { StorageObjectFetcherComponent: FetchLocalObject } } + + // The plain-Rust version: nothing to prove in the body, so it compiles exactly when the + // supertrait holds. + trait CanUseApp: CanFetchStorageObject {} + impl CanUseApp for App {} + + // What `check_components!` writes instead, which reports the missing requirement rather than + // only that the trait is unavailable. + mod generated_form { + use super::*; + check_components! { + App { + StorageObjectFetcherComponent, + } + } + } +} + +/// ## 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/tests/concepts/coherence.rs b/example-code/tests/concepts/coherence.rs new file mode 100644 index 00000000..e0c5cbe9 --- /dev/null +++ b/example-code/tests/concepts/coherence.rs @@ -0,0 +1,90 @@ +//! Code from `docs/concepts/coherence.md` — *Bypassing coherence*. + +/// ## The trait system is already a dependency-injection mechanism +pub mod trait_system_as_dependency_injection { + 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 +/// +/// 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 +/// ## Selecting one provider for each type +pub mod the_move { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self) -> Vec; + } + + #[cgp_impl(new EncodeAsText)] + #[uses(Display)] + impl Encoder { + fn encode(&self) -> Vec { + self.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeAsHex)] + #[uses(AsRef<[u8]>)] + impl Encoder { + fn encode(&self) -> Vec { + self.as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } + + delegate_components! { String { EncoderComponent: EncodeAsText } } + delegate_components! { Vec { EncoderComponent: EncodeAsHex } } + + mod check_string { + use super::*; + check_components! { String { EncoderComponent } } + } + + mod check_bytes { + use super::*; + 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"); + assert_eq!(b"hi".to_vec().encode(), b"6869"); + } +} diff --git a/example-code/tests/concepts/consumer_and_provider_traits.rs b/example-code/tests/concepts/consumer_and_provider_traits.rs new file mode 100644 index 00000000..5ff71185 --- /dev/null +++ b/example-code/tests/concepts/consumer_and_provider_traits.rs @@ -0,0 +1,284 @@ +//! Code from `docs/concepts/consumer-and-provider-traits.md` — *Consumer and provider traits*. +//! +//! 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. The page's S3 +//! client is a stand-in defined below, because the page shows only its type. + +/// Stand-in for the AWS SDK's S3 client, which the page names as `aws_sdk_s3::Client`. +pub mod aws_sdk_s3 { + pub struct Client; +} + +/// ## 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 there; without them +/// the failure would be an unresolved name rather than the overlap it is meant to show: +/// +/// 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 super::aws_sdk_s3; + + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + pub struct TestApp { + pub local_dir: String, + } + + impl CanFetchStorageObject for App { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + // fetch `object_id` from `self.bucket_id` through `self.storage_client` + // The page elides the request; the stand-in client has none to make. + let _ = (&self.storage_client, &self.bucket_id, object_id); + Ok(Vec::new()) + } + } + + impl CanFetchStorageObject for TestApp { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(std::fs::read(format!("{}/{object_id}", self.local_dir))?) + } + } +} + +/// ## 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 CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + // what implementations target + pub trait StorageObjectFetcher { + fn fetch_storage_object( + context: &Context, + object_id: &str, + ) -> anyhow::Result>; + } + + pub trait HasS3Client {} + pub trait HasLocalDir {} + + pub struct FetchS3Object; + pub struct FetchLocalObject; + + impl StorageObjectFetcher for FetchS3Object { + fn fetch_storage_object(context: &Context, object_id: &str) -> anyhow::Result> { + Ok(Vec::new()) + } + } + + impl StorageObjectFetcher for FetchLocalObject { + fn fetch_storage_object(context: &Context, object_id: &str) -> anyhow::Result> { + Ok(Vec::new()) + } + } +} + +/// ## 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::core::component::DelegateComponent; + use cgp::core::component::IsProviderFor; + use cgp::prelude::*; + + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + pub trait StorageObjectFetcher: + IsProviderFor + { + fn fetch_storage_object( + context: &Context, + object_id: &str, + ) -> anyhow::Result>; + } + + // The key. The page calls it "a marker generated alongside the two traits". + pub struct StorageObjectFetcherComponent; + + pub struct FetchS3Object; + pub struct FetchLocalObject; + + impl StorageObjectFetcher for FetchS3Object { + fn fetch_storage_object(context: &Context, object_id: &str) -> anyhow::Result> { + Ok(b"s3".to_vec()) + } + } + + impl StorageObjectFetcher for FetchLocalObject { + fn fetch_storage_object(context: &Context, object_id: &str) -> anyhow::Result> { + Ok(b"local".to_vec()) + } + } + + // Provider macros generate these checking implementations with the provider's bounds. + impl IsProviderFor for FetchS3Object {} + impl IsProviderFor for FetchLocalObject {} + + pub struct App; + pub struct TestApp; + + delegate_components! { App { StorageObjectFetcherComponent: FetchS3Object } } + delegate_components! { TestApp { StorageObjectFetcherComponent: FetchLocalObject } } + + // The first generated implementation: a context that implements the provider trait for itself + // gets the consumer trait. + impl CanFetchStorageObject for Context + where + Context: StorageObjectFetcher, + { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Context::fetch_storage_object(self, object_id) + } + } + + // The second: anything with a table entry inherits the provider trait from what the entry names. + impl StorageObjectFetcher for Provider + where + Provider: DelegateComponent + + IsProviderFor, + Provider::Delegate: StorageObjectFetcher, + { + fn fetch_storage_object( + context: &Context, + object_id: &str, + ) -> anyhow::Result> { + Provider::Delegate::fetch_storage_object(context, object_id) + } + } + + /// 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::(); + + assert_eq!(App.fetch_storage_object("alice.png").unwrap(), b"s3"); + assert_eq!(TestApp.fetch_storage_object("alice.png").unwrap(), b"local"); + } +} + +/// ## 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 cgp::prelude::*; + + use super::aws_sdk_s3; + + #[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // fetch `object_id` from `bucket_id` through `storage_client` + // The page elides the request; the stand-in returns the object's address instead. + let _ = storage_client; + Ok(format!("s3://{bucket_id}/{object_id}").into_bytes()) + } + } + + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } + } + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + #[derive(HasField)] + pub struct TestApp { + pub local_dir: String, + } + + delegate_components! { App { StorageObjectFetcherComponent: FetchS3Object } } + delegate_components! { TestApp { StorageObjectFetcherComponent: FetchLocalObject } } + + mod check_app { + use super::*; + check_components! { App { StorageObjectFetcherComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { StorageObjectFetcherComponent } } + } + + pub fn fetch_profile_picture( + app: &impl CanFetchStorageObject, + object_id: &str, + ) -> anyhow::Result> { + app.fetch_storage_object(object_id) + } + + /// A generic caller needs only the consumer trait, while each context's selected provider + /// reads its own fields. + #[test] + fn generic_caller_uses_each_selected_provider() { + let dir = std::env::temp_dir().join("cgp-consumer-and-provider-traits"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("alice.png"), b"picture").unwrap(); + + let test_app = TestApp { + local_dir: dir.to_str().unwrap().to_owned(), + }; + assert_eq!(fetch_profile_picture(&test_app, "alice.png").unwrap(), b"picture"); + + let app = App { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + assert_eq!( + fetch_profile_picture(&app, "alice.png").unwrap(), + b"s3://pictures/alice.png" + ); + } +} diff --git a/example-code/tests/concepts/dispatching.rs b/example-code/tests/concepts/dispatching.rs new file mode 100644 index 00000000..2b6f6d2f --- /dev/null +++ b/example-code/tests/concepts/dispatching.rs @@ -0,0 +1,131 @@ +//! 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; + 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 { + open ComputerComponent; + + ErrorTypeProviderComponent: UseType, + + // 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, + } + } + + 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/tests/concepts/extensible_records.rs b/example-code/tests/concepts/extensible_records.rs new file mode 100644 index 00000000..75035bef --- /dev/null +++ b/example-code/tests/concepts/extensible_records.rs @@ -0,0 +1,96 @@ +//! 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::core::field::traits::HasFields; + use cgp::core::field::types::Field; + 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< + Fields = Product![Field, Field], + >, + { + } + + 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 +pub mod building_one_field_at_a_time { + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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. +/// +/// 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/tests/concepts/extensible_variants.rs b/example-code/tests/concepts/extensible_variants.rs new file mode 100644 index 00000000..aca5b70f --- /dev/null +++ b/example-code/tests/concepts/extensible_variants.rs @@ -0,0 +1,165 @@ +//! 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::core::field::traits::HasFields; + use cgp::core::field::types::Field; + 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::(); + } + + /// 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 +pub mod one_handler_per_variant { + use core::convert::Infallible; + use core::fmt::Display; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::core::field::types::Field; + 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), + } + + // 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/tests/concepts/handlers.rs b/example-code/tests/concepts/handlers.rs new file mode 100644 index 00000000..26a6583c --- /dev/null +++ b/example-code/tests/concepts/handlers.rs @@ -0,0 +1,215 @@ +//! 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::extra::handler::AsyncComputer; + use cgp::extra::handler::Computer; + use cgp::extra::handler::Handler; + use cgp::extra::handler::TryComputer; + 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::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, + 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::core::field::traits::HasField; + 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/tests/concepts/higher_order_providers.rs b/example-code/tests/concepts/higher_order_providers.rs new file mode 100644 index 00000000..e15535e4 --- /dev/null +++ b/example-code/tests/concepts/higher_order_providers.rs @@ -0,0 +1,301 @@ +//! 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::core::component::UseContext; + 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::core::field::traits::HasField; + 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/tests/concepts/impl_side_dependencies.rs b/example-code/tests/concepts/impl_side_dependencies.rs new file mode 100644 index 00000000..d913a190 --- /dev/null +++ b/example-code/tests/concepts/impl_side_dependencies.rs @@ -0,0 +1,271 @@ +//! 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()) + } + } + + // Generic callers can require `CanGreet` without repeating `HasName`. + 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 cgp::prelude::*; + + /// Stand-in for the AWS SDK's S3 client, which the page names as `aws_sdk_s3::Client`. + pub mod aws_sdk_s3 { + pub struct Client; + } + + #[cgp_component(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + // The page names these getters and their methods in prose without declaring them. + #[cgp_auto_getter] + pub trait HasS3Bucket { + fn storage_client(&self) -> &aws_sdk_s3::Client; + + fn bucket_id(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasLocalDir { + fn local_dir(&self) -> &str; + } + + #[cgp_impl(new FetchS3Object)] + #[uses(HasS3Bucket)] + impl StorageObjectFetcher { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + // The page elides the request; the stand-in returns the object's address instead. + let _ = self.storage_client(); + Ok(format!("s3://{}/{object_id}", self.bucket_id()).into_bytes()) + } + } + + #[cgp_impl(new FetchLocalObject)] + #[uses(HasLocalDir)] + impl StorageObjectFetcher { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(std::fs::read(format!("{}/{object_id}", self.local_dir()))?) + } + } + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + #[derive(HasField)] + pub struct TestApp { + pub local_dir: String, + } + + delegate_components! { App { StorageObjectFetcherComponent: FetchS3Object } } + delegate_components! { TestApp { StorageObjectFetcherComponent: FetchLocalObject } } + + mod check_app { + use super::*; + check_components! { App { StorageObjectFetcherComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { StorageObjectFetcherComponent } } + } + + /// 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 load_picture(context: &Context) -> anyhow::Result> + where + Context: CanFetchStorageObject, + { + context.fetch_storage_object("alice.png") + } + + #[test] + fn one_bound_accepts_both_contexts() { + let dir = std::env::temp_dir().join("cgp-impl-side-dependencies"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("alice.png"), b"picture").unwrap(); + + let test_app = TestApp { + local_dir: dir.to_str().unwrap().to_owned(), + }; + assert_eq!(load_picture(&test_app).unwrap(), b"picture"); + + let app = App { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + assert_eq!(load_picture(&app).unwrap(), b"s3://pictures/alice.png"); + } +} + +/// ## 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 { + 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 } } + } +} + +/// ## Keeping type choices on the context +/// +/// 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; + } + + pub trait Runtime { + type Error; + } + + pub fn run_job(store: &S, runtime: &R) -> Result<(), E> + where + E: From + From, + R: Runtime, + S: Store, + { + // The page omits the job execution body. + Ok(()) + } + + // 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, + R: Runtime, + S: Store, + { + run_job(store, runtime) + } +} + +/// ## Keeping type choices on the context +/// +/// 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; + 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 forwarding operation shares the context's error and requires `CanRunJob` on its impl. + #[cgp_fn] + #[uses(CanRunJob)] + #[use_type(HasErrorType.Error)] + pub fn run_jobs(&self) -> Result<(), Error> { + self.run_job()?; + self.run_job() + } + + pub fn run_batch(context: &Context) -> Result<(), Context::Error> + where + Context: RunJobs, + { + context.run_jobs() + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + JobRunnerComponent: RunJobOnce, + } + } + + mod check_app { + use super::*; + check_components! { App { JobRunnerComponent } } + } + + #[test] + fn the_forwarder_uses_the_contexts_shared_error_type() { + let result: Result<(), String> = run_batch(&App); + assert!(result.is_ok()); + } +} diff --git a/example-code/tests/concepts/implicit_arguments.rs b/example-code/tests/concepts/implicit_arguments.rs new file mode 100644 index 00000000..116924cb --- /dev/null +++ b/example-code/tests/concepts/implicit_arguments.rs @@ -0,0 +1,198 @@ +//! 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::core::field::traits::HasField; + 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 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. +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`: any field implementing `AsRef`, 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/tests/concepts/mod.rs b/example-code/tests/concepts/mod.rs new file mode 100644 index 00000000..c8d92e9b --- /dev/null +++ b/example-code/tests/concepts/mod.rs @@ -0,0 +1,23 @@ +//! Code from the pages under `docs/concepts/`, one module per page. +//! +//! 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; +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 modularity_hierarchy; +pub mod monadic_handlers; +pub mod namespaces; +pub mod send_bounds; +pub mod type_level_dsls; diff --git a/example-code/tests/concepts/modular_error_handling.rs b/example-code/tests/concepts/modular_error_handling.rs new file mode 100644 index 00000000..8355493d --- /dev/null +++ b/example-code/tests/concepts/modular_error_handling.rs @@ -0,0 +1,217 @@ +//! 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 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. +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/tests/concepts/modularity_hierarchy.rs b/example-code/tests/concepts/modularity_hierarchy.rs new file mode 100644 index 00000000..3289939f --- /dev/null +++ b/example-code/tests/concepts/modularity_hierarchy.rs @@ -0,0 +1,237 @@ +//! Code from `docs/concepts/modularity-hierarchy.md` — *Modularity Hierarchy*. +//! +//! 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*. + +/// ## 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(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + #[cgp_impl(new FetchS3Object)] + impl StorageObjectFetcher { + // The page elides this body as `/* fetch the object from Amazon S3 */`. + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(Vec::new()) + } + } + + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + // The page elides this body as `/* read the object from a test's folder */`. + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + Ok(Vec::new()) + } + } + + pub struct App; + pub struct TestApp; + + delegate_components! { App { StorageObjectFetcherComponent: FetchS3Object } } + delegate_components! { TestApp { StorageObjectFetcherComponent: FetchLocalObject } } + + mod check_app { + use super::*; + check_components! { App { StorageObjectFetcherComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { StorageObjectFetcherComponent } } + } +} + +/// ## 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::core::component::UseContext; + use cgp::prelude::*; + + use super::tier_4::{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() { + use super::tier_4::CanEncodeValue; + + 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"); + } +} diff --git a/example-code/tests/concepts/monadic_handlers.rs b/example-code/tests/concepts/monadic_handlers.rs new file mode 100644 index 00000000..0c9c415b --- /dev/null +++ b/example-code/tests/concepts/monadic_handlers.rs @@ -0,0 +1,111 @@ +//! 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". +/// +/// 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 +pub mod chaining_through_the_err_monad { + #[test] + fn the_first_error_becomes_the_output() { + use cgp::extra::handler::Computer; + use cgp::prelude::*; + use super::{ErrMonadic, Increment, PipeMonadic}; + + 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::extra::handler::Computer; + 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/tests/concepts/namespaces.rs b/example-code/tests/concepts/namespaces.rs new file mode 100644 index 00000000..87e356ed --- /dev/null +++ b/example-code/tests/concepts/namespaces.rs @@ -0,0 +1,326 @@ +//! 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: +/// +/// 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: +/// +/// 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 +/// +/// 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/tests/concepts/send_bounds.rs b/example-code/tests/concepts/send_bounds.rs new file mode 100644 index 00000000..a92e1738 --- /dev/null +++ b/example-code/tests/concepts/send_bounds.rs @@ -0,0 +1,91 @@ +//! 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. +/// +/// 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 +/// +/// 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/tests/concepts/type_level_dsls.rs b/example-code/tests/concepts/type_level_dsls.rs new file mode 100644 index 00000000..2cf50721 --- /dev/null +++ b/example-code/tests/concepts/type_level_dsls.rs @@ -0,0 +1,88 @@ +//! 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_impl(new EvalAdd)] +#[uses(CanCompute, CanCompute)] +impl Computer, ()> { + type Output = u64; + + fn compute(&self, _code: PhantomData>, _input: ()) -> u64 { + self.compute(PhantomData::, ()) + self.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>>, ()), + ], + } + } +} + +/// The program structure selects providers statically; calling them evaluates the expression. +#[test] +fn the_program_type_selects_the_providers_that_compute_the_answer() { + // (2 + 3) * 4 + type Program = Multiply, Literal<3>>, Literal<4>>; + + assert_eq!(Interpreter.compute(PhantomData::, ()), 20); +} 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/tests/front_page.rs b/example-code/tests/front_page.rs new file mode 100644 index 00000000..6cd5b621 --- /dev/null +++ b/example-code/tests/front_page.rs @@ -0,0 +1,149 @@ +//! Runnable check for the code shown on the front page, `src/pages/index.tsx`. +//! +//! The front page belongs to no `docs/` section, so it gets its own test binary, as the Quickstart +//! does. The page's one compiling block is the hero's encoder pair under CGP. The rejected half of the +//! hero, the same pair without CGP, cannot compile, so it is a compile-fail fixture at +//! `tests/compile_fail/front_page/`. +//! +//! The text between each pair of `front-page:` marker comments is exactly what the page shows, so a +//! test can compare it with `index.tsx`. Everything outside the markers is what the page omits: the +//! imports and the checks. The rejected +//! block starts at its fixture's first line, so the page's quoted `E0119` names the lines the page +//! numbers; that fixture carries only the end marker. + +// The hero's CGP block. The page omits these two imports. +mod first_screen { + use cgp::prelude::*; + use core::fmt::Display; + + // front-page:cgp-block:begin + #[cgp_component(Encoder)] // generates the provider trait Encoder + pub trait CanEncode { + fn encode(&self) -> Vec; + } + + #[cgp_impl(new EncodeAsText)] // a provider: one named implementation + #[uses(Display)] + impl Encoder { + fn encode(&self) -> Vec { self.to_string().into_bytes() } + } + + #[cgp_impl(new EncodeAsBytes)] + #[uses(AsRef<[u8]>)] + impl Encoder { + fn encode(&self) -> Vec { self.as_ref().to_vec() } + } + + // Each type names the implementation it uses: + delegate_components! { u64 { EncoderComponent: EncodeAsText } } + delegate_components! { String { EncoderComponent: EncodeAsText } } + delegate_components! { Vec { EncoderComponent: EncodeAsBytes } } + // front-page:cgp-block:end + + // The page does not show checks; these prove each wiring resolves rather than merely parses. + check_components! { u64 { EncoderComponent } } + check_components! { String { EncoderComponent } } + check_components! { Vec { EncoderComponent } } + + // Property: for each wired type, `encode` runs the provider the wiring names. `u64` and `String` + // take `EncodeAsText`, which encodes the `Display` text; `Vec` takes `EncodeAsBytes`, which + // copies the bytes. `String` is the witness: it satisfies both bounds, so its result shows which + // provider the wiring chose. + #[test] + fn each_type_encodes_with_the_provider_it_names() { + assert_eq!(42u64.encode(), b"42"); + assert_eq!("hi".to_owned().encode(), b"hi"); + assert_eq!(vec![0xffu8, 0x00].encode(), vec![0xff, 0x00]); + } +} + +// Property: the text the page shows between each pair of `front-page:` markers equals the text this +// crate compiles between the same markers. The page keeps its blocks as template literals in +// `src/pages/index.tsx`, which no compiler reads, so without this check the page could drift from +// the code that proves it. +mod page_text { + use std::fs; + use std::path::Path; + + /// The lines strictly between `// front-page::begin` and `// front-page::end`. + fn region<'a>(source: &'a str, name: &str) -> Vec<&'a str> { + let begin = format!("// front-page:{name}:begin"); + let end = format!("// front-page:{name}:end"); + let lines: Vec<&str> = source.lines().collect(); + let start = lines.iter().position(|l| l.trim() == begin).expect("begin marker") + 1; + let stop = lines.iter().position(|l| l.trim() == end).expect("end marker"); + lines[start..stop].to_vec() + } + + /// The lines from the start of a file up to `// front-page::end`. + fn leading_region<'a>(source: &'a str, name: &str) -> Vec<&'a str> { + let end = format!("// front-page:{name}:end"); + let lines: Vec<&str> = source.lines().collect(); + let stop = lines.iter().position(|l| l.trim() == end).expect("end marker"); + lines[..stop].to_vec() + } + + /// A Rust region, with the indentation of the module it sits in removed. + fn rust_text(lines: &[&str]) -> String { + let indent = lines + .iter() + .filter(|l| !l.trim().is_empty()) + .map(|l| l.len() - l.trim_start().len()) + .min() + .unwrap_or(0); + lines + .iter() + .map(|l| if l.trim().is_empty() { "" } else { &l[indent..] }) + .collect::>() + .join("\n") + } + + /// The template literal a TSX region declares, with its escapes undone. + fn tsx_text(lines: &[&str]) -> String { + let joined = lines.join("\n"); + let open = joined.find('`').expect("opening backtick") + 1; + let close = joined.rfind('`').expect("closing backtick"); + joined[open..close].replace("\\`", "`").replace("\\$", "$").replace("\\\\", "\\") + } + + fn read(relative: &str) -> String { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative); + fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) + } + + #[test] + fn the_page_shows_the_code_this_crate_compiles() { + let page = read("../src/pages/index.tsx"); + let compiled = read("tests/front_page.rs"); + let rejected = read("tests/compile_fail/front_page/rust_accepts_only_one.rs"); + assert_eq!( + tsx_text(®ion(&page, "rejected-block")), + rust_text(&leading_region(&rejected, "rejected-block")), + "the page's `rejected-block` differs from the compiled code" + ); + assert_eq!( + tsx_text(®ion(&page, "cgp-block")), + rust_text(®ion(&compiled, "cgp-block")), + "the page's `cgp-block` differs from the compiled code" + ); + } + + // Property: the diagnostic the page quotes under the rejected block equals the compiler's output + // for that block, as the compile-fail snapshot records it, without the location line, which names + // the fixture's path rather than anything on the page. + #[test] + fn the_page_quotes_the_compiler_error() { + let page = read("../src/pages/index.tsx"); + let snapshot = read("tests/compile_fail/front_page/rust_accepts_only_one.stderr"); + let expected = snapshot + .lines() + .filter(|l| !l.trim_start().starts_with("--> ")) + .collect::>() + .join("\n"); + assert_eq!( + tsx_text(®ion(&page, "rejected-diagnostic")), + expected.trim_end(), + "the page's quoted diagnostic differs from the compile-fail snapshot" + ); + } +} diff --git a/example-code/tests/overview.rs b/example-code/tests/overview.rs new file mode 100644 index 00000000..d2f1b1d5 --- /dev/null +++ b/example-code/tests/overview.rs @@ -0,0 +1,323 @@ +//! Code from `docs/overview.md`, the feature tour. +//! +//! The Overview is a standalone page rather than a section, so it gets its own test binary, as the +//! Quickstart and the front page do. One module per key feature, in the page's order. The features +//! run the profile-picture scenario under the names the `cgp` README uses; the clients and +//! the pool are stand-ins defined below, because the page shows only their types. + +/// Stand-in for the AWS SDK's S3 client, which the page names as `aws_sdk_s3::Client`. +pub mod aws_sdk_s3 { + pub struct Client; + + impl Client { + pub fn get_object( + &self, + bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(format!("s3://{bucket_id}/{object_id}").into_bytes()) + } + } +} + +/// Stand-in for the Google Cloud Storage client, which the page names as +/// `google_cloud_storage::client::Storage`. +pub mod google_cloud_storage { + pub mod client { + pub struct Storage; + + impl Storage { + pub fn read_object( + &self, + bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(format!("gs://{bucket_id}/{object_id}").into_bytes()) + } + } + } +} + +/// ## One Interface, Many Implementations +pub mod one_interface_many_implementations { + use cgp::prelude::*; + + use super::{aws_sdk_s3, google_cloud_storage}; + + #[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // The page elides the request to Amazon S3. + storage_client.get_object(bucket_id, object_id) + } + } + + // The page names this provider in prose. + #[cgp_impl(new FetchGCloudObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] storage_client: &google_cloud_storage::client::Storage, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + storage_client.read_object(bucket_id, object_id) + } + } + + // The page names this provider in prose. + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + Ok(std::fs::read(format!("{local_dir}/{object_id}"))?) + } + } + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + #[derive(HasField)] + pub struct GCloudApp { + pub storage_client: google_cloud_storage::client::Storage, + pub bucket_id: String, + } + + #[derive(HasField)] + pub struct TestApp { + pub local_dir: String, + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } + } + + delegate_components! { + GCloudApp { + StorageObjectFetcherComponent: FetchGCloudObject, + } + } + + delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchLocalObject, + } + } + + mod check_contexts { + use super::*; + check_components! { App { StorageObjectFetcherComponent } } + check_components! { #[check_trait(CheckGCloudApp)] GCloudApp { StorageObjectFetcherComponent } } + check_components! { #[check_trait(CheckTestApp)] TestApp { StorageObjectFetcherComponent } } + } + + #[test] + fn each_context_fetches_through_its_own_provider() { + let app = App { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + let gcloud = GCloudApp { + storage_client: google_cloud_storage::client::Storage, + bucket_id: "pictures".to_owned(), + }; + let test = TestApp { + local_dir: env!("CARGO_MANIFEST_DIR").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() + ); + assert!(test.fetch_storage_object("Cargo.toml").is_ok()); + assert!(test.fetch_storage_object("no-such-object").is_err()); + } +} + +/// ## Zero-Cost Abstraction +/// +/// The page shows the impl that `App`'s wiring amounts to. It cannot sit beside the wiring, which +/// already implements the trait for `App`, so this module defines an unwired `App` of its own. +pub mod zero_cost_abstraction { + use cgp::prelude::*; + + use super::aws_sdk_s3; + use super::one_interface_many_implementations::{ + CanFetchStorageObject, FetchS3Object, StorageObjectFetcher, + }; + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + impl CanFetchStorageObject for App { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result> { + >::fetch_storage_object(self, object_id) + } + } + + #[test] + fn the_hand_written_impl_calls_the_provider() { + let app = App { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + assert_eq!( + app.fetch_storage_object("ada.png").unwrap(), + b"s3://pictures/ada.png".to_vec() + ); + } +} + +/// ## Type-Safe Wiring +/// +/// The page shows `App` without its `bucket_id` field, which the check rejects: the trybuild +/// fixture `tests/compile_fail/overview/type_safe_wiring_missing_field.rs`. Here the field is +/// present, so the same check passes. +pub mod type_safe_wiring { + use cgp::prelude::*; + + use super::aws_sdk_s3; + use super::one_interface_many_implementations::{FetchS3Object, StorageObjectFetcherComponent}; + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } + } + + check_components! { + App { + StorageObjectFetcherComponent, + } + } +} + +/// ## Abstract Over Every Dependency +pub mod abstract_over_every_dependency { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_component(StorageObjectFetcher)] + #[use_type(HasErrorType.Error)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> Result, Error>; + } + + #[cgp_impl(new FetchLocalObject)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> Result, Error> { + std::fs::read(format!("{local_dir}/{object_id}")).map_err(Self::raise_error) + } + } + + #[derive(HasField)] + pub struct TestApp { + pub local_dir: String, + } + + delegate_components! { + TestApp { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.std::io::Error: RaiseFrom, + StorageObjectFetcherComponent: FetchLocalObject, + } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { StorageObjectFetcherComponent } } + } + + #[test] + fn the_context_chooses_the_error_type() { + let test = TestApp { + local_dir: env!("CARGO_MANIFEST_DIR").to_owned(), + }; + assert!(test.fetch_storage_object("Cargo.toml").is_ok()); + let error: anyhow::Error = + test.fetch_storage_object("no-such-object").unwrap_err(); + assert!(error.downcast_ref::().is_some()); + } +} + +/// ## Still Ordinary Rust +pub mod still_ordinary_rust { + use cgp::prelude::*; + + /// Stand-in for the `sqlx` pool the page names. + pub struct PgPool; + + pub struct UserId(pub u64); + + pub struct User { + pub name: String, + pub profile_picture_object_id: Option, + } + + #[cgp_fn] + pub fn get_user( + &self, + #[implicit] database: &PgPool, + user_id: &UserId, + ) -> anyhow::Result { + // The page elides the query on `database`. + let _ = database; + Ok(User { + name: format!("user {}", user_id.0), + profile_picture_object_id: None, + }) + } + + #[derive(HasField)] + pub struct App { + pub database: PgPool, + } + + #[test] + fn a_context_with_the_field_gains_the_method() { + let app = App { database: PgPool }; + let user = app.get_user(&UserId(7)).unwrap(); + assert_eq!(user.name, "user 7"); + assert!(user.profile_picture_object_id.is_none()); + } +} diff --git a/example-code/tests/quickstart.rs b/example-code/tests/quickstart.rs new file mode 100644 index 00000000..9d48e5dc --- /dev/null +++ b/example-code/tests/quickstart.rs @@ -0,0 +1,49 @@ +//! 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, and `the_page_shows_this_program` holds the two equal. + +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(); +} + +/// The program between `use cgp::prelude::*;` and the end of this file, with the test's header put +/// back as the page's `fn main()`, must equal the page's `src/main.rs` block. +#[test] +fn the_page_shows_this_program() { + use std::fs; + use std::path::Path; + + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let page = fs::read_to_string(root.join("../docs/quickstart.md")).unwrap(); + let start = page.find("```rust title=\"src/main.rs\"\n").unwrap(); + let body = &page[start..]; + let body = &body[body.find('\n').unwrap() + 1..]; + let shown = &body[..body.find("```").unwrap()]; + + let source = fs::read_to_string(root.join("tests/quickstart.rs")).unwrap(); + let from = source.find("use cgp::prelude::*;").unwrap(); + let to = source.find("\n/// The program between").unwrap(); + let compiled = source[from..to].replace("#[test]\nfn quickstart_program_runs()", "fn main()"); + + assert_eq!(shown.trim_end(), compiled.trim_end()); +} 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..33e85b17 --- /dev/null +++ b/example-code/tests/reference/attributes/default_impl.rs @@ -0,0 +1,271 @@ +//! 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 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; + + 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_direct_entry_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<__Components__> AppNamespace<__Components__> 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!"); + } +} + +/// ## 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/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 new file mode 100644 index 00000000..a4ca0705 --- /dev/null +++ b/example-code/tests/reference/attributes/impl_generics.rs @@ -0,0 +1,230 @@ +//! 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!"); + } +} + +/// ## 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; + + 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::core::field::traits::HasField; + 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!"); + } +} + +/// ## 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!"); + } +} diff --git a/example-code/tests/reference/attributes/implicit.rs b/example-code/tests/reference/attributes/implicit.rs new file mode 100644 index 00000000..647f141f --- /dev/null +++ b/example-code/tests/reference/attributes/implicit.rs @@ -0,0 +1,403 @@ +//! 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::core::field::types::MRef; + 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 +/// `StorageObjectFetcher` component, the `App` context, and the S3 client 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, + } + + /// Stand-in for the AWS SDK's S3 client, which the page names as `aws_sdk_s3::Client`. + pub mod aws_sdk_s3 { + pub struct Client; + } + + #[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] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // fetch `object_id` from `bucket_id` through `storage_client` + // The page elides the request; the stand-in returns the object's address instead. + let _ = storage_client; + Ok(format!("s3://{bucket_id}/{object_id}").into_bytes()) + } + } + + #[derive(HasField)] + pub struct App { + pub storage_client: aws_sdk_s3::Client, + pub bucket_id: String, + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } + } + + check_components! { + App { + StorageObjectFetcherComponent, + } + } + + #[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 { + storage_client: aws_sdk_s3::Client, + bucket_id: "pictures".to_owned(), + }; + assert_eq!( + app.fetch_storage_object("alice.png").unwrap(), + b"s3://pictures/alice.png" + ); + } +} + +/// ## 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::core::field::traits::HasField; + 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 new file mode 100644 index 00000000..cfc1d548 --- /dev/null +++ b/example-code/tests/reference/attributes/mod.rs @@ -0,0 +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 new file mode 100644 index 00000000..5fab458d --- /dev/null +++ b/example-code/tests/reference/attributes/prefix.rs @@ -0,0 +1,354 @@ +//! 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::core::component::RedirectLookup; + 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!"); + } +} + +/// ## 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..d29c9567 --- /dev/null +++ b/example-code/tests/reference/attributes/use_provider.rs @@ -0,0 +1,283 @@ +//! 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::core::component::UseContext; + 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..8f3681e1 --- /dev/null +++ b/example-code/tests/reference/attributes/use_type.rs @@ -0,0 +1,486 @@ +//! 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 + } + + /// 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 { + 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!(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); + 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::core::field::traits::HasField; + 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()); + } +} diff --git a/example-code/tests/reference/components/can_raise_error.rs b/example-code/tests/reference/components/can_raise_error.rs new file mode 100644 index 00000000..5d693480 --- /dev/null +++ b/example-code/tests/reference/components/can_raise_error.rs @@ -0,0 +1,96 @@ +//! Code from `docs/reference/components/can_raise_error.md` — `CanRaiseError`. +//! +//! 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)] + #[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 { + 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 new file mode 100644 index 00000000..3aad4fa5 --- /dev/null +++ b/example-code/tests/reference/components/can_wrap_error.rs @@ -0,0 +1,89 @@ +//! Code from `docs/reference/components/can_wrap_error.md` — `CanWrapError`. +//! +//! 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. + +/// ## 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)] + #[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}")) + } + } + + #[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/handler/async_computer.rs b/example-code/tests/reference/components/handler/async_computer.rs new file mode 100644 index 00000000..a56a9b38 --- /dev/null +++ b/example-code/tests/reference/components/handler/async_computer.rs @@ -0,0 +1,144 @@ +//! 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 providers the page's Usage section lists: a promoted synchronous +//! computer, a `#[cgp_computer]` async function, and `UseField`. + +/// ## Usage +/// +/// A synchronous `Computer` answers the async slot through `PromoteAsync`. +pub mod usage { + use core::marker::PhantomData; + + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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); + } + + /// `#[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::core::field::impls::UseField; + use cgp::extra::handler::AsyncComputerComponent; + 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 +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::AsyncComputer; + use cgp::extra::handler::AsyncComputerComponent; + 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 + } + + #[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 new file mode 100644 index 00000000..f744342e --- /dev/null +++ b/example-code/tests/reference/components/handler/async_computer_ref.rs @@ -0,0 +1,104 @@ +//! 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, 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::AsyncComputerComponent; + use cgp::extra::handler::AsyncComputerRef; + use cgp::extra::handler::AsyncComputerRefComponent; + 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 { + use core::marker::PhantomData; + + use cgp::extra::handler::AsyncComputerRef; + use cgp::extra::handler::AsyncComputerRefComponent; + use cgp::extra::handler::CanComputeAsyncRef; + 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 { + 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 new file mode 100644 index 00000000..47dff4c9 --- /dev/null +++ b/example-code/tests/reference/components/handler/computer.rs @@ -0,0 +1,196 @@ +//! 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 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 +/// +/// 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; + use cgp::extra::handler::Computer; + use cgp::extra::handler::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 + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + @cgp.extra.handler.ComputerComponent: Double, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + 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::core::field::impls::UseField; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::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 + } + } + + 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 +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::PromoteComputer; + use cgp::extra::handler::TryComputerComponent; + 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::extra::handler::Computer; + use cgp::extra::handler::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 + } + } + + 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 new file mode 100644 index 00000000..76b47bcd --- /dev/null +++ b/example-code/tests/reference/components/handler/computer_ref.rs @@ -0,0 +1,90 @@ +//! Code from `docs/reference/components/handler/computer_ref.md` — `ComputerRef`. +//! +//! 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::ComputerComponent; + use cgp::extra::handler::ComputerRefComponent; + 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::extra::handler::ComputerRefComponent; + 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), + } + } + + #[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 new file mode 100644 index 00000000..3d7693d9 --- /dev/null +++ b/example-code/tests/reference/components/handler/handler.rs @@ -0,0 +1,60 @@ +//! Code from `docs/reference/components/handler/handler.md` — `Handler`. +//! +//! 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::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + 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: u64, + ) -> Result + where + 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 new file mode 100644 index 00000000..ffde4a9d --- /dev/null +++ b/example-code/tests/reference/components/handler/handler_ref.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/components/handler/handler_ref.md` — `HandlerRef`. +//! +//! 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::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::HandlerRefComponent; + use cgp::extra::handler::{CanHandleRef, HandlerRef}; + use cgp::prelude::*; + + #[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/mod.rs b/example-code/tests/reference/components/handler/mod.rs new file mode 100644 index 00000000..6dc3c2ea --- /dev/null +++ b/example-code/tests/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/tests/reference/components/handler/producer.rs b/example-code/tests/reference/components/handler/producer.rs new file mode 100644 index 00000000..5736205d --- /dev/null +++ b/example-code/tests/reference/components/handler/producer.rs @@ -0,0 +1,184 @@ +//! 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`, 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 +/// +/// 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::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + 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; + use cgp::extra::handler::Producer; + use cgp::extra::handler::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, + } + } + + check_components! { + App { + ProducerComponent: (), + } + } + + pub fn demo() { + assert_eq!(App.produce(PhantomData::<()>), 42); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## 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::ComputerComponent; + 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 +/// `#[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::extra::handler::ComputerComponent; + use cgp::extra::handler::Producer; + use cgp::extra::handler::ProducerComponent; + use cgp::extra::handler::PromoteProducer; + use cgp::extra::handler::TryComputerComponent; + 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 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 new file mode 100644 index 00000000..590939d4 --- /dev/null +++ b/example-code/tests/reference/components/handler/try_computer.rs @@ -0,0 +1,161 @@ +//! 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 Usage section's claims: the `#[cgp_computer]` function whose `Result` +//! output `TryPromote` reads, and `TryPromote` presenting a `TryComputer` as a `Computer`. + +/// ## 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::ComputerComponent; + use cgp::extra::handler::TryComputerComponent; + 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()) + ); + } + + /// `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::ComputerComponent; + use cgp::extra::handler::TryComputer; + use cgp::extra::handler::TryComputerComponent; + 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 +pub mod examples { + use core::marker::PhantomData; + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::CanTryCompute; + use cgp::extra::handler::TryComputer; + use cgp::extra::handler::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(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()); + } + + #[test] + 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 new file mode 100644 index 00000000..9bebbce0 --- /dev/null +++ b/example-code/tests/reference/components/handler/try_computer_ref.rs @@ -0,0 +1,70 @@ +//! Code from `docs/reference/components/handler/try_computer_ref.md` — `TryComputerRef`. +//! +//! 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::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::TryComputerRefComponent; + use cgp::extra::handler::{CanTryComputeRef, TryComputerRef}; + use cgp::prelude::*; + + #[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(); + } +} diff --git a/example-code/tests/reference/components/has_error_type.rs b/example-code/tests/reference/components/has_error_type.rs new file mode 100644 index 00000000..c60689a8 --- /dev/null +++ b/example-code/tests/reference/components/has_error_type.rs @@ -0,0 +1,69 @@ +//! 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]`. + +/// ## 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")) + } + + // `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}")) + } + + 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); + } +} + +/// ## 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, + } + } + + check_components! { + App { + ErrorTypeProviderComponent, + } + } +} diff --git a/example-code/tests/reference/components/has_runtime.rs b/example-code/tests/reference/components/has_runtime.rs new file mode 100644 index 00000000..8f88c68f --- /dev/null +++ b/example-code/tests/reference/components/has_runtime.rs @@ -0,0 +1,45 @@ +//! 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::core::field::impls::UseField; + 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/tests/reference/components/has_runtime_type.rs b/example-code/tests/reference/components/has_runtime_type.rs new file mode 100644 index 00000000..0f828d93 --- /dev/null +++ b/example-code/tests/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/tests/reference/components/has_type.rs b/example-code/tests/reference/components/has_type.rs new file mode 100644 index 00000000..d7b2fbff --- /dev/null +++ b/example-code/tests/reference/components/has_type.rs @@ -0,0 +1,72 @@ +//! 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::HasType; + 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() + } + + /// 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 + // `f64` for every tag, `ScalarTag` included. + assert_eq!(zero::(), 0.0); + } +} diff --git a/example-code/tests/reference/components/mod.rs b/example-code/tests/reference/components/mod.rs new file mode 100644 index 00000000..e2cca1cf --- /dev/null +++ b/example-code/tests/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/tests/reference/components/runner.rs b/example-code/tests/reference/components/runner.rs new file mode 100644 index 00000000..c5b6411a --- /dev/null +++ b/example-code/tests/reference/components/runner.rs @@ -0,0 +1,92 @@ +//! 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, 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. + +/// ## 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::*; + use futures::executor::block_on; + + // 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 + } + } + + check_components! { + App { + RunnerComponent: [ActionA, ActionB], + } + } + + #[test] + fn spawns_and_runs_a_task() { + let app = App; + block_on(app.run(PhantomData::)).unwrap(); + } +} diff --git a/example-code/tests/reference/components/send_runner.rs b/example-code/tests/reference/components/send_runner.rs new file mode 100644 index 00000000..e930de8e --- /dev/null +++ b/example-code/tests/reference/components/send_runner.rs @@ -0,0 +1,84 @@ +//! 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::*; + use futures::executor::block_on; + + // 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() { + let app = App; + block_on(app.run(PhantomData::)).unwrap(); + } +} diff --git a/example-code/tests/reference/derives/derive_build_field.rs b/example-code/tests/reference/derives/derive_build_field.rs new file mode 100644 index 00000000..0fee7f02 --- /dev/null +++ b/example-code/tests/reference/derives/derive_build_field.rs @@ -0,0 +1,259 @@ +//! 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. + +/// ## Overview +/// +/// The opening builder chain. The page shows it against `Person`, which it declares under *Usage*. +pub mod overview { + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::prelude::*; + + #[derive(BuildField, 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. +/// +/// 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 +/// 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. +/// +/// 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. +/// +/// 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 +/// +/// 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 usage { + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::types::Index; + use cgp::prelude::*; + + #[derive(BuildField, Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(BuildField, Debug, Eq, PartialEq)] + pub struct Pair(pub u32, pub u32); + + #[derive(BuildField, Debug, Eq, PartialEq)] + pub struct NoConfig {} + + #[derive(BuildField, 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::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasField; + use cgp::core::field::traits::IntoBuilder; + 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, Debug, Eq, PartialEq)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(BuildField, Debug, Eq, PartialEq)] + 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) + .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(), + } + ); + } +} + +/// ## 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::core::field::traits::FromVariant; + use cgp::core::field::traits::HasField; + 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); + } +} + +/// 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_data.rs b/example-code/tests/reference/derives/derive_cgp_data.rs new file mode 100644 index 00000000..dbb802f8 --- /dev/null +++ b/example-code/tests/reference/derives/derive_cgp_data.rs @@ -0,0 +1,155 @@ +//! Code from `docs/reference/derives/derive_cgp_data.md` — *`#[derive(CgpData)]`*. +//! +//! 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. + +/// ## 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 trybuild fixture, named in the module below this one. +pub mod usage { + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::FromFields; + use cgp::core::field::traits::FromVariant; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasField; + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Index; + 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, Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[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, Debug, Eq, PartialEq)] + pub struct RecordFace { + pub value: u32, + } + + #[derive(CgpVariant, Debug, Eq, PartialEq)] + pub enum VariantFace { + One(Circle), + } + + /// The degenerate struct shape: a parameterless companion, so `builder()` finalizes at once. + #[derive(CgpData, Debug, Eq, PartialEq)] + pub struct NoConfig {} + + /// A tuple struct, whose builder steps are keyed by position rather than by name. + #[derive(CgpData, 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. +/// +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs`. +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::core::field::traits::BuildField; + use cgp::core::field::traits::ExtractField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasExtractor; + 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/tests/reference/derives/derive_cgp_record.rs b/example-code/tests/reference/derives/derive_cgp_record.rs new file mode 100644 index 00000000..922368e3 --- /dev/null +++ b/example-code/tests/reference/derives/derive_cgp_record.rs @@ -0,0 +1,118 @@ +//! 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. + +/// ## 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::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasField; + use cgp::core::field::types::Index; + 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. +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::prelude::*; + + #[derive(CgpRecord, Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(CgpRecord, 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(), + } + ); + } +} + +/// ## Common Mistakes +/// +/// A single-field tuple struct's representation is the inner type, not a one-element product. +pub mod common_mistakes { + use cgp::core::field::traits::HasFields; + 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 new file mode 100644 index 00000000..3f18fbe7 --- /dev/null +++ b/example-code/tests/reference/derives/derive_cgp_variant.rs @@ -0,0 +1,140 @@ +//! 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. + +/// ## 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::core::field::traits::BuildField; + use cgp::core::field::traits::ExtractField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::FromVariant; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasExtractor; + 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. +/// +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs`. +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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractor; + 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 + ); + } +} + +/// 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::core::field::traits::FromVariant; + 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_extract_field.rs b/example-code/tests/reference/derives/derive_extract_field.rs new file mode 100644 index 00000000..6f8493a5 --- /dev/null +++ b/example-code/tests/reference/derives/derive_extract_field.rs @@ -0,0 +1,214 @@ +//! 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. + +/// ## Overview +/// +/// The opening extraction, and the payload types the page names without declaring. +pub mod overview { + use cgp::core::field::traits::ExtractField; + use cgp::core::field::traits::HasExtractor; + 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, 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()); + } +} + +/// ## Usage +/// +/// The accepted enum, the payload-struct rewrite the page recommends, and the variantless enum the +/// page says degenerates. +pub mod usage { + use cgp::core::field::traits::ExtractField; + use cgp::core::field::traits::HasExtractor; + use cgp::core::field::types::Nil; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + /// A unit variant is accepted as it stands: its payload is `Nil`. + #[derive(ExtractField, Debug, PartialEq)] + pub enum Shape { + Circle(Circle), + Empty, + } + + #[derive(ExtractField)] + pub enum Never {} + + #[derive(ExtractField)] + pub enum Generic { + Item(T), + } + + #[test] + 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 + .to_extractor() + .extract_field(PhantomData::) + .ok(); + + assert_eq!(extracted, Some(Nil)); + } + + /// `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) + .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. +/// +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs`. +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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractor; + use cgp::core::field::traits::HasExtractorMut; + use cgp::core::field::traits::HasExtractorRef; + 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, 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. +/// +/// 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/tests/reference/derives/derive_from_variant.rs b/example-code/tests/reference/derives/derive_from_variant.rs new file mode 100644 index 00000000..a0df9643 --- /dev/null +++ b/example-code/tests/reference/derives/derive_from_variant.rs @@ -0,0 +1,183 @@ +//! 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. + +/// ## Overview +/// +/// The opening claim: `from_variant` with a tag is the same construction as naming the variant. +pub mod overview { + use cgp::core::field::traits::FromVariant; + 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, 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 })); + } +} + +/// ## Usage +/// +/// The accepted enum, a generic one, and the variantless enum the page says produces no impls. +pub mod usage { + use cgp::core::field::traits::FromVariant; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Circle { + pub radius: u32, + } + + #[derive(FromVariant, Debug, Eq, PartialEq)] + pub enum Shape { + Circle(Circle), + } + + #[derive(FromVariant, 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. +/// +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs`. +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::core::field::traits::FromVariant; + 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, 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, Debug, PartialEq)] + pub enum LispSubExpr { + Ident(Ident), + } + + /// The full enum it is widened into. + #[derive(CgpData, Debug, PartialEq)] + pub enum LispExpr { + Ident(Ident), + 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; + + let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); + + assert_eq!(ident, LispExpr::Ident(Ident("+".to_owned()))); + } +} diff --git a/example-code/tests/reference/derives/derive_has_field.rs b/example-code/tests/reference/derives/derive_has_field.rs new file mode 100644 index 00000000..a389f750 --- /dev/null +++ b/example-code/tests/reference/derives/derive_has_field.rs @@ -0,0 +1,211 @@ +//! 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. + +/// ## 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. +pub mod overview { + use cgp::core::field::traits::HasField; + 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"); + } +} + +/// ## 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 +/// point is that it compiles and emits nothing. +pub mod usage { + use cgp::core::field::traits::HasField; + use cgp::core::field::types::Index; + 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, + } + + /// 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 { + 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::core::field::traits::HasField; + 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/tests/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs new file mode 100644 index 00000000..57574bed --- /dev/null +++ b/example-code/tests/reference/derives/derive_has_fields.rs @@ -0,0 +1,320 @@ +//! 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. + +/// ## Overview +/// +/// The `Fields` type the page opens on, checked by naming it explicitly. +pub mod overview { + use cgp::core::field::traits::FromFields; + use cgp::core::field::traits::HasFields; + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Field; + use cgp::prelude::*; + + #[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 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); + } +} + +/// ## 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. +pub mod usage { + use cgp::core::field::traits::FromFields; + use cgp::core::field::traits::HasFields; + use cgp::core::field::traits::HasFieldsRef; + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Field; + use cgp::core::field::types::Index; + use cgp::core::field::types::Nil; + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Named { + pub name: String, + pub age: u8, + } + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Tuple(pub u32, pub u32); + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Unit; + + /// The newtype special case: `Fields` is the inner type directly. + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Newtype(pub String); + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Generic { + 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 { + 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::core::field::traits::FromFields; + use cgp::core::field::traits::HasFields; + use cgp::core::field::traits::ToFields; + use cgp::core::field::traits::ToFieldsRef; + use cgp::core::field::types::Field; + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq, 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, HasFields)] + pub enum Shape { + Circle(Circle), + 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 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. + 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); + } +} + +/// ## 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::core::field::traits::HasFields; + use cgp::core::field::types::Void; + 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. +pub mod common_mistakes { + use cgp::core::field::traits::HasFields; + use cgp::core::field::types::Field; + 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 + } +} diff --git a/example-code/tests/reference/derives/mod.rs b/example-code/tests/reference/derives/mod.rs new file mode 100644 index 00000000..21d921ac --- /dev/null +++ b/example-code/tests/reference/derives/mod.rs @@ -0,0 +1,10 @@ +//! Code from the pages under `docs/reference/derives/`. + +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; +pub mod derive_has_fields; diff --git a/example-code/tests/reference/errors.rs b/example-code/tests/reference/errors.rs new file mode 100644 index 00000000..4a14498a --- /dev/null +++ b/example-code/tests/reference/errors.rs @@ -0,0 +1,72 @@ +//! 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 a trybuild fixture. +/// +/// 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`. +/// +/// 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. +/// +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/errors_the_fix_2.rs`. +pub mod the_fix {} 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..20484113 --- /dev/null +++ b/example-code/tests/reference/macros/async_trait.rs @@ -0,0 +1,196 @@ +//! 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; + } +} + +/// ## 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/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..f1dee64f --- /dev/null +++ b/example-code/tests/reference/macros/cgp_auto_dispatch.rs @@ -0,0 +1,339 @@ +//! 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, 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::*; + + #[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) + } + } + + /// 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"); + assert_eq!( + futures::executor::block_on(Token::Word(Word("abc".to_owned())).length()), + 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, 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::*; + + #[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" + } + } + + /// 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"); + } + + #[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/cgp_auto_getter.rs b/example-code/tests/reference/macros/cgp_auto_getter.rs new file mode 100644 index 00000000..bcd9c25c --- /dev/null +++ b/example-code/tests/reference/macros/cgp_auto_getter.rs @@ -0,0 +1,401 @@ +//! 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::core::field::types::MRef; + 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_component.rs b/example-code/tests/reference/macros/cgp_component.rs new file mode 100644 index 00000000..7cd6cdc7 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_component.rs @@ -0,0 +1,488 @@ +//! 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, + } + } + } +} + +/// ### Where the component key lives +/// +/// The module that re-exports the component's traits with its key, and a provider importing +/// both from it. The page names `components` without showing it. +pub mod where_the_component_key_lives { + pub mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + } + + pub mod shapes { + pub use super::components::{AreaCalculator, AreaCalculatorComponent, CanCalculateArea}; + } + + pub mod providers { + use cgp::prelude::*; + + use super::shapes::{AreaCalculator, AreaCalculatorComponent}; + + #[cgp_impl(new UnitArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + } + + use cgp::prelude::*; + + use shapes::{AreaCalculatorComponent, CanCalculateArea}; + + pub struct Unit; + + delegate_components! { + Unit { + AreaCalculatorComponent: providers::UnitArea, + } + } + + check_components! { + Unit { + AreaCalculatorComponent, + } + } + + #[test] + fn the_reexported_key_wires_the_provider() { + assert_eq!(Unit.area(), 1.0); + } +} + +/// ## 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_computer.rs b/example-code/tests/reference/macros/cgp_computer.rs new file mode 100644 index 00000000..da7a5055 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_computer.rs @@ -0,0 +1,296 @@ +//! 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`, and the +/// default for a raw function name. +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); + } + } + + /// 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; + + 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); + } + } + + /// 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 +/// +/// 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_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_getter.rs b/example-code/tests/reference/macros/cgp_getter.rs new file mode 100644 index 00000000..d1335489 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_getter.rs @@ -0,0 +1,334 @@ +//! 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::core::field::impls::UseField; + 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::core::component::UseFields; + 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::core::component::UseFields; + 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::core::component::UseFields; + 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::core::component::UseFields; + use cgp::core::component::WithProvider; + use cgp::core::field::impls::UseField; + 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::core::component::UseFields; + use cgp::core::field::impls::UseField; + 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_impl.rs b/example-code/tests/reference/macros/cgp_impl.rs new file mode 100644 index 00000000..07cb38b3 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_impl.rs @@ -0,0 +1,839 @@ +//! 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`. 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::*; + + #[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); + } +} + +/// ### Importing the component key +/// +/// A provider in another module than its component, importing the key beside the provider trait. +/// The page names `components` and `shapes` without showing them; they are declared here, with a +/// provider for each other form the page describes in prose: the trait named by its path, both +/// forms through a module that re-exports the trait and its key, and `Computer` from +/// `cgp::extra::handler` with its key. The modules nest here, so their paths start from `super::` +/// where the page writes `crate::`. The program without the import is the fixture +/// `tests/compile_fail/reference/macros/cgp_impl_importing_the_component_key.rs`. +pub mod importing_the_component_key { + pub mod components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + } + + pub mod shapes { + pub use super::components::{AreaCalculator, AreaCalculatorComponent}; + } + + pub mod providers { + use cgp::prelude::*; + + use super::components::{AreaCalculator, AreaCalculatorComponent}; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + } + + pub mod by_path { + use cgp::prelude::*; + + #[cgp_impl(new UnitArea)] + impl super::components::AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + #[cgp_impl(new HalfArea)] + impl super::shapes::AreaCalculator { + fn area(&self) -> f64 { + 0.5 + } + } + } + + pub mod through_shapes { + use cgp::prelude::*; + + use super::shapes::{AreaCalculator, AreaCalculatorComponent}; + + #[cgp_impl(new QuarterArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + 0.25 + } + } + } + + pub mod library_component { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[cgp_impl(new Double)] + impl Computer { + type Output = u64; + + fn compute(&self, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + } + + use core::marker::PhantomData; + + use cgp::extra::handler::{CanCompute, ComputerComponent}; + use cgp::prelude::*; + + use components::{AreaCalculatorComponent, CanCalculateArea}; + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: providers::RectangleArea, + ComputerComponent: library_component::Double, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + ComputerComponent: ((), u64), + } + } + + pub struct Unit; + delegate_components! { Unit { AreaCalculatorComponent: by_path::UnitArea } } + check_components! { Unit { AreaCalculatorComponent } } + + pub struct Half; + delegate_components! { Half { AreaCalculatorComponent: by_path::HalfArea } } + check_components! { Half { AreaCalculatorComponent } } + + pub struct Quarter; + delegate_components! { Quarter { AreaCalculatorComponent: through_shapes::QuarterArea } } + check_components! { Quarter { AreaCalculatorComponent } } + + #[test] + fn every_import_form_reaches_its_provider() { + let rect = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rect.area(), 12.0); + assert_eq!(rect.compute(PhantomData::<()>, 21), 42); + assert_eq!(Unit.area(), 1.0); + assert_eq!(Half.area(), 0.5); + assert_eq!(Quarter.area(), 0.25); + } +} + +/// ### 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::core::component::UseContext; + 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) + } + } + + /// `#[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, + }; + 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 < Self::LIMIT + } + } + + pub struct App; + + delegate_components! { + App { + RateLimiterComponent: AllowUnderLimit, + } + } + + check_components! { + App { + RateLimiterComponent, + } + } + + #[test] + fn the_blocks_own_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_namespace.rs b/example-code/tests/reference/macros/cgp_namespace.rs new file mode 100644 index 00000000..b114f2b7 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_namespace.rs @@ -0,0 +1,485 @@ +//! 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"); + } +} + +/// ### The rest of the body grammar +/// +/// The two shared forms the section says are worth writing in a namespace: `open`, which is +/// another spelling of `Component => @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 +/// 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, + } + } + } + } +} + +/// 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 +/// 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"); + } + } +} + +/// ## 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 +/// 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 +/// +/// 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`. +/// +/// 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`. +/// +/// 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`. +pub mod common_mistakes {} 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..10720755 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_producer.rs @@ -0,0 +1,195 @@ +//! 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`, and the default for a raw function name. +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); + } + } + + /// 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; + + 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); + } + } + + /// 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 +/// +/// 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/cgp_provider.rs b/example-code/tests/reference/macros/cgp_provider.rs new file mode 100644 index 00000000..0a4b4640 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_provider.rs @@ -0,0 +1,389 @@ +//! 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::core::field::types::Life; + 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::core::field::traits::HasField; + 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..c73d94d8 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_type.rs @@ -0,0 +1,330 @@ +//! 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 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] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } + + 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: f32, + pub height: f32, + } + + pub struct Circle { + pub radius: f32, + } + + #[cgp_impl(new RectangleArea)] + #[use_type(HasScalarType.Scalar)] + impl AreaCalculator + where + Scalar: From + Mul, + { + fn area(&self, shape: &Rectangle) -> Scalar { + Scalar::from(shape.width) * Scalar::from(shape.height) + } + } + + #[cgp_impl(new CircleArea)] + #[use_type(HasScalarType.Scalar)] + impl AreaCalculator + where + Scalar: From + Mul, + { + fn area(&self, shape: &Circle) -> Scalar { + 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 one_wiring_line_decides_the_scalar() { + assert_eq!(zero::(), 0.0f64); + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + 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 }); + } +} + +/// ## 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/check_components.rs b/example-code/tests/reference/macros/check_components.rs new file mode 100644 index 00000000..5ed6e98c --- /dev/null +++ b/example-code/tests/reference/macros/check_components.rs @@ -0,0 +1,337 @@ +//! 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 page's generic table: the providers are checked at every instantiation of `Gen`. + #[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::core::field::types::Life; + 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), + } + } + + #[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_and_check_components.rs b/example-code/tests/reference/macros/delegate_and_check_components.rs new file mode 100644 index 00000000..21cf44c3 --- /dev/null +++ b/example-code/tests/reference/macros/delegate_and_check_components.rs @@ -0,0 +1,615 @@ +//! 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::core::field::impls::UseField; + 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::core::field::impls::UseField; + 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::core::field::impls::UseField; + use cgp::core::field::types::Index; + 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 new file mode 100644 index 00000000..28ffbc66 --- /dev/null +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -0,0 +1,1099 @@ +//! 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 and Usage +/// +/// 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)] + 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. 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::core::field::types::Life; + use cgp::prelude::*; + + pub use super::overview::{AreaCalculatorComponent, CanCalculateArea, 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, + } + } + + #[derive(HasField)] + pub struct MyApp { + pub width: f64, + pub height: f64, + } + + delegate_components! { + MyApp { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent, + 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 + } + + // 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 { + 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 +/// +/// 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::overview::{AreaCalculatorComponent, CanCalculateArea, RectangleArea}; + + #[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 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 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! { + ScaledRectangle { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: ScaledGeometryComponents, + } + } + + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } + + #[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 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 App { + pub width: f64, + pub height: f64, + } + + delegate_components! { + App { + [AreaCalculatorComponent, PerimeterCalculatorComponent] => + @shared, + + @shared: RectangleGeometry, + } + } + + check_components! { + App { + 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 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::component::DelegateComponent; + use cgp::core::error::{ErrorRaiserComponent, ErrorWrapperComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + 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_impl(new SumAreas: ShapeAreaCalculatorComponent)] + impl ShapeAreaCalculator { + fn shape_area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + pub struct ShapeApp; + + delegate_components! { + ShapeApp { + ShapeAreaCalculatorComponent: SumAreas, + } + } + + check_components! { + ShapeApp { + ShapeAreaCalculatorComponent: Square, + } + } + + /// 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 SolidColor: ColorComponent)] + impl ColorProvider { + fn color(&self) -> &'static str { + "black" + } + } + + pub struct MyComponents; + + delegate_components! { + MyComponents { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + ColorComponent: SolidColor, + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ColorComponent, + ]: MyComponents, + } + } + + 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 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]` 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 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], + } + } + + #[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 WidthValue` alike. + pub struct WidthKey(pub PhantomData); + pub struct HeightKey; + pub struct HeightValue(pub PhantomData); + + delegate_components! { + new MyComponents { + WidthKey: UseDelegate { + HeightKey: HeightValue, + }>, + } + } + + 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 +/// +/// 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::*; + + #[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], + } + } + + /// The braced spelling of the header is the same statement. + pub struct BracedApp; + + delegate_components! { + BracedApp { + open { AreaCalculatorComponent }; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + check_components! { + BracedApp { + AreaCalculatorComponent: Rectangle, + } + } + + /// 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! { + ReferenceApp { + AreaCalculatorComponent: <'a> &'a Rectangle, + } + } + + pub mod later_parameters { + use cgp::extra::handler::{CanCompute, 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() { + let rectangle = || Rectangle { + width: 2.0, + height: 3.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 +/// +/// 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::*; + + pub use super::defining_the_target_at_the_same_time::{ + CanCalculatePerimeter, GeometryComponents, PerimeterCalculatorComponent, + }; + use super::the_key_forms::{ColorComponent, ColorProvider}; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle; + pub struct Circle; + pub struct Square; + pub struct Triangle; + + #[cgp_impl(new ShapeArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } + } + + #[cgp_impl(new PolygonArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 2.0 + } + } + + #[cgp_component { + provider: LabelProvider, + name: LabelComponent, + }] + pub trait HasLabel { + fn label(&self) -> &'static str; + } + + #[cgp_impl(new DefaultStyle: ColorComponent)] + impl ColorProvider { + fn color(&self) -> &'static str { + "black" + } + } + + #[cgp_impl(DefaultStyle: LabelComponent)] + impl LabelProvider { + fn label(&self) -> &'static str { + "shape" + } + } + + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + } + + delegate_components! { + App { + open AreaCalculatorComponent; + + PerimeterCalculatorComponent -> GeometryComponents, + + [ColorComponent, LabelComponent]: DefaultStyle, + + @AreaCalculatorComponent.{Rectangle, Circle}: + ShapeArea, + + @AreaCalculatorComponent.[Square, Triangle]: + PolygonArea, + } + } + + check_components! { + App { + AreaCalculatorComponent: [Rectangle, Circle, Square, Triangle], + 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 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::*; + + #[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()); + } + + #[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! { + 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 + } + + #[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); + } + + /// 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_shape_reaches_its_provider() { + let rectangle = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(MyApp.area(&rectangle), 6.0); + assert_eq!(MyApp.area(&Circle { radius: 1.0 }), core::f64::consts::PI); + } + } +} + +/// ## Under the hood +/// +/// 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 +/// +/// 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; + + delegate_components! { + new MyComponents { + ArrayKey: UseDelegate { + u32: RectangleArea, + }>, + } + } + + #[test] + 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/macros/enum.rs b/example-code/tests/reference/macros/enum.rs new file mode 100644 index 00000000..af0c4b93 --- /dev/null +++ b/example-code/tests/reference/macros/enum.rs @@ -0,0 +1,116 @@ +//! 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::core::field::types::Field; + use cgp::prelude::*; + + #[test] + fn the_shape_is_the_hand_written_variant_list() { + let _: PhantomData = + PhantomData::, Field]>; + } +} + +/// ## Usage +pub mod usage { + use cgp::core::field::traits::HasFields; + use cgp::core::field::types::Either; + use cgp::core::field::types::Field; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Void; + 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::]>; + } + + #[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 +pub mod examples { + use cgp::core::field::traits::FromFields; + use cgp::core::field::types::Either; + use cgp::core::field::types::Field; + 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::core::field::types::Either; + use cgp::core::field::types::Field; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Void; + 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 new file mode 100644 index 00000000..a620e297 --- /dev/null +++ b/example-code/tests/reference/macros/mod.rs @@ -0,0 +1,24 @@ +//! 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 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/path.rs b/example-code/tests/reference/macros/path.rs new file mode 100644 index 00000000..1d87bd39 --- /dev/null +++ b/example-code/tests/reference/macros/path.rs @@ -0,0 +1,170 @@ +//! 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::base::types::PathCons; + use cgp::core::error::ErrorRaiserComponent; + use cgp::core::field::types::Nil; + 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::base::types::PathCons; + use cgp::core::error::ErrorRaiserComponent; + use cgp::core::field::types::Nil; + 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::core::base::types::PathCons; + use cgp::core::component::RedirectLookup; + use cgp::core::field::types::Chars; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Symbol; + 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>>, + >; + } +} + +/// A segment that only looks like a primitive's name is a symbol. +pub mod primitive_like_names { + use core::marker::PhantomData; + + use cgp::core::base::types::PathCons; + use cgp::core::field::types::Nil; + use cgp::prelude::*; + + #[test] + fn f_is_a_symbol() { + let _: PhantomData = + PhantomData::>>; + } +} diff --git a/example-code/tests/reference/macros/product.rs b/example-code/tests/reference/macros/product.rs new file mode 100644 index 00000000..71eebcc9 --- /dev/null +++ b/example-code/tests/reference/macros/product.rs @@ -0,0 +1,145 @@ +//! 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::core::field::types::{Cons, Nil}; + 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::core::field::traits::HasField; + use cgp::core::field::traits::HasFields; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Field; + 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::core::field::types::Cons; + use cgp::core::field::types::Nil; + 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::core::field::types::{Cons, Nil}; + 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/struct.rs b/example-code/tests/reference/macros/struct.rs new file mode 100644 index 00000000..d59a2643 --- /dev/null +++ b/example-code/tests/reference/macros/struct.rs @@ -0,0 +1,203 @@ +//! Code from `docs/reference/macros/struct.md` — *`Struct!`*. +//! +//! 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 +pub mod overview { + use cgp::core::field::types::Field; + use cgp::prelude::*; + + #[test] + fn the_shape_is_the_hand_written_field_list() { + let _: PhantomData = + PhantomData::, Field]>; + } +} + +/// ## Usage +pub mod usage { + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Field; + use cgp::core::field::types::Index; + use cgp::core::field::types::Nil; + 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::; + } + + #[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, + 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::core::field::traits::FromFields; + use cgp::core::field::traits::HasFields; + 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::core::field::types::Cons; + use cgp::core::field::types::Field; + use cgp::core::field::types::Index; + use cgp::core::field::types::Nil; + 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::core::field::types::Cons; + use cgp::core::field::types::Field; + use cgp::core::field::types::Index; + use cgp::core::field::types::Nil; + use cgp::prelude::*; + + #[test] + fn a_one_element_positional_list_is_written_with_product() { + let _: PhantomData = PhantomData::; + let _: PhantomData, u64>]> = + PhantomData::, u64>, Nil>>; + } +} diff --git a/example-code/tests/reference/macros/sum.rs b/example-code/tests/reference/macros/sum.rs new file mode 100644 index 00000000..b9275aaa --- /dev/null +++ b/example-code/tests/reference/macros/sum.rs @@ -0,0 +1,92 @@ +//! 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::core::field::types::Void; + 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::core::field::traits::HasFields; + use cgp::core::field::types::Field; + use cgp::core::field::types::Index; + use cgp::core::field::types::Nil; + 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::core::field::types::Either; + use cgp::core::field::types::Void; + 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..bd3e30be --- /dev/null +++ b/example-code/tests/reference/macros/symbol.rs @@ -0,0 +1,188 @@ +//! 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::core::field::traits::HasField; + 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::core::field::traits::HasField; + use cgp::core::field::types::Index; + 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::core::field::traits::HasField; + 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::core::field::impls::UseField; + 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::core::field::traits::HasField; + 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::core::field::types::Chars; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Symbol; + use cgp::prelude::*; + + #[test] + fn the_expansion_is_a_length_and_a_character_list() { + let _: PhantomData = + PhantomData::>>>>; + let _: PhantomData = PhantomData::>; + let _: PhantomData = + PhantomData::>>>>>; + } +} diff --git a/example-code/tests/reference/mod.rs b/example-code/tests/reference/mod.rs new file mode 100644 index 00000000..7522f13f --- /dev/null +++ b/example-code/tests/reference/mod.rs @@ -0,0 +1,13 @@ +//! 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 attributes; +pub mod components; +pub mod derives; +pub mod errors; +pub mod macros; +pub mod providers; +pub mod traits; +pub mod types; diff --git a/example-code/tests/reference/providers/chain_getters.rs b/example-code/tests/reference/providers/chain_getters.rs new file mode 100644 index 00000000..6f7700e2 --- /dev/null +++ b/example-code/tests/reference/providers/chain_getters.rs @@ -0,0 +1,54 @@ +//! 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::component::WithProvider; + use cgp::core::field::impls::ChainGetters; + use cgp::core::field::impls::UseField; + 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, + } + } + + 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/dispatch/build_and_merge.rs b/example-code/tests/reference/providers/dispatch/build_and_merge.rs new file mode 100644 index 00000000..6d1aae52 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/build_and_merge.rs @@ -0,0 +1,107 @@ +//! Code from `docs/reference/providers/dispatch/build_and_merge.md` — `BuildAndMerge`. +//! +//! 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 cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[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(), + }, + ); + } + + #[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 new file mode 100644 index 00000000..dde9440f --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs @@ -0,0 +1,105 @@ +//! Code from `docs/reference/providers/dispatch/build_and_merge_outputs.md` — `BuildAndMergeOutputs`. +//! +//! 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 cgp::extra::dispatch::BuildAndMergeOutputs; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[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(), + }, + ); + } + + #[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 new file mode 100644 index 00000000..5ec07a51 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/build_and_set_field.rs @@ -0,0 +1,85 @@ +//! Code from `docs/reference/providers/dispatch/build_and_set_field.md` — `BuildAndSetField`. +//! +//! 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 cgp::core::field::traits::HasField; + use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[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, + }, + ); + } + + #[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 new file mode 100644 index 00000000..c9c97492 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/build_with_handlers.rs @@ -0,0 +1,101 @@ +//! Code from `docs/reference/providers/dispatch/build_with_handlers.md` — `BuildWithHandlers`. +//! +//! 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 cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[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(), + }, + ); + } + + #[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 new file mode 100644 index 00000000..db3fc49b --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs @@ -0,0 +1,85 @@ +//! Code from `docs/reference/providers/dispatch/downcast_and_handle.md` — `DowncastAndHandle`. +//! +//! 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 cgp::extra::dispatch::{ + DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers, + }; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + 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); + } + + #[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 new file mode 100644 index 00000000..f391d3e3 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs @@ -0,0 +1,80 @@ +//! 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. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::HasExtractor; + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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 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)); + } + } + } + + #[test] + 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 new file mode 100644 index 00000000..ad4f3064 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/handle_field_value.rs @@ -0,0 +1,74 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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; + + 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); + } + + #[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 new file mode 100644 index 00000000..10711b4c --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs @@ -0,0 +1,166 @@ +//! 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`, both through the explicit +//! list and through the `MatchFirstWithValueHandlers` convenience alias. + +/// ## Examples +pub mod examples { + use cgp::extra::dispatch::{ + ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, + }; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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 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::dispatch::MatchFirstWithValueHandlers; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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 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: MatchFirstWithValueHandlers, + } + } + + check_components! { + App { + ComputerComponent: ((), (Shape, f64)), + } + } + + #[test] + fn the_alias_builds_the_same_list() { + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.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 new file mode 100644 index 00000000..199ed3cd --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs @@ -0,0 +1,121 @@ +//! 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 +/// +/// `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::field::traits::StaticString; + use cgp::core::field::types::Field; + use cgp::extra::dispatch::MatchWithFieldHandlersRef; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Reading { + Temperature(i32), + Label(String), + } + + #[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::core::field::types::Field; + use cgp::extra::dispatch::MatchWithFieldHandlers; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[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"); + } + + #[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 new file mode 100644 index 00000000..b69f0b49 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs @@ -0,0 +1,246 @@ +//! 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 +/// +/// `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::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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; + + 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 circle = App.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); + } + + #[test] + 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::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::TryComputerComponent; + 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), + } + + #[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)); + } + + #[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 new file mode 100644 index 00000000..eb11981b --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs @@ -0,0 +1,279 @@ +//! 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 +/// +/// `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::dispatch::MatchWithValueHandlersRef; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::ComputerRefComponent; + 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::dispatch::MatchWithValueHandlers; + use cgp::extra::dispatch::MatchWithValueHandlersMut; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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::dispatch::MatchWithValueHandlers; + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + 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; + + 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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/dispatch/mod.rs b/example-code/tests/reference/providers/dispatch/mod.rs new file mode 100644 index 00000000..c7266730 --- /dev/null +++ b/example-code/tests/reference/providers/dispatch/mod.rs @@ -0,0 +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/tests/reference/providers/error/debug_error.rs b/example-code/tests/reference/providers/error/debug_error.rs new file mode 100644 index 00000000..9f5aaaa0 --- /dev/null +++ b/example-code/tests/reference/providers/error/debug_error.rs @@ -0,0 +1,62 @@ +//! 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. + +/// ## 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(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()) + ); + } + + #[test] + 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 new file mode 100644 index 00000000..013f47e2 --- /dev/null +++ b/example-code/tests/reference/providers/error/discard_detail.rs @@ -0,0 +1,53 @@ +//! 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. + +/// ## Examples +pub mod examples { + 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 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())); + } + + #[test] + 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 new file mode 100644 index 00000000..b7bafc56 --- /dev/null +++ b/example-code/tests/reference/providers/error/display_error.rs @@ -0,0 +1,62 @@ +//! 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. + +/// ## 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(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()) + ); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/error/mod.rs b/example-code/tests/reference/providers/error/mod.rs new file mode 100644 index 00000000..80bf48ba --- /dev/null +++ b/example-code/tests/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/tests/reference/providers/error/panic_on_error.rs b/example-code/tests/reference/providers/error/panic_on_error.rs new file mode 100644 index 00000000..844fadc6 --- /dev/null +++ b/example-code/tests/reference/providers/error/panic_on_error.rs @@ -0,0 +1,52 @@ +//! 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. + +/// ## Examples +pub mod examples { + 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, + } + } + + check_components! { + TestApp { + RunnerComponent, + } + } + + pub fn demo() { + let _ = TestApp.run(); // panics with "\"unrecoverable\"" + } + + #[test] + #[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 new file mode 100644 index 00000000..1d4f015a --- /dev/null +++ b/example-code/tests/reference/providers/error/raise_from.rs @@ -0,0 +1,83 @@ +//! 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. + +/// ## Examples +pub mod examples { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + 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 { + 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 { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + PortParserComponent: ParsePort, + } + } + + 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(_)))); + } + + #[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 new file mode 100644 index 00000000..63646d0b --- /dev/null +++ b/example-code/tests/reference/providers/error/raise_infallible.rs @@ -0,0 +1,61 @@ +//! 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. + +/// ## Examples +pub mod examples { + 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, 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(())); + } + + #[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 new file mode 100644 index 00000000..cb9c9f34 --- /dev/null +++ b/example-code/tests/reference/providers/error/return_error.rs @@ -0,0 +1,113 @@ +//! 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 +/// +/// 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}; + 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(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")); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/handler/compose_handlers.rs b/example-code/tests/reference/providers/handler/compose_handlers.rs new file mode 100644 index 00000000..1950d3a3 --- /dev/null +++ b/example-code/tests/reference/providers/handler/compose_handlers.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/providers/handler/compose_handlers.md` — `ComposeHandlers`. +//! +//! Pins the Examples program: `Double` then `AddOne`, composed and wired as one computer. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::{CanCompute, ComposeHandlers}; + 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, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 11); // (5 * 2) + 1 + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/handler/mod.rs b/example-code/tests/reference/providers/handler/mod.rs new file mode 100644 index 00000000..d9e06704 --- /dev/null +++ b/example-code/tests/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/tests/reference/providers/handler/pipe_handlers.rs b/example-code/tests/reference/providers/handler/pipe_handlers.rs new file mode 100644 index 00000000..7357e688 --- /dev/null +++ b/example-code/tests/reference/providers/handler/pipe_handlers.rs @@ -0,0 +1,101 @@ +//! 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 +pub mod usage { + use cgp::extra::handler::ComputerComponent; + 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, + } + } + + #[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::core::field::traits::HasField; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::{CanCompute, 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 MyContext { + pub foo: u64, + pub bar: u64, + pub baz: u64, + } + + delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } + } + + 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 test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/handler/promote.rs b/example-code/tests/reference/providers/handler/promote.rs new file mode 100644 index 00000000..0aef4e22 --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote.rs @@ -0,0 +1,67 @@ +//! 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. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::Producer; + use cgp::extra::handler::ProducerComponent; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanCompute, CanHandle, CanTryCompute, 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 + } + } + + #[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)); + } + + #[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 new file mode 100644 index 00000000..4c195653 --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_async.rs @@ -0,0 +1,74 @@ +//! 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. + +/// ## Examples +pub mod examples { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::TryComputer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanComputeAsync, CanHandle, 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 + } + } + + #[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)); + } + + #[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 new file mode 100644 index 00000000..f289925a --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_async_computer.rs @@ -0,0 +1,93 @@ +//! Code from `docs/reference/providers/handler/promote_async_computer.md` — `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::AsyncComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::PromoteAsyncComputer; + use cgp::extra::handler::{CanComputeAsync, CanHandle}; + use cgp::prelude::*; + + #[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)); + } + + #[test] + fn test_demo() { + 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::AsyncComputer; + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::AsyncComputerRefComponent; + use cgp::extra::handler::CanComputeAsyncRef; + use cgp::extra::handler::PromoteAsyncComputer; + 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 new file mode 100644 index 00000000..c179b71d --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_computer.rs @@ -0,0 +1,141 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::PromoteComputer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute}; + use cgp::prelude::*; + + #[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)); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); + } +} + +/// ## 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::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::ComputerRefComponent; + use cgp::extra::handler::PromoteComputer; + 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 +/// `AsyncComputerComponent` to `PromoteAsync`, each of which needs only the `Computer`. +pub mod common_mistakes { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::PromoteComputer; + use cgp::extra::handler::TryComputerComponent; + 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, + [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 new file mode 100644 index 00000000..d556863d --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_handler.rs @@ -0,0 +1,97 @@ +//! Code from `docs/reference/providers/handler/promote_handler.md` — `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`. + +/// ## 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::AsyncComputer; + use cgp::extra::handler::AsyncComputerComponent; + use cgp::extra::handler::AsyncComputerRefComponent; + use cgp::extra::handler::CanComputeAsyncRef; + use cgp::extra::handler::PromoteHandler; + 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; + use cgp::extra::handler::CanHandle; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::PromoteHandler; + use cgp::prelude::*; + + #[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())); + } + + #[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 new file mode 100644 index 00000000..55a8a667 --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_producer.rs @@ -0,0 +1,52 @@ +//! Code from `docs/reference/providers/handler/promote_producer.md` — `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::ComputerComponent; + use cgp::extra::handler::ProducerComponent; + use cgp::extra::handler::PromoteProducer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanCompute, CanProduce, CanTryCompute}; + use cgp::prelude::*; + + #[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)); + } + + #[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 new file mode 100644 index 00000000..2f7219fd --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_ref.rs @@ -0,0 +1,61 @@ +//! 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. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::ComputerRefComponent; + use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef}; + use cgp::prelude::*; + + /// 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; + + 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); + } + + #[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 new file mode 100644 index 00000000..d1513759 --- /dev/null +++ b/example-code/tests/reference/providers/handler/promote_try_computer.rs @@ -0,0 +1,105 @@ +//! 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 entries a hand-written base can use. The +//! hand-written base behind the `Handler` entry is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::PromoteTryComputer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanHandle, CanTryCompute}; + use cgp::prelude::*; + + #[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)); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); + } +} + +/// ## Common Mistakes +/// +/// 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::AsyncComputerComponent; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::HandlerComponent; + use cgp::extra::handler::PromoteTryComputer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanComputeAsync, PromoteAsync, TryPromote}; + 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, + [TryComputerComponent, AsyncComputerComponent]: PromoteTryComputer, + // The fix the page gives for the handler slot. + HandlerComponent: PromoteAsync>, + } + } + + check_components! { + App { + [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()); + } +} diff --git a/example-code/tests/reference/providers/handler/return_input.rs b/example-code/tests/reference/providers/handler/return_input.rs new file mode 100644 index 00000000..9377c7f6 --- /dev/null +++ b/example-code/tests/reference/providers/handler/return_input.rs @@ -0,0 +1,59 @@ +//! 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 +pub mod usage { + use cgp::extra::handler::ComputerComponent; + 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::ComputerComponent; + use cgp::extra::handler::{CanCompute, PipeHandlers, ReturnInput}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn add_one(value: u64) -> u64 { + value + 1 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeHandlers, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 7); // 5 -> 6 -> 6 -> 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 new file mode 100644 index 00000000..2f09bd98 --- /dev/null +++ b/example-code/tests/reference/providers/handler/try_promote.rs @@ -0,0 +1,81 @@ +//! 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; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::extra::handler::Computer; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::TryComputer; + use cgp::extra::handler::TryComputerComponent; + use cgp::extra::handler::{CanCompute, CanTryCompute, TryPromote}; + use cgp::prelude::*; + + /// 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)); + } + + #[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 new file mode 100644 index 00000000..8ef30378 --- /dev/null +++ b/example-code/tests/reference/providers/handler/use_input_delegate.rs @@ -0,0 +1,94 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::{CanCompute, 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, + } + } + + check_components! { + App { + ComputerComponent: [((), Circle), ((), Rectangle)], + } + } + + pub struct OpenApp; + + delegate_components! { + OpenApp { + open ComputerComponent; + + @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); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## 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; + + fn measure(&self, _code: PhantomData, input: Input) -> Self::Output; + } +} diff --git a/example-code/tests/reference/providers/mod.rs b/example-code/tests/reference/providers/mod.rs new file mode 100644 index 00000000..3ef4195f --- /dev/null +++ b/example-code/tests/reference/providers/mod.rs @@ -0,0 +1,24 @@ +//! 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 dispatch; +pub mod error; +pub mod handler; +pub mod monad; +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; +pub mod with_provider; +pub mod with_type; diff --git a/example-code/tests/reference/providers/monad/bind_err.rs b/example-code/tests/reference/providers/monad/bind_err.rs new file mode 100644 index 00000000..6c0977c2 --- /dev/null +++ b/example-code/tests/reference/providers/monad/bind_err.rs @@ -0,0 +1,34 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::Computer; + use cgp::extra::handler::PipeHandlers; + use cgp::extra::monad::monadic::err::BindErr; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::prelude::*; + + #[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")); + } + + #[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 new file mode 100644 index 00000000..301bbedb --- /dev/null +++ b/example-code/tests/reference/providers/monad/bind_ok.rs @@ -0,0 +1,41 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::Computer; + 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) } + } + + /// 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)); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/monad/mod.rs b/example-code/tests/reference/providers/monad/mod.rs new file mode 100644 index 00000000..6748082e --- /dev/null +++ b/example-code/tests/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/tests/reference/providers/monad/pipe_monadic.rs b/example-code/tests/reference/providers/monad/pipe_monadic.rs new file mode 100644 index 00000000..1156fbd6 --- /dev/null +++ b/example-code/tests/reference/providers/monad/pipe_monadic.rs @@ -0,0 +1,115 @@ +//! 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`. + +/// ## Examples +pub mod examples { + use cgp::extra::handler::CanCompute; + use cgp::extra::handler::ComputerComponent; + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::providers::PipeMonadic; + use cgp::prelude::*; + + #[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")); + } + + #[test] + fn test_demo() { + demo(); + } + + /// 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::handler::Computer; + use cgp::extra::handler::TryComputer; + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; + use cgp::extra::monad::providers::PipeMonadic; + use cgp::prelude::*; + + #[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::< + OkMonadicTrans, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), + Ok(Ok(())), + ); + + // An outer `Err` stops it too. + assert_eq!( + 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::< + OkMonadic, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::try_compute(&App, code, 1), + Ok(Ok(())), + ); + } + + #[test] + fn test_demo() { + demo(); + } + } +} diff --git a/example-code/tests/reference/providers/redirect_lookup.rs b/example-code/tests/reference/providers/redirect_lookup.rs new file mode 100644 index 00000000..597c3e0c --- /dev/null +++ b/example-code/tests/reference/providers/redirect_lookup.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/providers/redirect_lookup.md` — *`RedirectLookup`*. +//! +//! `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; + + delegate_components! { + App { + namespace DefaultNamespace; + + @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 new file mode 100644 index 00000000..4a3a84d6 --- /dev/null +++ b/example-code/tests/reference/providers/use_context.rs @@ -0,0 +1,79 @@ +//! Code from `docs/reference/providers/use_context.md` — *`UseContext`*. +//! +//! 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`). The self-cycle from Common Mistakes is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::component::UseContext; + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncode { + 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() + } + } + + pub struct EncodeVec(pub PhantomData); + + #[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() + } + } + + pub struct App; + + delegate_components! { + App { + open EncoderComponent; + + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVec, + } + } + + 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. + 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 new file mode 100644 index 00000000..20fa72f8 --- /dev/null +++ b/example-code/tests/reference/providers/use_default.rs @@ -0,0 +1,98 @@ +//! 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. 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 { + 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 NameGetter {} + + #[cgp_impl(UseDefault)] + #[uses(HasName)] + impl Greeter {} + + pub struct App; + + delegate_components! { + App { + [ + NameGetterComponent, + GreeterComponent, + ]: + UseDefault, + } + } + + check_components! { + App { + NameGetterComponent, + GreeterComponent, + } + } + + pub fn demo() { + assert_eq!(App.greet(), "Hello, John!"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/use_delegate.rs b/example-code/tests/reference/providers/use_delegate.rs new file mode 100644 index 00000000..260d7b56 --- /dev/null +++ b/example-code/tests/reference/providers/use_delegate.rs @@ -0,0 +1,84 @@ +//! 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], + } + } + + pub fn demo() { + assert_eq!(MyApp.area(&Rectangle { width: 2.0, height: 3.0 }), 6.0); + } + + #[test] + 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..092b8344 --- /dev/null +++ b/example-code/tests/reference/providers/use_delegated_type.rs @@ -0,0 +1,41 @@ +//! 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::HasType; + 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 new file mode 100644 index 00000000..e5f70d5d --- /dev/null +++ b/example-code/tests/reference/providers/use_field.rs @@ -0,0 +1,134 @@ +//! 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 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 { + use cgp::core::field::impls::UseField; + 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 demo() { + let person = Person { first_name: "Alice".to_owned() }; + assert_eq!(person.name(), "Alice"); // reads the first_name field + } + + #[test] + 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::core::field::impls::UseField; + 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::UseField; + use cgp::core::field::impls::WithField; + use cgp::core::types::HasType; + 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 new file mode 100644 index 00000000..e15e86c1 --- /dev/null +++ b/example-code/tests/reference/providers/use_fields.rs @@ -0,0 +1,80 @@ +//! Code from `docs/reference/providers/use_fields.md` — *`UseFields`*. +//! +//! 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. + +/// ## Usage +pub mod usage { + use cgp::core::component::UseFields; + 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, + } + } + + #[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::core::component::UseFields; + 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_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/providers/use_type.rs b/example-code/tests/reference/providers/use_type.rs new file mode 100644 index 00000000..4a15ed3e --- /dev/null +++ b/example-code/tests/reference/providers/use_type.rs @@ -0,0 +1,60 @@ +//! 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`, 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 +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, + } + } + + 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..b509f053 --- /dev/null +++ b/example-code/tests/reference/providers/with_context.rs @@ -0,0 +1,85 @@ +//! 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::core::component::WithContext; + use cgp::core::field::traits::HasField; + 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::component::WithContext; + 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_delegated_type.rs b/example-code/tests/reference/providers/with_delegated_type.rs new file mode 100644 index 00000000..241fb57a --- /dev/null +++ b/example-code/tests/reference/providers/with_delegated_type.rs @@ -0,0 +1,47 @@ +//! Code from `docs/reference/providers/with_delegated_type.md` — *`WithDelegatedType`*. +//! +//! `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 +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/tests/reference/providers/with_field.rs b/example-code/tests/reference/providers/with_field.rs new file mode 100644 index 00000000..4171e2b3 --- /dev/null +++ b/example-code/tests/reference/providers/with_field.rs @@ -0,0 +1,78 @@ +//! 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`, and gives a `#[cgp_type]` component a +//! field's type, which the plain `UseField` cannot; the bare `UseField` on that component is a trybuild +//! fixture. + +/// ## 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, + } + } + + 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 new file mode 100644 index 00000000..b6919acf --- /dev/null +++ b/example-code/tests/reference/providers/with_field_ref.rs @@ -0,0 +1,118 @@ +//! 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, +//! 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 { + 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, + } + } + + pub fn demo() { + let app = App { config: StoredConfig(Config { port: 8080 }) }; + assert_eq!(app.config().port, 8080); + } + + #[test] + 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::core::field::impls::UseField; + 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!(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 new file mode 100644 index 00000000..85e78c1a --- /dev/null +++ b/example-code/tests/reference/providers/with_provider.rs @@ -0,0 +1,110 @@ +//! 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, 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 { + 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, + } + } + + 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::component::WithContext; + 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; + } +} diff --git a/example-code/tests/reference/providers/with_type.rs b/example-code/tests/reference/providers/with_type.rs new file mode 100644 index 00000000..581f040f --- /dev/null +++ b/example-code/tests/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, + } + } +} diff --git a/example-code/tests/reference/traits/append_product.rs b/example-code/tests/reference/traits/append_product.rs new file mode 100644 index 00000000..88977cec --- /dev/null +++ b/example-code/tests/reference/traits/append_product.rs @@ -0,0 +1,39 @@ +//! 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::core::field::types::Field; + use cgp::core::field::types::Nil; + 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 + } + + /// 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, + ) -> Base { + fields + } +} 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..d2ec3095 --- /dev/null +++ b/example-code/tests/reference/traits/build_field.rs @@ -0,0 +1,53 @@ +//! 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::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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_from.rs b/example-code/tests/reference/traits/can_build_from.rs new file mode 100644 index 00000000..4e739dae --- /dev/null +++ b/example-code/tests/reference/traits/can_build_from.rs @@ -0,0 +1,81 @@ +//! Code from `docs/reference/traits/casting/can_build_from.md` — `CanBuildFrom`. +//! +//! 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 +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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, + } + + // 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, + 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); + } + + #[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..b965eaf6 --- /dev/null +++ b/example-code/tests/reference/traits/can_build_with_default.rs @@ -0,0 +1,40 @@ +//! 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::core::field::traits::HasBuilder; + 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_downcast.rs b/example-code/tests/reference/traits/can_downcast.rs new file mode 100644 index 00000000..ce505772 --- /dev/null +++ b/example-code/tests/reference/traits/can_downcast.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/traits/casting/can_downcast.md` — `CanDowncast`. +//! +//! 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)] + pub enum FooBar { + Foo(u64), + Bar(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + 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_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/can_downcast_fields.rs b/example-code/tests/reference/traits/can_downcast_fields.rs new file mode 100644 index 00000000..adce985f --- /dev/null +++ b/example-code/tests/reference/traits/can_downcast_fields.rs @@ -0,0 +1,61 @@ +//! Code from `docs/reference/traits/casting/can_downcast_fields.md` — `CanDowncastFields`. +//! +//! 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)] + 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), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum JustBaz { + Baz(bool), + } + + 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"); + } + + #[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..9265fa1e --- /dev/null +++ b/example-code/tests/reference/traits/can_finalize_with_default.rs @@ -0,0 +1,36 @@ +//! 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::core::field::traits::BuildField; + use cgp::core::field::traits::HasBuilder; + 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/can_upcast.rs b/example-code/tests/reference/traits/can_upcast.rs new file mode 100644 index 00000000..f5e9a0c1 --- /dev/null +++ b/example-code/tests/reference/traits/can_upcast.rs @@ -0,0 +1,38 @@ +//! Code from `docs/reference/traits/casting/can_upcast.md` — `CanUpcast`. +//! +//! 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::*; + + // 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), + } + + // 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), + } + + 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/can_use_component.rs b/example-code/tests/reference/traits/can_use_component.rs new file mode 100644 index 00000000..cfbc2d03 --- /dev/null +++ b/example-code/tests/reference/traits/can_use_component.rs @@ -0,0 +1,91 @@ +//! 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::core::component::CanUseComponent; + 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/concat_path.rs b/example-code/tests/reference/traits/concat_path.rs new file mode 100644 index 00000000..2f9d7b8b --- /dev/null +++ b/example-code/tests/reference/traits/concat_path.rs @@ -0,0 +1,30 @@ +//! Code from `docs/reference/traits/formatting/concat_path.md` — `ConcatPath`. +//! +//! 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 { + use cgp::core::base::traits::ConcatPath; + use cgp::prelude::*; + + pub type Outer = Path!(@a.b); + pub type Inner = Path!(@c.d); + + pub type Joined = >::Output; + + // 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/concat_product.rs b/example-code/tests/reference/traits/concat_product.rs new file mode 100644 index 00000000..ce52f802 --- /dev/null +++ b/example-code/tests/reference/traits/concat_product.rs @@ -0,0 +1,41 @@ +//! 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::core::field::types::Field; + use cgp::core::field::types::Nil; + 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/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/delegate_component.rs b/example-code/tests/reference/traits/delegate_component.rs new file mode 100644 index 00000000..301bccc8 --- /dev/null +++ b/example-code/tests/reference/traits/delegate_component.rs @@ -0,0 +1,79 @@ +//! 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::core::component::DelegateComponent; + 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/extract_field.rs b/example-code/tests/reference/traits/extract_field.rs new file mode 100644 index 00000000..8c8978ac --- /dev/null +++ b/example-code/tests/reference/traits/extract_field.rs @@ -0,0 +1,67 @@ +//! 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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractor; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + 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/field_getter.rs b/example-code/tests/reference/traits/field_getter.rs new file mode 100644 index 00000000..28a47267 --- /dev/null +++ b/example-code/tests/reference/traits/field_getter.rs @@ -0,0 +1,89 @@ +//! 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::component::WithProvider; + use cgp::core::field::impls::WithField; + use cgp::core::field::traits::FieldGetter; + use cgp::core::field::traits::HasField; + 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..f36d38d1 --- /dev/null +++ b/example-code/tests/reference/traits/field_mapper.rs @@ -0,0 +1,79 @@ +//! 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::component::UseContext; + use cgp::core::component::WithProvider; + use cgp::core::field::impls::UseField; + use cgp::core::field::traits::FieldGetter; + use cgp::core::field::traits::FieldMapper; + use cgp::core::field::traits::HasField; + 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/finalize_build.rs b/example-code/tests/reference/traits/finalize_build.rs new file mode 100644 index 00000000..1df4fd75 --- /dev/null +++ b/example-code/tests/reference/traits/finalize_build.rs @@ -0,0 +1,46 @@ +//! 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::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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_extract.rs b/example-code/tests/reference/traits/finalize_extract.rs new file mode 100644 index 00000000..fc8abebb --- /dev/null +++ b/example-code/tests/reference/traits/finalize_extract.rs @@ -0,0 +1,53 @@ +//! 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::core::field::traits::ExtractField; + use cgp::core::field::traits::FinalizeExtract; + use cgp::core::field::traits::HasExtractor; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn describe(shape: Shape) -> String { + match shape.to_extractor().extract_field(PhantomData::) { + 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..e3b4105f --- /dev/null +++ b/example-code/tests/reference/traits/finalize_extract_result.rs @@ -0,0 +1,50 @@ +//! 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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractor; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + 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/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/from_fields.rs b/example-code/tests/reference/traits/from_fields.rs new file mode 100644 index 00000000..90d10f7f --- /dev/null +++ b/example-code/tests/reference/traits/from_fields.rs @@ -0,0 +1,45 @@ +//! 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::core::field::traits::FromFields; + use cgp::core::field::traits::ToFields; + 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/from_variant.rs b/example-code/tests/reference/traits/from_variant.rs new file mode 100644 index 00000000..573f3b83 --- /dev/null +++ b/example-code/tests/reference/traits/from_variant.rs @@ -0,0 +1,64 @@ +//! 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::core::field::traits::FromVariant; + 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_builder.rs b/example-code/tests/reference/traits/has_builder.rs new file mode 100644 index 00000000..bc53204e --- /dev/null +++ b/example-code/tests/reference/traits/has_builder.rs @@ -0,0 +1,60 @@ +//! Code from `docs/reference/traits/builder/has_builder.md` — `HasBuilder`. +//! +//! 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 { + use cgp::core::field::impls::CanBuildFrom; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::HasField; + 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(Debug, PartialEq, BuildField)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + pub fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) + .build_field(PhantomData::, true) + .finalize_build() + } + + 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, + } + ); + } + + #[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..892b891c --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor.rs @@ -0,0 +1,58 @@ +//! 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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractor; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(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..3f298be9 --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor_mut.rs @@ -0,0 +1,55 @@ +//! 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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractorMut; + 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..1e15ab2f --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor_ref.rs @@ -0,0 +1,63 @@ +//! 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::ExtractField; + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::traits::HasExtractorRef; + 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/has_field.rs b/example-code/tests/reference/traits/has_field.rs new file mode 100644 index 00000000..745d1782 --- /dev/null +++ b/example-code/tests/reference/traits/has_field.rs @@ -0,0 +1,104 @@ +//! 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::core::field::traits::HasField; + 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..d0cc3262 --- /dev/null +++ b/example-code/tests/reference/traits/has_field_mut.rs @@ -0,0 +1,66 @@ +//! 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::core::field::traits::HasFieldMut; + 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..d75b70e3 --- /dev/null +++ b/example-code/tests/reference/traits/has_fields.rs @@ -0,0 +1,60 @@ +//! 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::core::field::traits::HasFields; + use cgp::core::field::types::Field; + 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::(); + + // The prose's shape-macro spellings of the first two checks. + assert_shape::(); + 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..d7c0f384 --- /dev/null +++ b/example-code/tests/reference/traits/has_fields_ref.rs @@ -0,0 +1,51 @@ +//! 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::core::field::traits::HasFieldsRef; + use cgp::core::field::types::Field; + 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/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..a3df9a61 --- /dev/null +++ b/example-code/tests/reference/traits/into_builder.rs @@ -0,0 +1,49 @@ +//! 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::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::IntoBuilder; + 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/is_provider_for.rs b/example-code/tests/reference/traits/is_provider_for.rs new file mode 100644 index 00000000..e098351e --- /dev/null +++ b/example-code/tests/reference/traits/is_provider_for.rs @@ -0,0 +1,105 @@ +//! 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::core::component::IsProviderFor; + 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/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_field.rs b/example-code/tests/reference/traits/map_field.rs new file mode 100644 index 00000000..35d7ca04 --- /dev/null +++ b/example-code/tests/reference/traits/map_field.rs @@ -0,0 +1,73 @@ +//! 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::component::WithProvider; + use cgp::core::field::impls::ChainGetters; + use cgp::core::field::impls::UseField; + use cgp::core::field::traits::HasField; + 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/map_fields.rs b/example-code/tests/reference/traits/map_fields.rs new file mode 100644 index 00000000..db69a18e --- /dev/null +++ b/example-code/tests/reference/traits/map_fields.rs @@ -0,0 +1,45 @@ +//! 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* lists — 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::IsNothing; + use cgp::core::field::impls::IsOptional; + use cgp::core::field::impls::IsPresent; + 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/tests/reference/traits/map_type.rs b/example-code/tests/reference/traits/map_type.rs new file mode 100644 index 00000000..445c9aca --- /dev/null +++ b/example-code/tests/reference/traits/map_type.rs @@ -0,0 +1,53 @@ +//! 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::IsNothing; + use cgp::core::field::impls::IsOptional; + use cgp::core::field::impls::IsPresent; + use cgp::core::field::impls::IsVoid; + use cgp::core::field::traits::MapType; + use cgp::core::field::types::Void; + + // 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..8e715571 --- /dev/null +++ b/example-code/tests/reference/traits/map_type_ref.rs @@ -0,0 +1,71 @@ +//! 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::IsMut; + use cgp::core::field::impls::IsOwned; + use cgp::core::field::impls::IsRef; + use cgp::core::field::traits::ExtractField; + use cgp::core::field::traits::HasExtractorMut; + use cgp::core::field::traits::HasExtractorRef; + use cgp::core::field::traits::MapTypeRef; + 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 new file mode 100644 index 00000000..bf8f8471 --- /dev/null +++ b/example-code/tests/reference/traits/mod.rs @@ -0,0 +1,65 @@ +//! Code from the pages under `docs/reference/traits/`. +//! +//! 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 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; +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; +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; +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; +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; +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/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/partial_data.rs b/example-code/tests/reference/traits/partial_data.rs new file mode 100644 index 00000000..a13d2d4a --- /dev/null +++ b/example-code/tests/reference/traits/partial_data.rs @@ -0,0 +1,38 @@ +//! 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::core::field::traits::BuildField; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::PartialData; + 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/static_format.rs b/example-code/tests/reference/traits/static_format.rs new file mode 100644 index 00000000..8db73c74 --- /dev/null +++ b/example-code/tests/reference/traits/static_format.rs @@ -0,0 +1,45 @@ +//! Code from `docs/reference/traits/formatting/static_format.md` — `StaticFormat`. +//! +//! 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::*; + + // A `Display` bound is all that formatting a name needs. + pub fn describe(_tag: PhantomData) -> String { + format!("missing field `{}`", Tag::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"); + + assert_eq!( + describe(PhantomData::), + "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 new file mode 100644 index 00000000..c5dd92c8 --- /dev/null +++ b/example-code/tests/reference/traits/static_string.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/traits/formatting/static_string.md` — `StaticString`. +//! +//! 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 { + 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`: reconstructed at the point of formatting + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + + 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/take_field.rs b/example-code/tests/reference/traits/take_field.rs new file mode 100644 index 00000000..9918c9e6 --- /dev/null +++ b/example-code/tests/reference/traits/take_field.rs @@ -0,0 +1,46 @@ +//! 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::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::IntoBuilder; + 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_fields.rs b/example-code/tests/reference/traits/to_fields.rs new file mode 100644 index 00000000..1a43ef77 --- /dev/null +++ b/example-code/tests/reference/traits/to_fields.rs @@ -0,0 +1,41 @@ +//! 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::core::field::traits::FromFields; + use cgp::core::field::traits::ToFields; + 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..967085a0 --- /dev/null +++ b/example-code/tests/reference/traits/to_fields_ref.rs @@ -0,0 +1,34 @@ +//! 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::core::field::traits::ToFieldsRef; + 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(); + } +} 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..0cdd306f --- /dev/null +++ b/example-code/tests/reference/traits/to_optional.rs @@ -0,0 +1,44 @@ +//! 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::core::field::traits::BuildField; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::IntoBuilder; + 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.rs b/example-code/tests/reference/traits/transform_map.rs new file mode 100644 index 00000000..830cc3d4 --- /dev/null +++ b/example-code/tests/reference/traits/transform_map.rs @@ -0,0 +1,65 @@ +//! 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::IsNothing; + use cgp::core::field::impls::IsOptional; + use cgp::core::field::impls::IsPresent; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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_default.rs b/example-code/tests/reference/traits/transform_map_default.rs new file mode 100644 index 00000000..55427dbb --- /dev/null +++ b/example-code/tests/reference/traits/transform_map_default.rs @@ -0,0 +1,41 @@ +//! 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::impls::IsPresent; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + 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_map_fields.rs b/example-code/tests/reference/traits/transform_map_fields.rs new file mode 100644 index 00000000..e3e4b455 --- /dev/null +++ b/example-code/tests/reference/traits/transform_map_fields.rs @@ -0,0 +1,97 @@ +//! 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::impls::IsPresent; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::IntoBuilder; + 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::impls::IsPresent; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::IntoBuilder; + 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])); + } +} 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..6b363b55 --- /dev/null +++ b/example-code/tests/reference/traits/transform_optional.rs @@ -0,0 +1,42 @@ +//! 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::BuildField; + use cgp::core::field::traits::HasBuilder; + 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..b06f1065 --- /dev/null +++ b/example-code/tests/reference/traits/update_field.rs @@ -0,0 +1,48 @@ +//! 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::core::field::impls::IsNothing; + use cgp::core::field::impls::IsPresent; + use cgp::core::field::traits::BuildField; + use cgp::core::field::traits::FinalizeBuild; + use cgp::core::field::traits::HasBuilder; + use cgp::core::field::traits::UpdateField; + 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(); + } +} diff --git a/example-code/tests/reference/types/chars.rs b/example-code/tests/reference/types/chars.rs new file mode 100644 index 00000000..3c85c8fe --- /dev/null +++ b/example-code/tests/reference/types/chars.rs @@ -0,0 +1,50 @@ +//! Code from `docs/reference/types/chars.md` — *`Chars`*. +//! +//! 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 +pub mod examples { + use cgp::core::field::traits::HasField; + use cgp::core::field::types::Chars; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Symbol; + use cgp::prelude::*; + + // The tag names the field the function reads. + pub fn name_of(context: &Context) -> &str + where + Context: HasField, + { + context.get_field(PhantomData::) + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + 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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/cons.rs b/example-code/tests/reference/types/cons.rs new file mode 100644 index 00000000..dd35cc98 --- /dev/null +++ b/example-code/tests/reference/types/cons.rs @@ -0,0 +1,63 @@ +//! Code from `docs/reference/types/cons.md` — *`Cons`*. +//! +//! `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 +pub mod examples { + use cgp::core::field::traits::HasFields; + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Field; + use cgp::core::field::types::Nil; + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + 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; + } + + impl Len for Nil { + const LEN: usize = 0; + } + + 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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/either.rs b/example-code/tests/reference/types/either.rs new file mode 100644 index 00000000..d2983d0a --- /dev/null +++ b/example-code/tests/reference/types/either.rs @@ -0,0 +1,55 @@ +//! Code from `docs/reference/types/either.md` — *`Either`*. +//! +//! `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 +pub mod examples { + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Either; + use cgp::core::field::types::{Nil, Void}; + use cgp::prelude::*; + + #[derive(HasFields)] + pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, + } + + 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 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_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/field.rs b/example-code/tests/reference/types/field.rs new file mode 100644 index 00000000..202fee65 --- /dev/null +++ b/example-code/tests/reference/types/field.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/types/field.md` — *`Field`*. +//! +//! 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 +pub mod examples { + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Field; + use cgp::core::field::types::{Index, Nil}; + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + #[derive(HasFields)] + pub struct Point(pub u32, pub u32); + + #[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\""); + } + + #[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 new file mode 100644 index 00000000..bd36f79a --- /dev/null +++ b/example-code/tests/reference/types/index_type.rs @@ -0,0 +1,32 @@ +//! Code from `docs/reference/types/index_type.md` — *`Index`*. +//! +//! `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 +pub mod examples { + use cgp::core::field::traits::HasField; + use cgp::core::field::types::Index; + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Pair(pub u32, pub 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_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/life.rs b/example-code/tests/reference/types/life.rs new file mode 100644 index 00000000..d04ec163 --- /dev/null +++ b/example-code/tests/reference/types/life.rs @@ -0,0 +1,122 @@ +//! Code from `docs/reference/types/life.md` — *`Life`*. +//! +//! `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 second +//! Examples program wires the same component at the unsized target `str` and calls it. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::HasField; + use cgp::core::field::types::Life; + 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, + } + + #[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(); + } + + // 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 +/// +/// 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::core::field::types::Life; + 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 new file mode 100644 index 00000000..b27e5be5 --- /dev/null +++ b/example-code/tests/reference/types/mod.rs @@ -0,0 +1,17 @@ +//! 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 overview page, which shows no code, gets 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 void; diff --git a/example-code/tests/reference/types/mref.rs b/example-code/tests/reference/types/mref.rs new file mode 100644 index 00000000..7ef767b1 --- /dev/null +++ b/example-code/tests/reference/types/mref.rs @@ -0,0 +1,86 @@ +//! Code from `docs/reference/types/mref.md` — *`MRef`*. +//! +//! `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 +pub mod examples { + use cgp::core::field::impls::UseField; + use cgp::core::field::types::MRef; + use cgp::prelude::*; + + #[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, + } + } + + 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 new file mode 100644 index 00000000..c57b4c91 --- /dev/null +++ b/example-code/tests/reference/types/nil.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/types/nil.md` — *`Nil`*. +//! +//! `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 +pub mod examples { + use cgp::core::base::types::PathCons; + use cgp::core::field::traits::ToFields; + use cgp::core::field::types::Chars; + use cgp::core::field::types::Cons; + use cgp::core::field::types::Nil; + use cgp::core::field::types::Symbol; + use cgp::prelude::*; + + #[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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/path_cons.rs b/example-code/tests/reference/types/path_cons.rs new file mode 100644 index 00000000..15667959 --- /dev/null +++ b/example-code/tests/reference/types/path_cons.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/types/path_cons.md` — *`PathCons`*. +//! +//! `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 +pub mod examples { + use cgp::core::base::traits::ConcatPath; + use cgp::core::base::types::PathCons; + use cgp::core::field::types::Nil; + 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 => + @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 new file mode 100644 index 00000000..91b46c00 --- /dev/null +++ b/example-code/tests/reference/types/phantom_data.rs @@ -0,0 +1,81 @@ +//! 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 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 +/// +/// 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 +pub mod examples { + use cgp::core::field::traits::HasField; + use cgp::prelude::*; + + #[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}!") + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetField, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + // 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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/types/void.rs b/example-code/tests/reference/types/void.rs new file mode 100644 index 00000000..b2267e7a --- /dev/null +++ b/example-code/tests/reference/types/void.rs @@ -0,0 +1,52 @@ +//! Code from `docs/reference/types/void.md` — *`Void`*. +//! +//! `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 +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::core::field::types::Either; + use cgp::core::field::types::Void; + use cgp::prelude::*; + + 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))); + + // A `Result` that cannot fail unwraps without an `unwrap`. + let result: Result = Ok(5); + assert_eq!(result.finalize_extract_result(), 5); + } + + #[test] + fn test_demo() { + demo(); + } +} 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; 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/storage_backend.rs b/example-code/tests/tutorials/storage_backend.rs new file mode 100644 index 00000000..f109bcd3 --- /dev/null +++ b/example-code/tests/tutorials/storage_backend.rs @@ -0,0 +1,405 @@ +//! `docs/tutorials/storage-backend.md` +//! +//! The page builds one `src/main.rs` in steps, so each module below is that file as it stands at the +//! end of the heading it names, assembled from the page's blocks in order and a later module repeating +//! what an earlier one showed. Each module's `main` is the page's, compiled but not run, since it writes +//! a `pictures` folder; a test beside it runs the same calls in a temporary directory. The deliberate +//! mistake in *Check the wiring* is a compile-fail fixture holding the whole finished file with the +//! field removed, at `tests/compile_fail/tutorials/storage_backend_missing_field.rs`. + +/// *Read the application's data with functions*. +mod read_with_functions { + use std::collections::HashMap; + use std::path::Path; + + use anyhow::anyhow; + use cgp::prelude::*; + + #[derive(Clone, PartialEq, Eq, Hash)] + pub struct UserId(pub u64); + + #[derive(Clone)] + pub struct User { + pub name: String, + pub profile_picture_object_id: Option, + } + + #[derive(HasField)] + pub struct App { + pub database: HashMap, + pub local_dir: String, + } + + #[cgp_fn] + #[async_trait] + pub async fn get_user( + &self, + #[implicit] database: &HashMap, + user_id: &UserId, + ) -> anyhow::Result { + database + .get(user_id) + .cloned() + .ok_or_else(|| anyhow!("no user with ID {}", user_id.0)) + } + + #[cgp_fn] + #[async_trait] + pub async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) + } + + #[tokio::main] + async fn main() -> anyhow::Result<()> { + tokio::fs::create_dir_all("pictures").await?; + tokio::fs::write("pictures/alice.png", b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: "pictures".to_owned(), + }; + + let user = app.get_user(&UserId(1)).await?; + let picture = app.fetch_storage_object("alice.png").await?; + println!("{} has a {}-byte picture", user.name, picture.len()); + + Ok(()) + } + + #[tokio::test] + async fn main_prints_the_user_and_the_picture_size() -> anyhow::Result<()> { + let local_dir = std::env::temp_dir().join("cgp-tutorial-storage-read"); + std::fs::create_dir_all(&local_dir)?; + tokio::fs::write(local_dir.join("alice.png"), b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: local_dir.to_str().unwrap().to_owned(), + }; + + let user = app.get_user(&UserId(1)).await?; + let picture = app.fetch_storage_object("alice.png").await?; + assert_eq!(format!("{} has a {}-byte picture", user.name, picture.len()), "Alice has a 16-byte picture"); + Ok(()) + } +} + +/// *Combine the steps*. +mod combine_the_steps { + use std::collections::HashMap; + use std::path::Path; + + use anyhow::anyhow; + use cgp::prelude::*; + + #[derive(Clone, PartialEq, Eq, Hash)] + pub struct UserId(pub u64); + + #[derive(Clone)] + pub struct User { + pub name: String, + pub profile_picture_object_id: Option, + } + + #[derive(HasField)] + pub struct App { + pub database: HashMap, + pub local_dir: String, + } + + #[cgp_fn] + #[async_trait] + pub async fn get_user( + &self, + #[implicit] database: &HashMap, + user_id: &UserId, + ) -> anyhow::Result { + database + .get(user_id) + .cloned() + .ok_or_else(|| anyhow!("no user with ID {}", user_id.0)) + } + + #[cgp_fn] + #[async_trait] + pub async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) + } + + #[tokio::main] + async fn main() -> anyhow::Result<()> { + tokio::fs::create_dir_all("pictures").await?; + tokio::fs::write("pictures/alice.png", b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: "pictures".to_owned(), + }; + + match app.get_user_profile_picture(&UserId(1)).await? { + Some(picture) => println!("Found a {}-byte picture", picture.len()), + None => println!("No picture"), + } + + Ok(()) + } + + #[cgp_fn] + #[async_trait] + #[uses(GetUser, FetchStorageObject)] + pub async fn get_user_profile_picture( + &self, + user_id: &UserId, + ) -> anyhow::Result>> { + let user = self.get_user(user_id).await?; + + match user.profile_picture_object_id { + Some(object_id) => Ok(Some(self.fetch_storage_object(&object_id).await?)), + None => Ok(None), + } + } + + /// The page's claim that a context with a `database` but no `local_dir` has `get_user`; the call + /// to `get_user_profile_picture` it says fails to compile is not made here. + #[derive(HasField)] + pub struct UsersOnlyApp { + pub database: HashMap, + } + + #[tokio::test] + async fn main_prints_the_picture_size() -> anyhow::Result<()> { + let local_dir = std::env::temp_dir().join("cgp-tutorial-storage-combine"); + std::fs::create_dir_all(&local_dir)?; + tokio::fs::write(local_dir.join("alice.png"), b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: local_dir.to_str().unwrap().to_owned(), + }; + + let picture = app.get_user_profile_picture(&UserId(1)).await?; + assert_eq!(picture.map(|data| data.len()), Some(16)); + + let users_only = UsersOnlyApp { database: HashMap::new() }; + assert!(users_only.get_user(&UserId(1)).await.is_err()); + Ok(()) + } +} + +/// *Add a backend for tests* and *Check the wiring*: the finished file. +mod a_backend_for_tests { + use std::collections::HashMap; + use std::path::Path; + + use anyhow::anyhow; + use cgp::prelude::*; + + #[derive(Clone, PartialEq, Eq, Hash)] + pub struct UserId(pub u64); + + #[derive(Clone)] + pub struct User { + pub name: String, + pub profile_picture_object_id: Option, + } + + #[derive(HasField)] + pub struct App { + pub database: HashMap, + pub local_dir: String, + } + + #[cgp_fn] + #[async_trait] + pub async fn get_user( + &self, + #[implicit] database: &HashMap, + user_id: &UserId, + ) -> anyhow::Result { + database + .get(user_id) + .cloned() + .ok_or_else(|| anyhow!("no user with ID {}", user_id.0)) + } + + #[async_trait] + #[cgp_component(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + #[cgp_impl(new FetchLocalObject)] + impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] local_dir: &str, + object_id: &str, + ) -> anyhow::Result> { + let data = tokio::fs::read(Path::new(local_dir).join(object_id)).await?; + Ok(data) + } + } + + #[tokio::main] + async fn main() -> anyhow::Result<()> { + tokio::fs::create_dir_all("pictures").await?; + tokio::fs::write("pictures/alice.png", b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: "pictures".to_owned(), + }; + + match app.get_user_profile_picture(&UserId(1)).await? { + Some(picture) => println!("Found a {}-byte picture", picture.len()), + None => println!("No picture"), + } + + Ok(()) + } + + #[cgp_fn] + #[async_trait] + #[uses(GetUser, CanFetchStorageObject)] + pub async fn get_user_profile_picture( + &self, + user_id: &UserId, + ) -> anyhow::Result>> { + let user = self.get_user(user_id).await?; + + match user.profile_picture_object_id { + Some(object_id) => Ok(Some(self.fetch_storage_object(&object_id).await?)), + None => Ok(None), + } + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchLocalObject, + } + } + + check_components! { + App { + StorageObjectFetcherComponent, + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[derive(HasField)] + pub struct TestApp { + pub database: HashMap, + pub objects: HashMap>, + } + + #[cgp_impl(new FetchMemoryObject)] + impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] objects: &HashMap>, + object_id: &str, + ) -> anyhow::Result> { + objects + .get(object_id) + .cloned() + .ok_or_else(|| anyhow!("no object named {object_id}")) + } + } + + delegate_components! { + TestApp { + StorageObjectFetcherComponent: FetchMemoryObject, + } + } + + check_components! { + TestApp { + StorageObjectFetcherComponent, + } + } + + #[tokio::test] + async fn fetches_the_picture_from_memory() -> anyhow::Result<()> { + let app = TestApp { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + objects: HashMap::from([("alice.png".to_owned(), b"fake image".to_vec())]), + }; + + let picture = app.get_user_profile_picture(&UserId(1)).await?; + assert_eq!(picture, Some(b"fake image".to_vec())); + + Ok(()) + } + } + + #[tokio::test] + async fn main_reads_from_the_folder() -> anyhow::Result<()> { + let local_dir = std::env::temp_dir().join("cgp-tutorial-storage-backend"); + std::fs::create_dir_all(&local_dir)?; + tokio::fs::write(local_dir.join("alice.png"), b"not really a PNG").await?; + + let app = App { + database: HashMap::from([( + UserId(1), + User { + name: "Alice".to_owned(), + profile_picture_object_id: Some("alice.png".to_owned()), + }, + )]), + local_dir: local_dir.to_str().unwrap().to_owned(), + }; + + let picture = app.get_user_profile_picture(&UserId(1)).await?; + assert_eq!(picture.map(|data| data.len()), Some(16)); + Ok(()) + } +} diff --git a/example-code/tests/tutorials_tests.rs b/example-code/tests/tutorials_tests.rs new file mode 100644 index 00000000..c7c73c97 --- /dev/null +++ b/example-code/tests/tutorials_tests.rs @@ -0,0 +1,13 @@ +//! 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; + mod storage_backend; +} 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" } } diff --git a/scripts/fonts/README.md b/scripts/fonts/README.md new file mode 100644 index 00000000..f1e8fcf7 --- /dev/null +++ b/scripts/fonts/README.md @@ -0,0 +1,32 @@ +# Fonts + +The site self-hosts two font families under `static/fonts/`, under the SIL Open Font License 1.1, each +beside its licence: + +- `inter/`: Inter, for body text and headings, weights 400 to 700, upright and italic, at the + text optical size. Headings use weight 600. +- `jetbrains-mono/`: JetBrains Mono, for code, weights 400 to 700, upright only and without its + ligature feature. Code sets at weight 500, and the code themes set comments upright. + +Each file is a WOFF2 subset, cut from the variable font in the +[Google Fonts repository](https://github.com/google/fonts/tree/main/ofl) with `fonttools`, run +through `uv run --with fonttools --with brotli`. Both keep Latin; the code font also keeps Greek, +superscripts and subscripts, and box drawing, which the site's code blocks and quoted diagnostics use: + +```sh +fonttools varLib.instancer 'Inter[opsz,wght].ttf' wght=400:700 opsz=14 -o inter.ttf +pyftsubset inter.ttf --unicodes="$LATIN" --layout-features='kern,liga,calt,mark,mkmk,ccmp,locl' \ + --flavor=woff2 --output-file=inter-latin.woff2 +fonttools varLib.instancer 'Inter-Italic[opsz,wght].ttf' wght=400:700 opsz=14 -o inter-italic.ttf +pyftsubset inter-italic.ttf --unicodes="$LATIN" --layout-features='kern,liga,calt,mark,mkmk,ccmp,locl' \ + --flavor=woff2 --output-file=inter-latin-italic.woff2 +fonttools varLib.instancer 'JetBrainsMono[wght].ttf' wght=400:700 -o jb.ttf +pyftsubset jb.ttf --unicodes="$LATIN,U+0370-03FF,U+2070-209F,U+2500-257F,U+2022,U+25B6,U+2713,U+2717" \ + --layout-features='kern,mark,mkmk' --flavor=woff2 --output-file=jetbrains-mono-latin.woff2 +``` + +`$LATIN` is +`U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2190-2199,U+2212,U+2215,U+2248,U+2260,U+2264-2265`. +The three files total about 80 KB. A character outside these ranges renders in the fallback face, so +recut the subsets when a page starts using a new script or symbol block. +`src/css/custom.css` declares the faces and their metric-matched fallbacks. diff --git a/scripts/social-card/make.py b/scripts/social-card/make.py new file mode 100644 index 00000000..abd98acb --- /dev/null +++ b/scripts/social-card/make.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Render the site's social card, the image a shared link to contextgeneric.dev shows. + +The card is the hero illustration beside the project's name, its tag line, and the site address, at +1200x630, in the site theme's colours, in the site's font. Run it from the website's root after changing the tag line or the hero illustration: + + python3 scripts/social-card/make.py + +It needs `google-chrome` to render the page and ImageMagick's `magick` to read the illustration's +background colour and write the JPEG. Commit the resulting `static/img/social-card.jpg`. +""" + +import pathlib +import subprocess +import tempfile + +ROOT = pathlib.Path(__file__).resolve().parents[2] +HERO = ROOT / "static/img/cgp-hero.webp" +FONT = ROOT / "static/fonts/inter/inter-latin.woff2" +OUT = ROOT / "static/img/social-card.jpg" +TAG_LINE = "A language extension for Rust, with pluggable trait implementations at compile-time." + + +def background_colour(): + """The hero illustration's corner colour, so the card has no visible seam around it.""" + out = subprocess.run( + ["magick", str(HERO), "-format", "%[hex:p{5,5}]", "info:"], + check=True, capture_output=True, text=True, + ).stdout.strip() + return "#" + out[:6] + + +def page(colour): + return f""" + +

Context-Generic Programming

+

{TAG_LINE}

+

contextgeneric.dev

+""" + + +def main(): + with tempfile.TemporaryDirectory() as tmp: + html = pathlib.Path(tmp) / "card.html" + png = pathlib.Path(tmp) / "card.png" + html.write_text(page(background_colour())) + subprocess.run( + ["google-chrome", "--headless=new", "--disable-gpu", "--hide-scrollbars", + "--allow-file-access-from-files", "--window-size=1200,630", + f"--screenshot={png}", html.as_uri()], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + subprocess.run(["magick", str(png), "-quality", "85", str(OUT)], check=True) + print(f"wrote {OUT.relative_to(ROOT)} ({OUT.stat().st_size} bytes)") + + +if __name__ == "__main__": + main() diff --git a/scripts/theme/contrast.py b/scripts/theme/contrast.py new file mode 100755 index 00000000..9e3017c9 --- /dev/null +++ b/scripts/theme/contrast.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Check the site theme's colours against WCAG 2 contrast ratios. + +Reads the token values for each theme from `src/css/custom.css`, resolves `var()` references, blends +translucent colours over their background, and checks each pair below: text at 4.5:1, and focus rings, +admonition borders, the two navbar logos, and the front page's diff marks at 3:1. Text pairs include +the front page's cards on the raised surface. It also checks every token +colour of the two Prism themes in `src/prism/themes.ts`, on the code background, on a highlighted +line's tint, and on the front page's two diff tints. + +Run it from the repository's root after changing a colour: + + python3 scripts/theme/contrast.py + +It exits 1 when a pair falls below its minimum. +""" +import re +import sys +from pathlib import Path + +# (foreground token, background token, minimum ratio, what the pair is) +PAIRS = [ + ("--cgp-text", "--cgp-bg", 4.5, "body text"), + ("--cgp-text", "--cgp-surface", 4.5, "body text on a surface"), + ("--cgp-text", "--cgp-code-bg", 4.5, "plain code text"), + ("--cgp-text", "--cgp-inline-code-bg", 4.5, "inline code"), + ("--cgp-text-muted", "--cgp-bg", 4.5, "secondary text"), + ("--cgp-text-muted", "--cgp-surface", 4.5, "secondary text on a surface"), + ("--cgp-heading", "--cgp-bg", 4.5, "headings"), + ("--ifm-color-content-secondary", "--cgp-bg", 4.5, "secondary content, such as the table of contents"), + ("--ifm-color-primary-contrast-foreground", "--ifm-color-primary-contrast-background", 4.5, "primary alert"), + ("--cgp-link", "--cgp-bg", 4.5, "links"), + ("--cgp-link", "--cgp-surface", 4.5, "links on a surface"), + ("--cgp-link", "--cgp-inline-code-bg", 4.5, "linked inline code"), + ("--cgp-link", "--cgp-red-50", 4.5, "the active sidebar item"), + ("--cgp-link-hover", "--cgp-bg", 4.5, "hovered links"), + ("--cgp-announce-text", "--cgp-announce-bg", 4.5, "the announcement bar"), + ("--cgp-footer-text", "--cgp-footer-bg", 4.5, "footer text"), + ("--cgp-footer-link", "--cgp-footer-bg", 4.5, "footer links"), + ("--cgp-footer-title", "--cgp-footer-bg", 4.5, "footer titles"), + ("--cgp-focus", "--cgp-bg", 3.0, "the focus ring"), + ("--cgp-border", "--cgp-bg", 1.2, "borders (decorative, informational only)"), + ("--ifm-color-info-contrast-foreground", "--ifm-color-info-contrast-background", 4.5, "info admonition"), + ("--ifm-color-success-contrast-foreground", "--ifm-color-success-contrast-background", 4.5, "tip admonition"), + ("--ifm-color-secondary-contrast-foreground", "--ifm-color-secondary-contrast-background", 4.5, "note admonition"), + ("--ifm-color-warning-contrast-foreground", "--ifm-color-warning-contrast-background", 4.5, "warning admonition"), + ("--ifm-color-danger-contrast-foreground", "--ifm-color-danger-contrast-background", 4.5, "danger admonition"), + ("--ifm-color-info-dark", "--ifm-color-info-contrast-background", 3.0, "info admonition border and icon"), + ("--ifm-color-success-dark", "--ifm-color-success-contrast-background", 3.0, "tip admonition border and icon"), + ("--ifm-color-secondary-dark", "--ifm-color-secondary-contrast-background", 3.0, "note admonition border and icon"), + ("--ifm-color-warning-dark", "--ifm-color-warning-contrast-background", 3.0, "warning admonition border and icon"), + ("--ifm-color-danger-dark", "--ifm-color-danger-contrast-background", 3.0, "danger admonition border and icon"), + ("--ifm-color-danger", "--cgp-surface", 4.5, "the front page's quoted diagnostic, first line"), + ("--cgp-surface-raised", "--cgp-diff-removed-mark", 3.0, "the rejected window's cross badge"), + ("--cgp-surface-raised", "--cgp-diff-added-mark", 3.0, "the accepted window's tick badge"), + ("--cgp-text", "--cgp-surface-raised", 4.5, "the front page's cards, text on the raised surface"), + ("--cgp-text-muted", "--cgp-surface-raised", 4.5, "the front page's cards, secondary text on the raised surface"), + ("--cgp-link", "--cgp-surface-raised", 4.5, "the front page's cards, links on the raised surface"), + ("--cgp-heading", "--cgp-surface", 4.5, "headings and cost labels on a surface"), + ("--cgp-heading", "--cgp-surface-raised", 4.5, "card titles on the raised surface"), +] +# The front page's diff tints, laid over the code background: (tint token, its gutter mark, what). +DIFFS = [ + ("--cgp-diff-removed", "--cgp-diff-removed-mark", "the line Rust rejects"), + ("--cgp-diff-added", "--cgp-diff-added-mark", "the lines CGP adds"), +] +LIGHT_ONLY = [("--cgp-on-red", "--cgp-red", 4.5, "text on a red button")] +REPORT_ONLY = [("--cgp-link", "--cgp-text", "links against body text (links are underlined)")] + +BLOCK = re.compile(r"([^{}]+)\{([^{}]*)\}", re.S) +DECL = re.compile(r"(--[\w-]+)\s*:\s*([^;]+);") + + +def parse(css): + css = re.sub(r"/\*.*?\*/", "", css, flags=re.S) + themes = {"light": {}, "dark": {}} + for selector, body in BLOCK.findall(css): + decls = dict(DECL.findall(body)) + if not decls: + continue + if "data-theme='dark'" in selector: + themes["dark"].update(decls) + elif ":root" in selector or "data-theme='light'" in selector: + themes["light"].update(decls) + # The dark theme inherits every light token it does not redefine, as the cascade does. + themes["dark"] = {**themes["light"], **themes["dark"]} + return themes + + +def resolve(tokens, value, depth=0): + value = value.strip() + m = re.fullmatch(r"var\((--[\w-]+)\)", value) + if m: + if depth > 10 or m.group(1) not in tokens: + raise KeyError(m.group(1)) + return resolve(tokens, tokens[m.group(1)], depth + 1) + return value + + +def rgba(value): + value = value.strip() + if value.startswith("#"): + h = value[1:] + if len(h) == 3: + h = "".join(c * 2 for c in h) + return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) + (1.0,) + m = re.fullmatch(r"rgba?\(([^)]*)\)", value) + if m: + parts = [p.strip() for p in m.group(1).split(",")] + r, g, b = (int(p) for p in parts[:3]) + a = float(parts[3]) if len(parts) > 3 else 1.0 + return (r, g, b, a) + raise ValueError(f"cannot read colour {value!r}") + + +def over(fg, bg): + a = fg[3] + return tuple(round(fg[i] * a + bg[i] * (1 - a)) for i in range(3)) + (1.0,) + + +def lum(c): + def ch(x): + x /= 255 + return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 + return 0.2126 * ch(c[0]) + 0.7152 * ch(c[1]) + 0.0722 * ch(c[2]) + + +def ratio(a, b): + la, lb = lum(a), lum(b) + return (max(la, lb) + 0.05) / (min(la, lb) + 0.05) + + +def colour(tokens, name, page_bg): + c = rgba(resolve(tokens, tokens[name])) + return over(c, page_bg) if c[3] < 1 else c + + +def prism_themes(path): + text = Path(path).read_text() + out = {} + for theme in ("light", "dark"): + m = re.search(rf"export const {theme}Theme[^=]*=\s*\{{(.*?)\n\}};", text, re.S) + if not m: + raise SystemExit(f"no `export const {theme}Theme` in {path}") + body = m.group(1) + plain_bg = re.search(r"plain:\s*\{[^}]*backgroundColor:\s*'([^']+)'", body).group(1) + plain_fg = re.search(r"plain:\s*\{[^}]*color:\s*'([^']+)'", body).group(1) + styles = re.findall(r"types:\s*\[([^\]]*)\][^}]*?color:\s*'([^']+)'", body, re.S) + out[theme] = (plain_bg, plain_fg, [(t.strip(), c) for t, c in styles]) + return out + + +LOGOS = [("light", "static/img/cgp-logo.svg"), ("dark", "static/img/cgp-logo-dark.svg")] + + +def logo_fill(path): + fills = set(re.findall(r"fill:(#[0-9a-fA-F]{6})", Path(path).read_text())) + if len(fills) != 1: + raise SystemExit(f"expected one fill colour in {path}, found {sorted(fills)}") + return fills.pop() + + +def main(argv): + site = Path(argv[0]) if argv else Path(__file__).resolve().parents[2] + themes = parse((site / "src/css/custom.css").read_text()) + failed = 0 + for theme, tokens in themes.items(): + print(f"== {theme}") + page_bg = rgba(resolve(tokens, tokens["--cgp-bg"])) + pairs = PAIRS + (LIGHT_ONLY if theme == "light" else []) + for fg, bg, minimum, what in pairs: + b = colour(tokens, bg, page_bg) + f = colour(tokens, fg, b) + r = ratio(f, b) + ok = r >= minimum + failed += not ok + print(f" {'ok ' if ok else 'FAIL'} {r:5.2f} >= {minimum:<3} {what}") + for fg, bg, what in REPORT_ONLY: + r = ratio(colour(tokens, fg, page_bg), colour(tokens, bg, page_bg)) + print(f" info {r:5.2f} {what}") + for logo_theme, path in LOGOS: + if logo_theme == theme: + r = ratio(rgba(logo_fill(site / path)), page_bg) + ok = r >= 3.0 + failed += not ok + print(f" {'ok ' if ok else 'FAIL'} {r:5.2f} >= 3.0 the navbar logo, {path}") + for theme, (bg, fg, styles) in prism_themes(site / "src/prism/themes.ts").items(): + print(f"== prism {theme}") + b = rgba(bg) + tokens = themes[theme] + hl = over(rgba(resolve(tokens, tokens["--cgp-highlight-line"])), b) + tints = [over(rgba(resolve(tokens, tokens[tint])), b) for tint, _, _ in DIFFS] + for name, c in [("plain", fg)] + styles: + r = ratio(rgba(c), b) + rh = ratio(rgba(c), hl) + rd = [ratio(rgba(c), t) for t in tints] + ok = min([r, rh] + rd) >= 4.5 + failed += not ok + diffs = " / ".join(f"{x:5.2f}" for x in rd) + print(f" {'ok ' if ok else 'FAIL'} {r:5.2f} / {rh:5.2f} highlighted / {diffs} diff >= 4.5 {name}") + for (tint, mark, what), t in zip(DIFFS, tints): + r = ratio(rgba(resolve(tokens, tokens[mark])), t) + ok = r >= 3.0 + failed += not ok + print(f" {'ok ' if ok else 'FAIL'} {r:5.2f} >= 3.0 the gutter mark on {what}") + print("all pairs pass" if not failed else f"{failed} pair(s) below the minimum") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/src/components/HomepageFeatures/index.tsx b/src/components/HomepageFeatures/index.tsx index 9fdaea50..13e415b3 100644 --- a/src/components/HomepageFeatures/index.tsx +++ b/src/components/HomepageFeatures/index.tsx @@ -1,104 +1,91 @@ import type {ReactNode} from 'react'; -import clsx from 'clsx'; +import Link from '@docusaurus/Link'; import Heading from '@theme/Heading'; +import useBaseUrl from '@docusaurus/useBaseUrl'; import styles from './styles.module.css'; -type FeatureItem = { +// The first four headline features, in the order and with the titles the knowledge base's +// identity.md fixes; the hero's reassurance line carries the fifth, Still Ordinary Rust, so no card +// repeats it. Each card is one link to the page that answers it, and each illustration is decorative +// beside its title, so its alt text is empty. +type Feature = { title: string; + body: ReactNode; + to: string; image: string; - description: ReactNode; }; -const FeatureList: FeatureItem[] = [ +const FEATURES: Feature[] = [ { - title: 'Modular Component System', - image: '/img/features/modular-component-system-480p.png', - description: ( + title: 'One Interface, Many Implementations', + body: ( <> - Decouple interface definitions from implementations using provider traits. - Write multiple context-generic providers that can coexist without conflicts. + The two encoders above coexist because each one lives on its own provider type, and each type + names the one it uses. ), + to: '/docs/concepts/coherence', + image: '/img/features/one-interface-many-implementations.webp', }, { - title: 'Highly Expressive Macros', - image: '/img/features/highly-expressive-macros-480p.png', - description: ( - <> - Write abstract programs generic over contexts without managing long lists - of generic parameters. Achieve expressiveness rivaling dynamic languages. - - ), - }, - { - title: 'Type-Safe Composition', - image: '/img/features/type-safe-composition-480p.png', - description: ( - <> - All component wiring is verified at compile time. Missing dependencies are - caught early, with no runtime errors possible from CGP constructs. - - ), - }, - { - title: 'No-Std Friendly', - image: '/img/features/no-std-friendly-480p.png', - description: ( + title: 'Zero-Cost Abstraction', + body: ( <> - Build fully abstract programs without concrete dependencies. Deploy to - embedded systems, kernels, WebAssembly, or symbolic execution platforms. + Provider selection resolves at compile time into a direct call, without a container or a + vtable lookup. ), + to: '/docs/comparisons/dynamic-dispatch', + image: '/img/features/zero-cost-abstraction.webp', }, { - title: 'Zero-Cost Abstraction', - image: '/img/features/zero-cost-abstraction-480p.png', - description: ( + title: 'Type-Safe Wiring', + body: ( <> - All CGP operations happen at compile time using Rust's type system. - No runtime overhead, upholding Rust's zero-cost abstraction guarantee. + A provider states its needs, as #[uses(Display)] does above, and a{' '} + check_components! assertion or a use of the component fails the build when a + context lacks one. ), + to: '/docs/comparisons/dependency-injection', + image: '/img/features/type-safe-wiring.webp', }, { - title: 'Bypass Coherence Rules', - image: '/img/features/bypass-coherence-rules-480p.png', - description: ( + title: 'Abstract Over Every Dependency', + body: ( <> - Enable overlapping and orphan trait implementations without restriction. - Define implementations for types you don't own and traits you don't control. + Core logic names abstract error, runtime, and I/O types, and each context supplies concrete + ones, so the core builds for no_std where the chosen implementations allow. ), + to: '/docs/concepts/modular-error-handling', + image: '/img/features/abstract-over-every-dependency.webp', }, ]; -function Feature({title, image, description}: FeatureItem) { +function FeatureCard({title, body, to, image}: Feature): ReactNode { return ( -
-
- {title} -
-
- {title} -

{description}

-
-
+
  • + + + + + {title} + + {body} + + +
  • ); } -export default function HomepageFeatures(): ReactNode { +// The cards sit two to a row, each illustration beside its text, and one to a row on a phone. +export default function FeatureCards(): ReactNode { return ( -
    -
    - - Why Context-Generic Programming? - -
    - {FeatureList.map((props, idx) => ( - - ))} -
    -
    -
    +
      + {FEATURES.map((feature) => ( + + ))} +
    ); } diff --git a/src/components/HomepageFeatures/styles.module.css b/src/components/HomepageFeatures/styles.module.css index cae50959..0ea1b38f 100644 --- a/src/components/HomepageFeatures/styles.module.css +++ b/src/components/HomepageFeatures/styles.module.css @@ -1,34 +1,99 @@ -.features { +/* The five headline features as linked cards, inside the front page's own section and container. + Colours come from the site theme's tokens in src/css/custom.css. */ +.cards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.25rem; + margin: 0; + padding: 0; + list-style: none; +} + +.card { + display: flex; + gap: 1rem; + height: 100%; + padding: 1.25rem 1.25rem 1.4rem; + border: 1px solid var(--cgp-border); + border-radius: 14px; + background: var(--cgp-surface-raised); + color: var(--cgp-text); + text-decoration: none; + transition: border-color 0.15s, transform 0.15s; +} + +.card:hover { + color: var(--cgp-text); + text-decoration: none; + border-color: var(--cgp-link); + transform: translateY(-2px); +} + +/* The illustrations have white backgrounds, so each sits in a rounded frame that reads as a tile in + both themes. */ +.image { + display: block; + flex: none; + align-self: flex-start; + width: 112px; + height: auto; + border-radius: 18px; + background: var(--cgp-image-frame); + box-shadow: 0 0 0 1px var(--ifm-color-emphasis-200); +} + +/* The illustrations' white is the images' own background, so the dark theme dims each image and its + frame together, as it does the hero art. */ +html[data-theme='dark'] .image { + filter: brightness(0.9); +} + +.text { display: flex; flex-direction: column; - align-items: center; - padding: 4rem 0; - width: 100%; + gap: 0.45rem; + min-width: 0; } -.featuresTitle { - font-size: 2.5rem; - margin-bottom: 3rem; +.title { + font-size: 1.1rem; + line-height: 1.3; + margin: 0; + color: var(--cgp-heading); } -.featureSvg { - height: 180px; - width: 180px; - margin-bottom: 1rem; +.card:hover .title, +.card:focus-visible .title { + color: var(--cgp-link); } -@media screen and (max-width: 996px) { - .features { - padding: 2rem 0; +.body { + font-size: 0.95rem; + color: var(--cgp-text-muted); +} + +/* An attribute such as `#[uses(Display)]` breaks after its `#` in a narrow column, so inline code + keeps to one line. */ +.body code { + white-space: nowrap; +} + +@media (prefers-reduced-motion: reduce) { + .card { + transition: none; } - .featuresTitle { - font-size: 2rem; - margin-bottom: 2rem; + .card:hover { + transform: none; + } +} + +@media screen and (max-width: 996px) { + .cards { + grid-template-columns: minmax(0, 1fr); } - .featureSvg { - height: 150px; - width: 150px; + .image { + width: 88px; } } diff --git a/src/css/custom.css b/src/css/custom.css index 308c34b3..bae5d428 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -1,52 +1,442 @@ /** - * Any CSS included here will be global. The classic template - * bundles Infima by default. Infima is a CSS framework designed to - * work well for content-centric websites. + * The site's theme: colour tokens for each theme, the Infima variables they feed, and the fonts. The + * palette keeps the CGP logo's red, #8f1f1d, and builds the rest around it: a tint scale of the same + * hue, warm neutrals, and admonition and status colours made for it. The code colours live in + * src/prism/themes.ts. In the dark theme the logo's red reaches only about 2:1 against the + * background, so a lighter tint of the same hue carries links and other text, and `--cgp-red` stays + * for filled elements with white text. + * + * Page styles use these tokens rather than hex colours. After changing a colour, run + * `python3 scripts/theme/contrast.py`, which checks every pair against WCAG AA. The knowledge base's + * website section records the palette and its reasons. */ -/* You can override the default Infima variables here. */ -:root { - --ifm-color-primary: #5D0705; - --ifm-color-primary-dark: #4A0504; - --ifm-color-primary-darker: #370304; - --ifm-color-primary-darkest: #240202; - --ifm-color-primary-light: #D4A5A0; - --ifm-color-primary-lighter: #E8D4CF; - --ifm-color-primary-lightest: #F5E9E6; - --ifm-code-font-size: 95%; - --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); +/* The fonts: Inter for body text and headings, and JetBrains Mono for code, self-hosted under + static/fonts/. Their @font-face rules are a style tag in docusaurus.config.ts, because a url() here + would be copied to a hashed name that the preload cannot match. Each face has a fallback sized to + its metrics, so text does not shift when the font arrives. The site ships no italic code face, so + the code themes set comments upright. */ + +/* Inter's average width is 104.93% of Arial's, and its ascent and descent are 0.969 and 0.241 em, + so the overrides divide those by the size adjustment. */ +@font-face { + font-family: 'Inter Fallback'; + src: local('Arial'), local('ArialMT'), local('Liberation Sans'), local('Helvetica'); + font-weight: 400 500; + size-adjust: 104.93%; + ascent-override: 92.32%; + descent-override: 22.99%; + line-gap-override: 0%; +} + +/* The bold fallback names a bold face, so the browser does not embolden the regular one. */ +@font-face { + font-family: 'Inter Fallback'; + src: local('Arial Bold'), local('Arial-BoldMT'), local('Liberation Sans Bold'), local('Helvetica Bold'); + font-weight: 600 700; + size-adjust: 104.93%; + ascent-override: 92.32%; + descent-override: 22.99%; + line-gap-override: 0%; +} + +@font-face { + font-family: 'JetBrains Mono Fallback'; + src: local('Courier New'), local('Liberation Mono'); + size-adjust: 100%; + ascent-override: 102%; + descent-override: 30%; + line-gap-override: 0%; +} + +/* The light theme. `html[data-theme=...]` matches the specificity of Infima's own dark-theme rules. */ +:root, +html[data-theme='light'] { + /* The brand red and its tint scale. */ + --cgp-red: #8f1f1d; + --cgp-red-50: #fcf1ef; + --cgp-red-100: #f8e1dd; + --cgp-red-200: #f0c2bb; + --cgp-red-300: #e59a90; + --cgp-red-400: #d06b61; + --cgp-red-500: #b23a33; + --cgp-red-700: #741816; + --cgp-red-800: #5a1311; + --cgp-red-900: #3d0d0c; + + /* Warm neutrals. Infima's own grey scale is cool, so it takes the same warm values. */ + --ifm-color-gray-100: #f5efea; + --ifm-color-gray-200: #ebe2dc; + --ifm-color-gray-300: #ddd1ca; + --ifm-color-gray-400: #c4b6ae; + --ifm-color-gray-500: #a39189; + --ifm-color-gray-600: #7d6b64; + --ifm-color-gray-700: #5e504c; + --ifm-color-gray-800: #45393a; + --ifm-color-gray-900: #2b2221; + --cgp-bg: #fdfaf7; + --cgp-surface: #f7f0ea; + --cgp-surface-raised: #ffffff; + --cgp-border: #e3d5cb; + --cgp-text: #261d1b; + --cgp-text-muted: #66574f; + --cgp-heading: #1d1514; + + /* Roles. */ + --cgp-link: var(--cgp-red); + --cgp-link-hover: var(--cgp-red-700); + --cgp-focus: var(--cgp-red-500); + --cgp-code-bg: #f4ece5; + --cgp-inline-code-bg: #f1e6de; + --cgp-highlight-line: rgba(214, 150, 40, 0.18); + /* The front page's diff lines: a tint for the line Rust rejects and the lines CGP adds, and a + stronger colour for each one's gutter mark and verdict badge. */ + --cgp-diff-removed: rgba(196, 55, 43, 0.1); + --cgp-diff-added: rgba(40, 150, 70, 0.16); + --cgp-diff-removed-mark: var(--ifm-color-danger); + --cgp-diff-added-mark: #2f7a40; + --cgp-selection: rgba(178, 58, 51, 0.18); + --cgp-image-frame: #ffffff; + --cgp-hero-art-bg: #fdefe1; + --cgp-announce-bg: #fbf1ed; + --cgp-announce-text: #4a2f2b; + --cgp-footer-bg: #4a1110; + --cgp-footer-text: #f7efec; + --cgp-footer-title: #ffffff; + --cgp-footer-link: #fdf4f1; + --cgp-on-red: #ffffff; + + /* Infima: the primary scale. */ + --ifm-color-primary: var(--cgp-red); + --ifm-color-primary-dark: #811c1a; + --ifm-color-primary-darker: #7a1a19; + --ifm-color-primary-darkest: #641614; + --ifm-color-primary-light: #9d2220; + --ifm-color-primary-lighter: #a42422; + --ifm-color-primary-lightest: #b72826; + + /* Infima: the warm grey scale that borders, hovers, and secondary text use. */ + --ifm-color-emphasis-0: #ffffff; + --ifm-color-emphasis-100: #f5efea; + --ifm-color-emphasis-200: #ebe2dc; + --ifm-color-emphasis-300: #ddd1ca; + --ifm-color-emphasis-400: #c4b6ae; + --ifm-color-emphasis-500: #a39189; + --ifm-color-emphasis-600: #7d6b64; + --ifm-color-emphasis-700: #5e504c; + --ifm-color-emphasis-800: #45393a; + --ifm-color-emphasis-900: #2b2221; + --ifm-color-emphasis-1000: #120d0c; + + /* Infima: surfaces and text. Infima sets the two content colours to literal greys, which the table of + contents and other secondary text read, so they point at the tokens too. */ + --ifm-color-content: var(--cgp-text); + --ifm-color-content-secondary: var(--cgp-text-muted); + --ifm-color-primary-contrast-background: var(--cgp-red-50); + --ifm-color-primary-contrast-foreground: var(--cgp-red-800); + --ifm-background-color: var(--cgp-bg); + --ifm-background-surface-color: var(--cgp-surface); + --ifm-font-color-base: var(--cgp-text); + --ifm-font-color-secondary: var(--cgp-text-muted); + --ifm-heading-color: var(--cgp-heading); + --ifm-link-color: var(--cgp-link); + --ifm-link-hover-color: var(--cgp-link-hover); + --ifm-navbar-background-color: var(--cgp-bg); + --ifm-navbar-link-color: var(--cgp-text); + --ifm-navbar-link-hover-color: var(--cgp-link); + --ifm-menu-color: var(--cgp-text-muted); + --ifm-menu-color-active: var(--cgp-red); + --ifm-menu-color-background-active: var(--cgp-red-50); + --ifm-menu-color-background-hover: var(--ifm-color-emphasis-100); + --ifm-toc-border-color: var(--cgp-border); + --ifm-hr-background-color: var(--cgp-border); + --ifm-table-border-color: var(--cgp-border); + --ifm-table-stripe-background: rgba(143, 31, 29, 0.03); + --ifm-table-head-background: var(--cgp-surface); + --ifm-code-background: var(--cgp-inline-code-bg); + --ifm-pre-background: var(--cgp-code-bg); + --ifm-card-background-color: var(--cgp-surface-raised); + --ifm-dropdown-background-color: var(--cgp-surface-raised); + --ifm-breadcrumb-item-background-active: var(--cgp-red-50); + --ifm-code-font-size: 90%; + --ifm-font-family-base: 'Inter', 'Inter Fallback', system-ui, -apple-system, 'Segoe UI', Roboto, + Ubuntu, Cantarell, 'Noto Sans', sans-serif; + --ifm-heading-font-family: var(--ifm-font-family-base); + --ifm-heading-font-weight: 600; + --ifm-font-family-monospace: 'JetBrains Mono', 'JetBrains Mono Fallback', SFMono-Regular, Menlo, + Consolas, monospace; --ifm-container-width-xl: 1400px; + --docusaurus-highlighted-code-line-bg: var(--cgp-highlight-line); + --ifm-scrollbar-track-background-color: transparent; + --ifm-scrollbar-thumb-background-color: var(--ifm-color-emphasis-400); + --ifm-scrollbar-thumb-hover-background-color: var(--ifm-color-emphasis-500); + + /* Infima: admonitions. `note` uses secondary, `tip` success, `info` info, `warning` warning, and + `danger` danger. The four kinds the site uses sit away from the brand red, so a link never looks + like an admonition; `danger`, which no page uses, keeps a red distinct from the brand's. */ + --ifm-color-info: #4f7387; + --ifm-color-info-dark: #4f7387; + --ifm-color-info-contrast-background: #edf3f6; + --ifm-color-info-contrast-foreground: #1c2f3a; + --ifm-color-success: #4a7a55; + --ifm-color-success-dark: #4a7a55; + --ifm-color-success-contrast-background: #edf4ee; + --ifm-color-success-contrast-foreground: #1b3522; + --ifm-color-secondary: #e9e0da; + --ifm-color-secondary-dark: #95857e; + --ifm-color-secondary-contrast-background: #f4efeb; + --ifm-color-secondary-contrast-foreground: #362b28; + --ifm-color-warning: #b9821f; + --ifm-color-warning-dark: #b9821f; + --ifm-color-warning-contrast-background: #fbf3e2; + --ifm-color-warning-contrast-foreground: #45300c; + --ifm-color-danger: #c4372b; + --ifm-color-danger-dark: #c4372b; + --ifm-color-danger-contrast-background: #fcebe9; + --ifm-color-danger-contrast-foreground: #4a1111; +} + +/* The dark theme. It redefines the tints of the red scale that it uses, so a tint keeps its role in + both themes: `--cgp-red-50`, for example, is the faint surface behind the active sidebar item. */ +html[data-theme='dark'] { + --cgp-red-50: #2a1716; + --cgp-red-100: #3a1b19; + --cgp-red-300: #c9584f; + --cgp-red-400: #e0766c; + --cgp-red-500: #ef8f86; + + --cgp-bg: #0e0c0c; + --cgp-surface: #171414; + --cgp-surface-raised: #1f1b1a; + --cgp-border: #332c2b; + --cgp-text: #ece3df; + --cgp-text-muted: #b3a39e; + --cgp-heading: #f7f0ed; + + --cgp-link: #ef8f86; + --cgp-link-hover: #f7b6ae; + --cgp-focus: #ef8f86; + --cgp-code-bg: #191515; + --cgp-inline-code-bg: #262120; + --cgp-highlight-line: rgba(230, 170, 60, 0.14); + --cgp-diff-removed: rgba(232, 116, 106, 0.14); + --cgp-diff-added: rgba(100, 200, 120, 0.16); + --cgp-diff-added-mark: #7cc58a; + --cgp-selection: rgba(239, 143, 134, 0.28); + --cgp-image-frame: #fdfaf7; + --cgp-announce-bg: #1c1818; + --cgp-announce-text: #f1e7e4; + --cgp-footer-bg: #2b0c0b; + --cgp-footer-text: #eee4e1; + --cgp-footer-title: #ffffff; + --cgp-footer-link: #f8efec; + + --ifm-color-primary: #ef8f86; + --ifm-color-primary-dark: #ec7d72; + --ifm-color-primary-darker: #ea7369; + --ifm-color-primary-darkest: #e2554a; + --ifm-color-primary-light: #f2a19a; + --ifm-color-primary-lighter: #f4aba4; + --ifm-color-primary-lightest: #f8c9c4; + + --ifm-color-emphasis-0: #0e0c0c; + --ifm-color-emphasis-100: #1a1716; + --ifm-color-emphasis-200: #262120; + --ifm-color-emphasis-300: #3b3332; + --ifm-color-emphasis-400: #5d4d4a; + --ifm-color-emphasis-500: #7f6d69; + --ifm-color-emphasis-600: #a3918c; + --ifm-color-emphasis-700: #c1b2ad; + --ifm-color-emphasis-800: #dccfca; + --ifm-color-emphasis-900: #ede4e0; + --ifm-color-emphasis-1000: #fbf7f5; + + --ifm-color-content: var(--cgp-text); + --ifm-color-content-secondary: var(--cgp-text-muted); + --ifm-color-primary-contrast-background: var(--cgp-red-50); + --ifm-color-primary-contrast-foreground: #f8e1dd; + --ifm-background-color: var(--cgp-bg); + --ifm-background-surface-color: var(--cgp-surface); + --ifm-font-color-base: var(--cgp-text); + --ifm-font-color-secondary: var(--cgp-text-muted); + --ifm-heading-color: var(--cgp-heading); + --ifm-link-color: var(--cgp-link); + --ifm-link-hover-color: var(--cgp-link-hover); + --ifm-navbar-background-color: var(--cgp-bg); + --ifm-navbar-link-color: var(--cgp-text); + --ifm-navbar-link-hover-color: var(--cgp-link); + --ifm-menu-color: var(--cgp-text-muted); + --ifm-menu-color-active: var(--cgp-link); + --ifm-menu-color-background-active: var(--cgp-red-50); + --ifm-menu-color-background-hover: var(--ifm-color-emphasis-100); + --ifm-toc-border-color: var(--cgp-border); + --ifm-hr-background-color: var(--cgp-border); + --ifm-table-border-color: var(--cgp-border); + --ifm-table-stripe-background: rgba(236, 227, 223, 0.03); + --ifm-table-head-background: var(--cgp-surface); + --ifm-code-background: var(--cgp-inline-code-bg); + --ifm-pre-background: var(--cgp-code-bg); + --ifm-card-background-color: var(--cgp-surface-raised); + --ifm-dropdown-background-color: var(--cgp-surface-raised); + --ifm-breadcrumb-item-background-active: var(--cgp-red-50); + --docusaurus-highlighted-code-line-bg: var(--cgp-highlight-line); + --ifm-scrollbar-track-background-color: transparent; + --ifm-scrollbar-thumb-background-color: var(--ifm-color-emphasis-400); + --ifm-scrollbar-thumb-hover-background-color: var(--ifm-color-emphasis-500); + + --ifm-color-info: #7ea3b7; + --ifm-color-info-dark: #7ea3b7; + --ifm-color-info-contrast-background: #1a2328; + --ifm-color-info-contrast-foreground: #d7e4eb; + --ifm-color-success: #79a884; + --ifm-color-success-dark: #79a884; + --ifm-color-success-contrast-background: #18231b; + --ifm-color-success-contrast-foreground: #d4e8d9; + --ifm-color-secondary: #332c2b; + --ifm-color-secondary-dark: #8d7c76; + --ifm-color-secondary-contrast-background: #1b1717; + --ifm-color-secondary-contrast-foreground: #e6dcd8; + --ifm-color-warning: #d4a246; + --ifm-color-warning-dark: #d4a246; + --ifm-color-warning-contrast-background: #2a2114; + --ifm-color-warning-contrast-foreground: #f1e1c2; + --ifm-color-danger: #e8746a; + --ifm-color-danger-dark: #e8746a; + --ifm-color-danger-contrast-background: #2c1716; + --ifm-color-danger-contrast-foreground: #f3d4d0; +} + +/* Inline code and links inside an admonition get a tint of the admonition's own hue, in place of + Infima's bright green, blue, and red. */ +.alert--info { + --ifm-alert-background-color-highlight: rgba(79, 115, 135, 0.14); +} + +.alert--success { + --ifm-alert-background-color-highlight: rgba(74, 122, 85, 0.14); +} + +.alert--secondary { + --ifm-alert-background-color-highlight: rgba(149, 133, 126, 0.16); +} + +.alert--warning { + --ifm-alert-background-color-highlight: rgba(185, 130, 31, 0.14); +} + +.alert--danger { + --ifm-alert-background-color-highlight: rgba(196, 55, 43, 0.12); } -.footer { - --ifm-footer-background-color: #504938; - --ifm-link-color: #FCF7E9; +/* Code shows the characters a reader types, so `->` and `=>` never join into one glyph. JetBrains + Mono's regular weight looks thin beside Inter, so code sets at 500, except inside bold text, + headings, and table headers, where it keeps the weight around it. */ +code, +pre, +kbd { + font-variant-ligatures: none; + font-weight: 500; } +:is(strong, b, th, h1, h2, h3, h4, h5, h6) :is(code, kbd) { + font-weight: inherit; +} + +.navbar__title { + font-family: var(--ifm-heading-font-family); +} + +/* Firefox styles scrollbars only through `scrollbar-color`, so the sidebar's thin scrollbar takes the + theme's colours there too, instead of a white track beside the dark sidebar. */ +.thin-scrollbar { + scrollbar-color: var(--ifm-scrollbar-thumb-background-color) + var(--ifm-scrollbar-track-background-color); +} + +::selection { + background-color: var(--cgp-selection); +} + +/* A visible focus ring on every link, button, and control. */ +:focus-visible { + outline: 2px solid var(--cgp-focus); + outline-offset: 2px; + border-radius: 2px; +} + +/* Prose links are underlined, because colour alone does not separate them from body text. Heading + anchors and the generated category cards keep their own styles. */ +.markdown a:not(.hash-link):not(.card) { + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 0.18em; + text-decoration-color: color-mix(in srgb, currentColor 45%, transparent); +} + +.markdown a:not(.hash-link):not(.card):hover { + text-decoration-color: currentColor; +} + +/* The navbar sits on the page background with a hairline below it. */ +.navbar { + box-shadow: none; + border-bottom: 1px solid var(--cgp-border); +} + +/* The announcement bar takes its colours from the config, which points them at these tokens. */ .theme-announcement-bar { - font-size: 1.2em; -} - -[data-theme='light'] { - --ifm-color-primary: #5D0705; - --ifm-color-primary-dark: #4A0504; - --ifm-color-primary-darker: #370304; - --ifm-color-primary-darkest: #240202; - --ifm-color-primary-light: #D4A5A0; - --ifm-color-primary-lighter: #E8D4CF; - --ifm-color-primary-lightest: #F5E9E6; - --ifm-code-font-size: 95%; - --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); -} - -/* For readability concerns, you should choose a lighter palette in dark mode. */ -[data-theme='dark'] { - --ifm-color-primary: #E8A89A; - --ifm-color-primary-dark: #D99080; - --ifm-color-primary-darker: #CA7868; - --ifm-color-primary-darkest: #AB5F50; - --ifm-color-primary-light: #F5D4CC; - --ifm-color-primary-lighter: #F9E4DD; - --ifm-color-primary-lightest: #FCF0EB; - --docusaurus-highlighted-code-line-bg: rgba(232, 168, 154, 0.1); + font-size: 1.1em; + border-bottom: 1px solid var(--cgp-border); +} + +.theme-announcement-bar a { + color: inherit; +} + +/* The footer is a deep red in both themes. */ +.footer--dark { + --ifm-footer-background-color: var(--cgp-footer-bg); + --ifm-footer-color: var(--cgp-footer-text); + --ifm-footer-link-color: var(--cgp-footer-link); + --ifm-footer-link-hover-color: var(--cgp-footer-title); + --ifm-footer-title-color: var(--cgp-footer-title); +} + +.footer--dark a { + color: var(--cgp-footer-link); +} + +/* Content images keep their light backgrounds, because an image loaded by follows the operating + system's colour scheme rather than the site's switch. In the dark theme each one sits in a + paper-coloured frame, so it reads as a tile rather than a bright hole in the page. */ +html[data-theme='dark'] .markdown img { + background-color: var(--cgp-image-frame); + border-radius: 12px; + padding: 0.5rem; +} + +/* The footer's links share its text colour, so the links inside the licence line are underlined. */ +.footer__copyright a { + text-decoration: underline; + text-underline-offset: 0.18em; +} + +/* Infima's primary hero, which the blog archive's header uses, fills with the primary colour: the full + brand red in the light theme and a loud coral in the dark one. It takes the warm surface instead, + with the heading colour for its text. */ +.hero--primary { + --ifm-hero-background-color: var(--cgp-surface); + --ifm-hero-text-color: var(--cgp-heading); + border-bottom: 1px solid var(--cgp-border); +} + +/* The blog list's post titles are links set at heading size; they take the heading colour and turn + red on hover, so a page of posts does not read as a wall of red. */ +article > header > h2 > a { + color: var(--ifm-heading-color); +} + +article > header > h2 > a:hover { + color: var(--ifm-link-color); + text-decoration: none; } diff --git a/src/pages/index.module.css b/src/pages/index.module.css index 6976b825..1962041c 100644 --- a/src/pages/index.module.css +++ b/src/pages/index.module.css @@ -1,156 +1,790 @@ /** - * CSS files with the .module.css suffix will be treated as CSS modules - * and scoped locally. + * The front page's layout, on the site theme's tokens from src/css/custom.css; no colour here is a + * literal. The knowledge base's homepage guide sets the targets: the hero copy beside the hero art, + * then both code blocks side by side, so the whole first screen fits at 1920x1080 and the tops of both + * blocks show at 1440x900. */ +.page { + --page-gutter: 1.5rem; + /* One spacing scale for the page: the padding of each section band, the gap between blocks inside a + band, the gap between the parts of one group, and the gap that ties a mark to its text. */ + --space-section: 4rem; + --space-block: 1.5rem; + --space-group: 1rem; + --space-tight: 0.5rem; + /* Wide enough that the numbered rejected block, whose longest line is 70 characters, fits its + window at 1440 px without scrolling. */ + --page-width: 1280px; +} + +/* One container for every band, so the title, the code, and the essay share a left edge. */ +.container { + max-width: calc(var(--page-width) + 2 * var(--page-gutter)); + margin: 0 auto; + padding: 0 var(--page-gutter); +} + +/* The hero. A soft glow in the brand's tints sits behind the art, and a faint dot grid across the + band, both drawn in CSS. */ .hero { - background-color: #fcefe1; + position: relative; + overflow: hidden; + background-color: var(--cgp-surface); + background-image: + radial-gradient(circle at 82% 45%, color-mix(in srgb, var(--cgp-red-200) 45%, transparent) 0, transparent 34%), + radial-gradient(color-mix(in srgb, var(--cgp-text) 9%, transparent) 1px, transparent 1px); + background-size: auto, 22px 22px; + border-bottom: 1px solid var(--cgp-border); } -.heroInner { - padding: 4rem 2rem; +html[data-theme='dark'] .hero { + background-image: + radial-gradient(circle at 82% 45%, color-mix(in srgb, var(--cgp-red-300) 11%, transparent) 0, transparent 34%), + radial-gradient(color-mix(in srgb, var(--cgp-text) 8%, transparent) 1px, transparent 1px); } -.heroOuter { - display: flex; +.heroGrid { + display: grid; + /* The copy column stops near the tag line's width, and the art centres in the rest, so the hero + leaves no wide gap between them on a large screen. */ + grid-template-columns: minmax(0, 52rem) minmax(auto, 1fr); align-items: center; - margin: 0 auto; - max-width: 1100px; - padding: 0 0.5rem; - gap: 1.5rem; + gap: 2.5rem; + padding-top: 1rem; + padding-bottom: 1rem; } -.heroProjectTagline { - color: var(--ifm-color-primary-dark); +.heroTitle { font-size: 3rem; - margin: 0; + line-height: 1.05; + letter-spacing: -0.02em; + margin: 0 0 0.6rem; } -.heroLogo { - display: block; - margin: 0; - margin-left: auto; - width: 300px; - flex-shrink: 0; +.heroTagline { + font-family: var(--ifm-heading-font-family); + font-size: 1.4rem; + font-weight: 600; + line-height: 1.3; + color: var(--cgp-heading); + margin: 0 0 0.5rem; + max-width: 34em; + text-wrap: balance; } -.heroTitleTextHtml { - display: block; - margin-top: 0.5rem; - line-height: 1.2; +.heroReassurance { + font-size: 1.05rem; + color: var(--cgp-text-muted); + margin: 0 0 0.75rem; + max-width: 40em; } -.heroTitleTextHtml b { - color: #911f1c; +/* The install line looks like a terminal prompt, with a button that copies the command. */ +.install { + display: inline-flex; + align-items: center; + gap: 0.75rem; + margin: 0 0 0.75rem; + padding: 0.35rem 0.4rem 0.35rem 0.9rem; + border: 1px solid var(--cgp-border); + border-radius: 10px; + background: var(--cgp-code-bg); } -.indexCtas { - --ifm-button-size-multiplier: 1.2; +.install code { + background: none; + border: 0; + padding: 0; + font-size: 0.95rem; + color: var(--cgp-text); +} + +.prompt { + color: var(--cgp-text-muted); + user-select: none; +} + +.copy { + font: inherit; + font-size: 0.8rem; + font-weight: 600; + padding: 0.25rem 0.6rem; + border: 1px solid var(--cgp-border); + border-radius: 7px; + background: var(--cgp-surface-raised); + color: var(--cgp-text-muted); + cursor: pointer; +} + +.copy:hover { + color: var(--cgp-link); + border-color: var(--cgp-link); +} + +.heroLinks { display: flex; flex-wrap: wrap; - gap: 1rem; - margin-top: 2rem; + align-items: center; + gap: 0.75rem; } -.indexCtasGitHubButtonWrapper { - display: flex; +.primaryButton, +.secondaryButton { + display: inline-flex; align-items: center; + justify-content: center; + min-height: 2.75rem; + padding: 0 1.4rem; + border-radius: 10px; + font-family: var(--ifm-heading-font-family); + font-size: 1.05rem; + font-weight: 700; + text-decoration: none; } -.indexCtasGitHubButton { +.primaryButton, +.primaryButton:hover { + background: var(--cgp-red); + color: var(--cgp-on-red); + text-decoration: none; +} + +.primaryButton:hover { + background: var(--cgp-red-700); +} + +.secondaryButton, +.secondaryButton:hover { + border: 1px solid var(--ifm-color-emphasis-400); + color: var(--ifm-heading-color); + text-decoration: none; +} + +.secondaryButton:hover { + background: var(--cgp-surface-raised); + border-color: var(--cgp-link); +} + +.starButton { border: 0; overflow: hidden; + margin-left: 0.25rem; } -.section { - padding: 4rem 2rem; +/* The hero art has an opaque background of its own. Its edges fade out, so it never shows a + rectangle against the band; in the dark theme it sits on a circle of its own background colour. */ +.heroArtFrame { + display: grid; + place-items: center; + justify-self: center; +} + +.heroArt { + display: block; + width: 280px; + height: auto; + /* A mask reads only alpha, so its colour stands for "opaque", not for a colour on the page. */ + mask-image: radial-gradient(closest-side, black 72%, transparent 100%); +} + +html[data-theme='dark'] .heroArtFrame { + width: 270px; + height: 270px; + border-radius: 50%; + background: var(--cgp-hero-art-bg); + box-shadow: 0 0 0 6px color-mix(in srgb, var(--cgp-hero-art-bg) 30%, transparent); +} + +html[data-theme='dark'] .heroArt { + width: 236px; +} + +/* The art's own background is the brightest thing on the dark page, so the dark theme dims the art + and its circle together, without redrawing them. */ +html[data-theme='dark'] .heroArtFrame { + filter: brightness(0.9); +} + +/* The code band: two editor windows side by side, ending on the caption. The tinted section below it + marks where the band ends. */ +.codeBand { + padding: 0.75rem 0 2.5rem; +} + +.codeColumns { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.5rem; + align-items: stretch; } -.sectionAlt { - background-color: var(--ifm-color-emphasis-200); +.window { + display: flex; + flex-direction: column; + margin: 0; + min-width: 0; + border: 1px solid var(--cgp-border); + border-radius: 14px; + overflow: hidden; + background: var(--cgp-code-bg); } -[data-theme='dark'] .sectionAlt { - background-color: var(--ifm-color-emphasis-200); +.windowBar { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.55rem 0.9rem; + border-bottom: 1px solid var(--cgp-border); + background: var(--cgp-surface-raised); + font-family: var(--ifm-heading-font-family); + font-size: 0.98rem; + font-weight: var(--ifm-heading-font-weight); + color: var(--ifm-heading-color); } -.codeExample { - background-color: var(--ifm-code-background); - border-radius: var(--ifm-code-border-radius); - padding: 1rem; +.verdictMark { + display: inline-grid; + place-items: center; + width: 1.4rem; + height: 1.4rem; + border-radius: 50%; + font-size: 0.85rem; + font-weight: 700; + color: var(--cgp-surface-raised); +} + +.rejected .verdictMark { + background: var(--cgp-diff-removed-mark); +} + +.accepted .verdictMark { + background: var(--cgp-diff-added-mark); +} + +.windowCode { + flex: 1; + /* A wider gutter leaves room for the glyph that marks a changed line. */ + --ifm-pre-padding: 1.3rem; +} + +.windowCode :global(.theme-code-block) { + margin: 0; + border-radius: 0; + box-shadow: none; +} + +.windowCode pre { + font-size: 0.8rem; + line-height: 1.5; +} + +/* Decorative glyphs below give an empty alternative text after a plain fallback, so a screen reader + skips them and an older browser still draws them. */ + +/* The changed lines read like a diff: a tint and a gutter mark in each window's own colour, a cross + on the line Rust rejects and a plus on the lines CGP adds. The rejected block shows line numbers, + which Docusaurus lays out as table rows, so its mark sits in the line-number cell; a pseudo-element + on the row itself would become a cell of its own. The tints and marks are theme tokens, which + `scripts/theme/contrast.py` checks against every code colour. The line-number cell is opaque, so it + lays the tint over the code background. */ +.rejected :global(.theme-code-block-highlighted-line) { + background: var(--cgp-diff-removed); +} + +.rejected :global(.theme-code-block-highlighted-line) [class*='codeLineNumber'] { + background: linear-gradient(var(--cgp-diff-removed), var(--cgp-diff-removed)), var(--cgp-code-bg); + box-shadow: inset 3px 0 0 var(--cgp-diff-removed-mark); +} + +.rejected :global(.theme-code-block-highlighted-line) [class*='codeLineNumber']::after { + content: '✗'; + content: '✗' / ''; + position: absolute; + left: 0.45rem; + font-weight: 700; + color: var(--cgp-diff-removed-mark); +} + +.accepted :global(.theme-code-block-highlighted-line) { + position: relative; + background: var(--cgp-diff-added); + box-shadow: inset 3px 0 0 var(--cgp-diff-added-mark); +} + +.accepted :global(.theme-code-block-highlighted-line)::before { + content: '+'; + content: '+' / ''; + position: absolute; + left: 0.45rem; + font-weight: 700; + color: var(--cgp-diff-added-mark); +} + +/* The compiler's error, quoted under the rejected block, reads as terminal output with its first + line in the rejection's colour, a pair the contrast script checks. */ +.diagnostic { + margin: 0; + padding: 0.9rem 1.4rem 1rem; + border-top: 1px dashed var(--cgp-border); + border-radius: 0; + background: var(--cgp-surface); + color: var(--cgp-text-muted); + font-size: 0.76rem; + line-height: 1.45; + white-space: pre; overflow-x: auto; } -.codeExample pre { +.diagnostic::first-line { + color: var(--ifm-color-danger); + font-weight: 700; +} + +/* The caption: its reason at body size, then its conclusion set large in the heading colour, under a + short rule in the link colour. The rule sits closer to the quote than to the reason, so it reads as + the quote's mark rather than an underline of the reason. */ +.caption { + /* Wide enough for the pull quote to stay on one line at desktop widths. */ + max-width: calc(1040px + 2 * var(--page-gutter)); + margin-top: 1.75rem; + text-align: center; +} + +.captionReason { + font-size: 1.05rem; + color: var(--cgp-text-muted); + margin: 0 0 var(--space-group); +} + +.captionQuote { + font-family: var(--ifm-heading-font-family); + font-size: 2rem; + font-weight: var(--ifm-heading-font-weight); + line-height: 1.2; + letter-spacing: -0.01em; + color: var(--cgp-heading); + margin: 0; + text-wrap: balance; +} + +/* Code in the pull quote sets a little smaller than the heading type, so its box does not outweigh + the words around it. */ +.captionQuote code { + font-size: 0.85em; +} + +.captionQuote::before { + content: ''; + display: block; + width: 3rem; + height: 3px; + margin: 0 auto var(--space-tight); + border-radius: 2px; + background: var(--cgp-link); +} + +/* The essay. Each section takes the layout that fits its content, and the sections alternate between + the page and the tint, so every one meets a change of background. */ +.section { + padding: var(--space-section) 0; +} + +.sectionTinted { + background: var(--cgp-surface); + border-top: 1px solid var(--cgp-border); + border-bottom: 1px solid var(--cgp-border); +} + +.sectionTitle { + font-size: 2rem; + line-height: 1.15; + margin: 0 0 1.25rem; + /* A title that wraps, as section 1's does in its narrow column and every title does on a phone, + splits into lines of even length rather than leaving one word on the last line. */ + text-wrap: balance; +} + +.prose { + font-size: 1.05rem; + max-width: 44em; +} + +.prose p:last-child { + margin-bottom: 0; +} + +.lead { + font-size: 1.15rem; + color: var(--cgp-text-muted); + margin: -0.5rem 0 var(--space-block); +} + +/* Prose links on the page are underlined, as in Markdown content. */ +.prose a, +.lead a, +.sectionNote a, +.routeReason a { + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 0.18em; + text-decoration-color: color-mix(in srgb, currentColor 45%, transparent); +} + +/* Section 1: the title in its own column beside the prose. The prose runs several paragraphs, so on + a wide screen the title stays in view below the navbar while the reader scrolls through them. */ +.split { + display: grid; + grid-template-columns: minmax(0, 4fr) minmax(0, 8fr); + gap: 2.5rem; + align-items: start; +} + +.split > .sectionTitle { + position: sticky; + top: calc(var(--ifm-navbar-height) + 1.5rem); +} + +/* Section 2: the four features, whose cards live in src/components/HomepageFeatures/. */ +.sectionNote { + margin: var(--space-block) 0 0; + font-size: 1.05rem; +} + +.tileGrid, +.routeGrid { + list-style: none; margin: 0; padding: 0; - background: transparent; - font-size: 0.9rem; - line-height: 1.5; + display: grid; + gap: 1.25rem; +} + +/* Section 3: three link tiles. */ +.tileGrid { + grid-template-columns: repeat(3, minmax(0, 1fr)); } -.problemCard { - padding: 1.5rem; - border-radius: 8px; +.tile { + display: flex; + flex-direction: column; + gap: 0.4rem; height: 100%; - background-color: var(--ifm-card-background-color); - border: 1px solid var(--ifm-color-emphasis-300); + padding: 1.3rem 1.4rem; + border: 1px solid var(--cgp-border); + border-radius: 14px; + background: var(--cgp-surface-raised); + color: var(--cgp-text); + text-decoration: none; + transition: border-color 0.15s, transform 0.15s; +} + +.tile:hover { + color: var(--cgp-text); + text-decoration: none; + border-color: var(--cgp-link); + transform: translateY(-2px); +} + +.tileTitle { + font-family: var(--ifm-heading-font-family); + font-size: 1.15rem; + font-weight: var(--ifm-heading-font-weight); + color: var(--cgp-heading); +} + +.tile:hover .tileTitle, +.tile:focus-visible .tileTitle { + color: var(--cgp-link); +} + +.tileTitle::after { + content: ' →'; + content: ' →' / ''; +} + +.tileBody { + color: var(--cgp-text-muted); +} + +/* Section 4: the costs in a framed panel, ending on the advice. */ +.costPanel { + padding: 2rem 2.25rem; + border: 1px solid var(--cgp-border); + border-left: 4px solid var(--ifm-color-warning); + border-radius: 14px; + background: var(--cgp-surface); +} + +.costSplit { + display: grid; + grid-template-columns: minmax(0, 4fr) minmax(0, 8fr); + gap: 2.5rem; + align-items: start; +} + +.costSplit .prose { + max-width: none; +} + +/* The heading and its lead stay in view beside the costs while the reader scrolls through them, as + section 1's title does. */ +.costIntro { + position: sticky; + top: calc(var(--ifm-navbar-height) + 1.5rem); +} + +.costLead { + font-size: 1.05rem; + margin: 0; +} + +/* The costs read as a table: each row sets its label in a column of its own beside one statement, + with a rule between rows, so a reader scans the labels down the left edge. */ +.costTable { + margin: 0; + border-top: 1px solid var(--cgp-border); +} + +.costRow { + display: grid; + grid-template-columns: minmax(0, 11rem) minmax(0, 1fr); + gap: var(--space-block); + padding: 0.85rem 0; + border-bottom: 1px solid var(--cgp-border); +} + +.costRow dt { + font-family: var(--ifm-heading-font-family); + font-weight: var(--ifm-heading-font-weight); + color: var(--cgp-heading); + margin: 0; +} + +.costRow dd { + margin: 0; +} + +/* A command or crate name such as `cargo-cgp` would otherwise break at its hyphen. */ +.costTable code { + white-space: nowrap; +} + +.costAdvice { + margin: var(--space-block) 0 0; + font-weight: 600; } -.problemCard h3 { - margin-bottom: 1rem; - font-size: 1.2rem; +/* Section 5: one card per reader, ending the page on a choice. Each card's main link stretches over + the whole card through a positioned pseudo-element, so the card is one target, and a second link in + its reason sits above that layer. The main link's focus ring outlines the whole card. */ +.routeGrid { + grid-template-columns: repeat(5, minmax(0, 1fr)); } -.buttons { +.route { + position: relative; display: flex; - align-items: center; - justify-content: center; - flex-wrap: wrap; - gap: 0.5rem; + flex-direction: column; + gap: 0.4rem; + padding: 1.2rem 1.25rem; + border: 1px solid var(--cgp-border); + border-radius: 14px; + background: var(--cgp-surface-raised); + transition: border-color 0.15s, transform 0.15s; +} + +.route:hover { + border-color: var(--cgp-link); + transform: translateY(-2px); } -.getStartedButton { - --ifm-button-background-color: var(--ifm-color-primary-dark); - --ifm-button-border-color: var(--ifm-color-primary-darkest); +.routeLink { + font-weight: 600; + text-decoration: none; +} - color: white; +.routeLink::after { + content: ''; + position: absolute; + inset: 0; + border-radius: 14px; } -.tutorialButton { - --ifm-button-background-color: var(--ifm-color-primary-lighter); - --ifm-button-border-color: var(--ifm-color-primary-lighter); +.routeLink:focus-visible { + outline: none; } -/* Responsive adjustments */ -@media screen and (max-width: 996px) { - .heroInner { - padding: 0.5rem 1rem; +.routeLink:focus-visible::after { + outline: 2px solid var(--cgp-focus); + outline-offset: 2px; +} + +.routeLink::before { + content: '→ '; + content: '→ ' / ''; +} + +.routeReason { + font-size: 0.92rem; + color: var(--cgp-text-muted); +} + +.routeReason a { + position: relative; + z-index: 1; +} + +.routeReader { + font-family: var(--ifm-heading-font-family); + font-size: 1.1rem; + font-weight: var(--ifm-heading-font-weight); + color: var(--ifm-heading-color); +} + +@media (prefers-reduced-motion: reduce) { + .tile, + .route { + transition: none; + } + + .tile:hover, + .route:hover { + transform: none; + } +} + +/* Two code windows side by side need about 1240 px for their 70-character lines at a readable size. + Below 1360 px the code sets a little smaller, and below 1240 px the windows stack, so neither + scrolls sideways. */ +@media screen and (max-width: 1360px) { + .windowCode pre { + font-size: 0.76rem; + } +} + +@media screen and (max-width: 1239px) { + .codeColumns { + grid-template-columns: minmax(0, 1fr); } - .heroProjectTagline { - font-size: 2rem; + .windowCode pre { + font-size: 0.82rem; } - .heroOuter { - display: block; + /* Between the phone layout and 1240 px the hero copy has less room beside the art, so the art and + the title shrink, and the first code window still starts high on the screen. */ + .heroGrid { + grid-template-columns: minmax(0, 1fr) auto; } - .heroLogo { + .heroArt { width: 200px; - margin: 0 auto; } - .section { - padding: 2rem 1rem; + html[data-theme='dark'] .heroArtFrame { + width: 196px; + height: 196px; + } + + html[data-theme='dark'] .heroArt { + width: 170px; + } + + .heroTitle { + font-size: 2.6rem; + } +} + +@media screen and (max-width: 1100px) { + .routeGrid { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} + +@media screen and (max-width: 996px) { + .page { + --page-gutter: 1rem; + --space-section: 2.75rem; + } + + .heroGrid { + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + padding-top: 1.25rem; + } + + .heroArtFrame { + order: -1; + justify-self: center; + } + + .heroArt { + width: 150px; + } + + html[data-theme='dark'] .heroArtFrame { + width: 160px; + height: 160px; + } + + html[data-theme='dark'] .heroArt { + width: 134px; + } + + .heroTitle { + font-size: 2.2rem; + } + + .heroTagline { + font-size: 1.2rem; + } + + .codeColumns, + .split, + .costSplit, + .tileGrid { + grid-template-columns: minmax(0, 1fr); + } + + .split { + gap: 0; + } + + .split > .sectionTitle, + .costIntro { + position: static; + } + + .costSplit { + gap: 1rem; + } + + .captionQuote { + font-size: 1.5rem; } - .indexCtas { - flex-direction: column; + .sectionTitle { + font-size: 1.6rem; } - .indexCtasGitHubButtonWrapper { - width: 100%; - justify-content: center; + .costPanel { + padding: 1.5rem 1.25rem; + } + + /* On a phone the label sits above its statement. */ + .costRow { + grid-template-columns: minmax(0, 1fr); + gap: 0.2rem; + } + + .routeGrid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media screen and (max-width: 480px) { + .routeGrid { + grid-template-columns: minmax(0, 1fr); } } diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 36e0245c..573521e1 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -1,187 +1,530 @@ -import type {ReactNode} from 'react'; +import {useState, 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'; import Heading from '@theme/Heading'; import CodeBlock from '@theme/CodeBlock'; +import FeatureCards from '@site/src/components/HomepageFeatures'; import styles from './index.module.css'; -function HeroBanner() { +// The front page is written as its own markup and stylesheet on the site theme's tokens, inside the +// Docusaurus layout. Its copy, code, and art follow the knowledge base's homepage guide. + +// The page's code. `example-code/tests/front_page.rs` compiles each block and compares the text +// between each pair of `front-page:` markers with the same markers in its own sources, so a change +// here needs the same change there. The knowledge base's homepage guide specifies the blocks. + +// front-page:rejected-block:begin +const REJECTED_BLOCK = `// Rust allows only one of these. \`String\` is both \`Display\` and +// \`AsRef<[u8]>\`, so the compiler has no principled way to choose. +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +impl CanEncode for T { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +impl> CanEncode for T { // error[E0119] + fn encode(&self) -> Vec { self.as_ref().to_vec() } +}`; +// front-page:rejected-block:end + +// The compiler's error for the rejected block, from its compile-fail snapshot, without the location +// line, which names the fixture's path. The block starts at the fixture's first line, so the line +// numbers here are the ones the page shows beside the block. +// front-page:rejected-diagnostic:begin +const REJECTED_DIAGNOSTIC = `error[E0119]: conflicting implementations of trait \`CanEncode\` + | + 7 | impl CanEncode for T { + | -------------------------------- first implementation here +... +11 | impl> CanEncode for T { // error[E0119] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation`; +// front-page:rejected-diagnostic:end + +// front-page:cgp-block:begin +const CGP_BLOCK = `#[cgp_component(Encoder)] // generates the provider trait Encoder +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +#[cgp_impl(new EncodeAsText)] // a provider: one named implementation +#[uses(Display)] +impl Encoder { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +#[cgp_impl(new EncodeAsBytes)] +#[uses(AsRef<[u8]>)] +impl Encoder { + fn encode(&self) -> Vec { self.as_ref().to_vec() } +} + +// Each type names the implementation it uses: +delegate_components! { u64 { EncoderComponent: EncodeAsText } } +delegate_components! { String { EncoderComponent: EncodeAsText } } +delegate_components! { Vec { EncoderComponent: EncodeAsBytes } }`; +// front-page:cgp-block:end + +const INSTALL_COMMAND = 'cargo add cgp'; + +// The install line copies its command, so a reader can paste it without selecting the text. A +// browser without the clipboard API, or one that refuses it, leaves the button unchanged, and the +// command stays selectable by hand. +function InstallLine(): ReactNode { + const [copied, setCopied] = useState(false); + const copy = () => { + navigator.clipboard + ?.writeText(INSTALL_COMMAND) + .then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 1500); + }) + .catch(() => {}); + }; return ( -
    -
    - Context-Generic Programming -
    - - - Build modular Rust applications with zero-cost abstractions - +
    + + {' '} + {INSTALL_COMMAND} + + +
    + ); +} + +function Hero(): ReactNode { + return ( +
    +
    +
    + + Context-Generic Programming -
    - - Get Started +

    + A language extension for Rust, with pluggable trait implementations at compile-time. +

    +

    + Still ordinary Rust: a library on the stable toolchain, with provider selection resolved + at compile time, adopted one trait at a time. +

    + +
    + + Quickstart - - Tutorial - 5 min ⏱️ + + Costs and maturity - -

    ` for the payload type `P` of every variant, which is `Nil` for a variant with +no fields. + +## 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 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. + +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. +- [`SerializeUnit`](./serialize_unit.md) writes the `Nil` payload of a variant with no fields. + +## 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/serialize_with_display.md b/docs/projects/cgp-serde/reference/providers/serialize_with_display.md new file mode 100644 index 00000000..a774a445 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_with_display.md @@ -0,0 +1,83 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..8fe63164 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md @@ -0,0 +1,83 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..20095b48 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/try_serialize_from.md @@ -0,0 +1,92 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..4d6c83c5 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/use_serde.md @@ -0,0 +1,103 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `UseSerde` is how a 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 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 +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..257815fa --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/can_deserialize_json_string.md @@ -0,0 +1,92 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..77b42330 --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/deserialize_with_context.md @@ -0,0 +1,95 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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..21019cbe --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/serialize_with_context.md @@ -0,0 +1,95 @@ +--- +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 + +In [cgp-serde](../../index.md), a serialization library built with +[Context-Generic Programming (CGP)](/docs/), `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 + [`SerializeRecordFields`](../providers/serialize_record_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..d634b728 --- /dev/null +++ b/docs/projects/cgp-serde/serde-comparison.md @@ -0,0 +1,124 @@ +--- +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 +[Context-Generic Programming (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 `SerializeRecordFields` and `DeserializeRecordFields` | +| `#[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 | + +## 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. +- **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 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. +- **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/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..a6e5e4b6 --- /dev/null +++ b/docs/projects/hypershell/architecture/abstract-syntax.md @@ -0,0 +1,114 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that lets a program's parts take their +meaning from elsewhere. 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..b5d75872 --- /dev/null +++ b/docs/projects/hypershell/architecture/assembly.md @@ -0,0 +1,168 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library whose implementations are selected by +a context's wiring. 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/tooling/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..a9b8b49c --- /dev/null +++ b/docs/projects/hypershell/architecture/crate-layout.md @@ -0,0 +1,77 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), a Rust library +that separates implementations from the code that chooses them. 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, the handler traits and their keys among them. 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, while a small program, such as +[`hello`](../examples/hello.md), builds on stable Rust in a crate of its own. + +## 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 that large, 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..a5c3a86e --- /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 [Context-Generic Programming](/docs/) (CGP), a Rust library whose wiring decides which +implementation a program runs. 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..3ec16c11 --- /dev/null +++ b/docs/projects/hypershell/architecture/streams-and-input-dispatch.md @@ -0,0 +1,165 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that chooses an implementation from +the types involved. 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..a9dd0ca6 --- /dev/null +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -0,0 +1,193 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that keeps a context's choices in its +own wiring. 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. + +::: + +## 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): + +```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. The program then fails at its `handle` call, +and [`cargo cgp check`](/docs/tooling/cargo-cgp/check) reports the missing route, shown here with the long +type abridged: + +```text +error[E0277]: [CGP-E001] missing wiring for `@cgp.core.error.ErrorRaiserComponent.tokio_tungstenite::tungstenite::Error` on `MyApp` + = note: root cause: [CGP-E113] missing wiring for `@cgp.core.error.ErrorRaiserComponent.tokio_tungstenite::tungstenite::Error` on `MyApp` +``` + +The path's last segment is the error type the provider raises, written by its full path: +`tokio_tungstenite::tungstenite::Error`, the type the program imports as `TungsteniteError`. So the +message names `tungstenite`'s error rather than the context's own, and adding the route back fixes +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 + +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. +- [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. + +--- + +*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..046ef20c --- /dev/null +++ b/docs/projects/hypershell/examples/bluesky.md @@ -0,0 +1,124 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that resolves every stage's +implementation at compile time. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..9f221045 --- /dev/null +++ b/docs/projects/hypershell/examples/github-issues.md @@ -0,0 +1,158 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), a Rust +library that resolves a program's nested parts through its context. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..55139965 --- /dev/null +++ b/docs/projects/hypershell/examples/hello-name.md @@ -0,0 +1,188 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library whose wiring supplies the values a +program's parts need. This page shows where such runtime values live, 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. + +::: + +## 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): + +```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/tooling/cargo-cgp/check) reports the failure with its root cause, shown here with +the long types abridged: + +```text +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 +`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 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. +- [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. + +--- + +*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..6b2f898a --- /dev/null +++ b/docs/projects/hypershell/examples/hello.md @@ -0,0 +1,184 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that gives a program's parts their +meaning 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. + +::: + +## 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): + +```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. 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. +- [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. + +--- + +*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..eefa2f94 --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-cli.md @@ -0,0 +1,170 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that resolves each stage's +implementation when the program compiles. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..22f4b5b1 --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-client.md @@ -0,0 +1,191 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that picks an implementation by the +types a stage receives. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..69bfb720 --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -0,0 +1,205 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that lets a language be extended +without editing its crates. 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. + +::: + +## 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): + +```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 +}; +``` + +The program then fails at its `handle` call, and [`cargo cgp check`](/docs/tooling/cargo-cgp/check) names +the missing entry, shown here with the long types abridged: + +```text +error[E0277]: [CGP-E001] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `hypershell_tokio_components::providers::async_read::HandleToTokioAsyncRead` + = note: root cause: [CGP-E114] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `hypershell_tokio_components::providers::async_read::HandleToTokioAsyncRead` +``` + +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 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. +- [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. + +--- + +*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..dabbbab3 --- /dev/null +++ b/docs/projects/hypershell/examples/index.md @@ -0,0 +1,79 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that lets each application choose an +implementation. 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..34c3737e --- /dev/null +++ b/docs/projects/hypershell/examples/nix-manual.md @@ -0,0 +1,144 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library whose wiring decides what each piece +of a program means. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..79391ad1 --- /dev/null +++ b/docs/projects/hypershell/examples/rust-playground.md @@ -0,0 +1,158 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that fixes a program's interface +through its wiring. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..86a81ac1 --- /dev/null +++ b/docs/projects/hypershell/examples/save-webpage.md @@ -0,0 +1,124 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), a +Rust library that derives a program's behavior from its wiring. 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. + +::: + +## 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): + +```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. +- [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. + +--- + +*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..a4af824c --- /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, a shell-scripting language built with Context-Generic Programming (CGP)." + } +} diff --git a/docs/projects/hypershell/guides/debugging.md b/docs/projects/hypershell/guides/debugging.md new file mode 100644 index 00000000..3d83f0b9 --- /dev/null +++ b/docs/projects/hypershell/guides/debugging.md @@ -0,0 +1,285 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), a Rust library whose wiring selects +the implementation behind each trait. This guide shows the common mistakes, each with the code +that triggers it, the root cause [`cargo cgp check`](/docs/tooling/cargo-cgp/check) reports, and the fix. +Each output below comes from compiling the program against `cargo-cgp` built from its current +source, sometimes through a `check_components!` and sometimes at the `handle` call, and is trimmed +to its headline and root cause. Long type paths are abridged with an ellipsis, and the dependency +chain the tool prints below the root cause is left out. `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 + +**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 on the [error codes](/docs/tooling/cargo-cgp/error-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-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 +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 +error[E0277]: [CGP-E001] the trait bound `…::TokioAsyncReadStream<…::ChildOutputStream>: AsRef<[u8]>` is not satisfied + = note: root cause: [CGP-E117] the trait bound `…::TokioAsyncReadStream<…::ChildOutputStream>: 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 +error[E0277]: [CGP-E001] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `hypershell_tokio_components::providers::async_read::HandleToTokioAsyncRead` + = note: root cause: [CGP-E114] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `hypershell_tokio_components::providers::async_read::HandleToTokioAsyncRead` +``` + +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] missing wiring for `PathCons<…>` on `HypershellCli` + = note: root cause: [CGP-E113] missing wiring for `PathCons<…>` on `HypershellCli` +``` + +The message names the route as the type-level path the lookup follows, `PathCons<…>`, with the +`Checksum` segment inside it. `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] 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` +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-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 +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! { + MyApp { + namespace HypershellNamespace; + @cgp.extra.handler.HandlerComponent. SimpleExec: FakeSimpleExec, + } +} +``` + +```text +error[E0119]: [CGP-E011] conflicting wiring: `MyApp` 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. +**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/tooling/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..67fea63e --- /dev/null +++ b/docs/projects/hypershell/guides/writing-a-program.md @@ -0,0 +1,163 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), a Rust library that lets an application choose an +implementation. 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/tooling/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 does not yet reshape every class. + +## Build large programs with nightly and the new trait solver + +A small program builds on stable Rust in a crate of its own. 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..327342b8 --- /dev/null +++ b/docs/projects/hypershell/index.md @@ -0,0 +1,189 @@ +--- +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 +[Context-Generic Programming](/docs/) (CGP), 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 its +largest programs need 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 for large programs.** The library and small programs, such as the one above, build + on stable Rust. The largest examples, which nest whole programs inside others, exhausted memory + while type-checking on stable Rust, growing `rustc` to about 7 GB; on nightly with the + next-generation trait solver, `-Z next-solver=globally`, a check of one of them took about 9 + seconds and 460 MB. The repository pins nightly and turns the solver on. 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/tooling/cargo-cgp/check) helps: `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 + 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, add it from crates.io with `cgp` and an async runtime. The +`hypershell!` macro's expansion names the `cgp` crate, so your crate depends on it as well: + +```toml +[dependencies] +cgp = "0.8.0" +hypershell = "0.2.0" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +``` + +A small program builds on stable Rust. A crate whose programs nest others, as the largest examples +do, can copy the repository's `rust-toolchain.toml` and `.cargo/config.toml` to build with the same +nightly and solver. + +## 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 in Rust](/blog/hypershell-release): the post that + announced the project, with its history and motivation. Its code predates the current design. +- [Hypershell's release notes](/docs/release-notes/hypershell): what each official release changed, and the + steps to upgrade from the one before. + +--- + +*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..12a69a11 --- /dev/null +++ b/docs/projects/hypershell/limitations.md @@ -0,0 +1,88 @@ +--- +sidebar_label: 'Limitations' +sidebar_position: 10 +description: 'The limits of Hypershell: a proof of concept, programs fixed at compile time, a nightly toolchain for large programs, and when a shell or plain Rust fits better.' +--- + +# Limitations + +Hypershell is a proof of concept, and its design has limits that are worth knowing before reading +further. [Hypershell](./index.md) is a small shell-scripting language built with +[Context-Generic Programming](/docs/) (CGP), a Rust library that selects an implementation through +a context's wiring. 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. + +## Large programs need 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, while +small programs build on stable Rust. 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/tooling/cargo-cgp/check) gets to the cause faster: +`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 + +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..9d5d88ab --- /dev/null +++ b/docs/projects/index.md @@ -0,0 +1,78 @@ +--- +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 [Context-Generic Programming](/docs/) (CGP), 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 whose largest programs + need 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. +- **[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 + +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), [`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) | +| 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) | +| 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 + 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. + +--- + +*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/quickstart.md b/docs/quickstart.md new file mode 100644 index 00000000..5d8f1515 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,87 @@ +--- +title: 'Quickstart: install and run a first program' +sidebar_label: 'Quickstart' +sidebar_position: 2 +description: 'Install Context-Generic Programming and run your first Rust program with it in a few minutes.' +--- + +# Quickstart + +[Context-Generic Programming](/docs/) (CGP) enables pluggable trait implementations in Rust. To +try it, you will create a Rust project and run a small program that prints a greeting. You can +follow the steps without learning the concepts first, because the +[Hello World tutorial](/docs/tutorials/hello) explains them afterward. + +You need Rust 1.89 or newer on the stable toolchain. Check your version with `rustc --version` +before you start. On an older toolchain, `cargo add` picks an older release of `cgp` that lacks the +features this program uses, so the build fails. Run `rustup update stable` if you need to update. + +## Install + +Create a project, open its directory, and add CGP: + +```bash +cargo new hello-cgp +cd hello-cgp +cargo add cgp +``` + +`cargo add` writes the dependency into your `Cargo.toml`: + +```toml title="Cargo.toml" +[dependencies] +cgp = "0.8.0" +``` + +## The program + +With CGP installed, replace the contents of `src/main.rs` with this greeting program: + +```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 + +Run the program with Cargo: + +```bash +cargo run +``` + +It should print: + +```text +Hello, World! +``` + +If you see that greeting, CGP is working in your project. + +## Next + +The [Hello World tutorial](/docs/tutorials/hello) explains a program like this one, then shows how +the same `greet` function runs unchanged on a 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 new file mode 100644 index 00000000..a2975f3e --- /dev/null +++ b/docs/reference/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Reference", + "position": 6, + "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..5dda2e1e --- /dev/null +++ b/docs/reference/attributes/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Attributes", + "position": 2, + "link": { + "type": "doc", + "id": "reference/attributes/index" + } +} diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md new file mode 100644 index 00000000..ed5bb640 --- /dev/null +++ b/docs/reference/attributes/default_impl.md @@ -0,0 +1,376 @@ +--- +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(...)]` + +Register a provider as a namespace's default for a key. + +## Overview + +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: + +```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. + +Registering at the definition keeps the provider and its default together, so a new per-type +implementation is one edit rather than two. + +## 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`: + +```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 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: +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 without any `for` loop: + +```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 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 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 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 + +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() + } +} + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } +} +``` + +Then the context: + +```rust +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @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 +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)). + +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 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, 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](/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 +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 + +The attribute emits a single impl of the named lookup trait, for the key type: + +```rust +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 +[`PathCons`](../types/path_cons.md) list that `cargo cgp expand` prints as `Path!(@app.GreeterComponent)`: + +```rust +impl<__Components__> AppNamespace<__Components__> 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 +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 the compiler checks them when a real context +resolves the provider. + +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 +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 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 -> Key `in` NamespacePath + +Key -> Type | Path + +Path -> `@` PathSegment ( `.` PathSegment )* +PathSegment -> Type + +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 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 + +**`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/namespace/default_impls1.md) suggest otherwise. + +**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` +``` + +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 +`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 +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. 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: + +```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 cannot be overridden from the context.** A direct entry for a type the registry +already covers overlaps the loop's impl and is rejected with `E0119`, naming the path both impls cover. +Wire directly only the types the registry leaves out. + +**On the `#[cgp_impl(Self)]` form the macro emits the registration with `Delegate = Self`.** That form +does not build a provider, so the macro fills the delegate with `Self`, which inside the registration +impl is the key itself. The attribute has no sensible use there, so leave it off. + +## Related constructs + +- [`DefaultImpls1`](../traits/namespace/default_impls1.md) — the usual target, and where the positional rule is + 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 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. +- [`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. + +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) + +--- + +*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 new file mode 100644 index 00000000..dd777048 --- /dev/null +++ b/docs/reference/attributes/derive_delegate.md @@ -0,0 +1,333 @@ +--- +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]` + +Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `open` statement. + +:::info + +### 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 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. + +**Prefer `open` for anything new.** This page exists because you will meet the older form, including +in the library'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. The project expects to +deprecate the attribute once `open` is shown to cover every dispatch case. + +::: + +## Overview + +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 +type, and forwards every method to it. That code is mechanical and identical in shape for every +component, differing only in which parameter is the key. The attribute writes it for you: + +```rust +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} +``` + +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 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 +[`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 + +`#[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 the macro uses only the parameter in that wrapper's brackets 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, 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. + +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`, which a check confirms for both shapes: + +```rust +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } +} +``` + +`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 +let the context open it: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +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 neither an attribute nor a table +type. + +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. +- **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. + +## Under the hood + +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 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. + +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. 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 +[`#[use_type]`](use_type.md) yields a dispatcher whose `where` clause also requires +`__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 impls are independent, so a context may +dispatch on either or nest one table inside the other. + +## 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 (the parser rejects an empty `()` with *expect +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 + +**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. 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 +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: + +```text +error[E0119]: conflicting implementations of trait `DelegateComponent` + for type `App` + | + | open AreaCalculatorComponent; + | ----------------------- first implementation here + | + | AreaCalculatorComponent: + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` +``` + +Pick one per component. The related restriction is that `open` does not combine with a joined namespace +where the component carries a [`#[prefix(...)]`](./prefix.md): 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 + 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. +- [`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: + +- [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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..d9cd27b5 --- /dev/null +++ b/docs/reference/attributes/extend.md @@ -0,0 +1,304 @@ +--- +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]` + +Add a trait as a [supertrait](/docs/reference/glossary#supertrait) of a generated trait, so callers can rely on it too. + +## Overview + +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. + +```rust +#[extend(HasName)] +``` + +**`#[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 +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 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]` +macro treats a `where` clause you write as an implementation detail and never puts it on the generated +trait, so you cannot write a supertrait by hand. `#[extend]` is the only way to add one. + +## Usage + +`#[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. 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), 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. + +### 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), 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)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +`#[extend]` is therefore for a **method** supertrait, one whose methods matter and whose associated +types the signatures do not name. + +## Examples + +A `#[cgp_fn]` trait 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`. That 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 consumer +trait's contract: + +```rust +#[cgp_component(Greeter)] +#[extend(HasName)] +pub trait CanGreet { + fn greet(&self); +} +``` + +`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 + +**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 + 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 + 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 cost decides whether to promote a requirement. +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. + +## Under the hood + +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] +#[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 { /* ... */ } +} +``` + +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. 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 +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) + } +} +``` + +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. + +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 + +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. 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 + +**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 +``` + +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. + +**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]`. + +## 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 traits 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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..c75fae98 --- /dev/null +++ b/docs/reference/attributes/extend_where.md @@ -0,0 +1,261 @@ +--- +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]` + +Add `where` predicates to a generated trait's own definition, not only to its implementation. + +## Overview + +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. + +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 +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: + +```rust +#[extend_where(Scalar: Clone)] +``` + +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](/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. + +## Usage + +`#[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. 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]`**, 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 + +A generic trait 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 +} +``` + +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 +trait for a type it cannot satisfy, at the place the bound is written, and names the trait that +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() +} +``` + +**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: + +```rust +pub fn scale_it(ctx: &Ctx) -> Scalar +where + Ctx: Scale, + Scalar: Clone, +{ + ctx.scale() +} +``` + +## When to use it + +**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 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. + +- **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 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 trait on the context. +- **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 +should imply something, use a supertrait, which requires the bound to be on `Self`. + +## Under the hood + +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 +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 all of them, and their **order is fixed**: the function's own `where` clause +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. + +## 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, 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. + +## 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 +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. 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 + | + | Ctx: Scale, + | ^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Scalar` + | +note: required by a bound in `Scale` +``` + +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 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_component(Scaler)] +#[extend_where(Scalar: Clone)] +pub trait CanScale { + fn scale(&self) -> Scalar; +} +``` + +```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 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. + +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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..a34ebcac --- /dev/null +++ b/docs/reference/attributes/impl_generics.md @@ -0,0 +1,332 @@ +--- +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(...)]` + +Declare a generic parameter on the generated implementation alone, so a context supplies the type +through a field and callers never name it. + +## Overview + +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 +**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 +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: + +```rust +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn greet(&self, #[implicit] name: &Name) -> 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. The context does not need +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](/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 + +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. 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`. 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. 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 +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 + +A trait 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](/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](/docs/reference/glossary#value-context): the greeting reads the data each type +holds. + +A trait 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". 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 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 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 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 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. + +## 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 +[`#[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. + +## 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: + +```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 +``` + +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 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 +#[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. 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. + +**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 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: + +```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 + +error[E0425]: cannot find type `Name` in this scope +``` + +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 + +- [`#[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 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. + +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) + +--- + +*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 new file mode 100644 index 00000000..a1b55c34 --- /dev/null +++ b/docs/reference/attributes/implicit.md @@ -0,0 +1,368 @@ +--- +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]` + +Source a function argument from a same-named field on the context. + +## Overview + +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 +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +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 +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 +context-generic function and +learn the machinery later, when they need it. + +## Usage + +`#[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 { + width * height +} +``` + +`#[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. 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` +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 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 | +|---|---|---| +| An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | +| `&T` | `T` | by reference, no conversion | +| `&str` | any `'static` value implementing `AsRef` | `.as_ref()` | +| `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | +| `Option<&T>` | `Option` | `.as_ref()` | +| `Option<&str>` | any `'static` `Option` whose `U` implements `AsRef` | `.option_as_ref()` | +| `&mut T` | `T` | mutably, no conversion | +| `&mut str` | a field implementing `AsMut` | `.as_mut()` | +| `&mut [T]` | anything `AsMut<[T]>` | `.as_mut()` | +| `Option<&mut T>` | `Option` | `.as_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 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. + +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 the macro clones it. This is the one place where a small change to the type changes the read without +a warning. + +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`, 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 +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. 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 +a mutable field borrow rather than a mutable local copy. + +## Examples + +A complete trait, 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), and that derive is all it needs to +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 +`&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. This fragment assumes a `StorageObjectFetcher` component +whose `fetch_storage_object(&self, object_id: &str) -> anyhow::Result>` method is defined +elsewhere. The macro removes the implicit arguments from the signature and keeps `object_id`: + +```rust +#[cgp_impl(new FetchS3Object)] +impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] storage_client: &aws_sdk_s3::Client, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> anyhow::Result> { + // fetch `object_id` from `bucket_id` through `storage_client` + } +} +``` + +Callers still write `app.fetch_storage_object(object_id)`. The provider needs two fields from its +context, `storage_client` and `bucket_id`, the second borrowed here as a `&str` from a `String`, +and neither requirement 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 + +**Reach for `#[implicit]` by default whenever a provider needs a value from its own context.** It is the +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. + +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. + +- **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 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](/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. + +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) is the advanced form. Use it only when the +*field a getter reads* should be chosen per context at wiring time. + +## Under the hood + +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] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +the macro strips the arguments from the trait's method and turns them into +[`HasField`](../traits/field-access/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 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](/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. + +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`. + +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, 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 + +**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.** 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 + want a mutable local copy of the value) +``` + +**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 `&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` + +error: a `&mut` implicit argument must be the only implicit argument, since its mutable + 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. +- [`#[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 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. + +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) +- 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) + +--- + +*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/index.md b/docs/reference/attributes/index.md new file mode 100644 index 00000000..9c44fa33 --- /dev/null +++ b/docs/reference/attributes/index.md @@ -0,0 +1,77 @@ +--- +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 + +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 +`#[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 +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, 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 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 +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](/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. `#[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 + +[`#[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, 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. 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 + +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 +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 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 new file mode 100644 index 00000000..454cd227 --- /dev/null +++ b/docs/reference/attributes/prefix.md @@ -0,0 +1,424 @@ +--- +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(...)]` + +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 + +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 +where to look next. + +```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`.* 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 +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](/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](/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 +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](/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. + +### Choosing a prefix + +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](/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. + +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](/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 +repeating anything from the first: + +```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 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** 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. +- **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 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 + +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 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 +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. + +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 + +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 macro appends the marker, so do not write it.** `#[prefix(@app.GreeterComponent in Ns)]` +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 +[`check_components!`](../macros/check_components.md) reports it, as an unsatisfied bound on the +*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 + | + | 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: + +```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` +``` + +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 +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 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 +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 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 +``` + +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) + +--- + +*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 new file mode 100644 index 00000000..527966be --- /dev/null +++ b/docs/reference/attributes/use_provider.md @@ -0,0 +1,334 @@ +--- +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]` + +Depend on another provider by name, importing the provider trait it must satisfy. + +## Overview + +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. + +```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). `#[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 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 +associated function and passes the context: + +```rust +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](/docs/reference/glossary#higher-order-provider) wants. + +## Usage + +`#[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 it must satisfy. The trait may carry further arguments of its own, +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. + +**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 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. 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 + +The typical 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. `Rectangle` is a [value context](/docs/reference/glossary#value-context), the shape being measured, and it carries +the fields both layers read: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: ScaledArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +Because the wrapper never names a particular inner implementation, the same `ScaledArea` composes over any +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 +[`#[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] +#[use_provider(RectangleArea: AreaCalculator)] +pub fn rect_area(&self) -> f64 { + RectangleArea::area(self) +} +``` + +## 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 +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 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 + 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. 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. + +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 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 +original `Self` moves into an explicit leading type parameter for the context, so the real bound on an +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)] +#[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. + +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: + +```rust +impl<__Context__> RectArea for __Context__ +where + RectangleArea: AreaCalculator, +{ + fn rect_area(&self) -> f64 { + RectangleArea::area(self) + } +} +``` + +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 + +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? +``` + +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: `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 +[Common Mistakes](#common-mistakes). + +## 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: + +```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 +from those attributes leads to this error. + +**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 `:` + | + | #[use_provider(RectangleArea)] + | ^ +``` + +**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, write 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 localizes a broken layer. + +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) +- 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) + +--- + +*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 new file mode 100644 index 00000000..e367472f --- /dev/null +++ b/docs/reference/attributes/use_type.md @@ -0,0 +1,466 @@ +--- +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]` + +Import an abstract associated type and write it as a bare name. + +## Overview + +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. + +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)] +``` + +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 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](/docs/reference/glossary#abstract-type) together. + +## Usage + +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 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), [`#[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 + +Separate entries with commas, and **prefer one attribute carrying the whole list**, because 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})] +``` + +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 +reason. + +### Pinning a type to a concrete one + +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. 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})] +``` + +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. + +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. + +### 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, 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: + +```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 shared by 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](/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. + +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 +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + ScalarTypeProviderComponent: UseType, + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +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)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +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 use it + +**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 handle the requirements that are not types, and one of them declares the type this +attribute imports. + +- **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. +- **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). 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. + +`#[use_type]` does not import a construct's **own** associated type, so it stays qualified as +`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 does not need +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 + +`#[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: + +```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. 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: + +```rust +pub trait AreaOf +where + Types: HasScalarType, +{ + fn area_of(&self) -> ::Scalar; +} +``` + +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, 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 +the struct: + +```rust +let value = Marker; // stays the unit struct `Marker` +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. A **cycle** is the +only arrangement without a valid order. See [Common Mistakes](#common-mistakes). + +## 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. The pin is accepted on `#[cgp_fn]` and +`#[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 + +**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 +``` + +**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 +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**, 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 +``` + +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 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. +- [`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 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 + [`#[cgp_component]`](../macros/cgp_component.md) — the hosts, together with the macros built on + `#[cgp_component]`. + +The ideas behind it: + +- [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 + +- 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) + +--- + +*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 new file mode 100644 index 00000000..e56ff2e8 --- /dev/null +++ b/docs/reference/attributes/uses.md @@ -0,0 +1,291 @@ +--- +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]` + +Import the traits an implementation depends on, reading like a `use` statement. + +## Overview + +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 +#[uses(RectangleArea)] +``` + +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 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 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) +shows that the two desugar identically. + +## Usage + +`#[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 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 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 +`#[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), 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 + +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, 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](/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](/docs/reference/glossary#supertrait) or [`#[extend_where]`](extend_where.md) for a predicate. + +## Examples + +A trait 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)]` 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 trait: + +```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 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](/docs/reference/glossary#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 + +**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 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. +- **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. + `#[uses]` keeps a requirement private to the implementation, where those two make it public. + +## Under the hood + +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 macro emits the trait 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 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. + +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. That is also where the generated +[`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 + +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. 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 + +**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: + +```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` + | + | #[uses(AreaCalculator)] + | ^^^^^^^^^^^^^^ expected 1 generic argument + | +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 mean a named implementation, and it will supply +the missing argument. + +**`#[uses]` is rejected on a component trait.** It declares the dependencies of a provider, and the macro +says so: + +```rust +#[cgp_component(Shouter)] +#[uses(CanCalculateArea)] +pub trait CanShout { + fn shout(&self) -> String; +} +``` + +```text +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 +[`#[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. +- [`#[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 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 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 trait + 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) +- 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) + +--- + +*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/_category_.json b/docs/reference/components/_category_.json new file mode 100644 index 00000000..ad05d6c1 --- /dev/null +++ b/docs/reference/components/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Components", + "position": 4, + "link": { + "type": "doc", + "id": "reference/components/index" + } +} diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md new file mode 100644 index 00000000..c278d38a --- /dev/null +++ b/docs/reference/components/can_raise_error.md @@ -0,0 +1,180 @@ +--- +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 +--- + +# `CanRaiseError` + +Turn a concrete source error into the context's abstract `Self::Error`. + +## Overview + +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. +`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 +"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 { + #[track_caller] + 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]`](../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`. + +## 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 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 +knows how to handle it: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseError: DebugError, + } +} +``` + +`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 +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. + +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: + +```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](/docs/reference/glossary#environmental-context)**, and the component targets +it rather than a value. + +## 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 +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/) + +--- + +*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 new file mode 100644 index 00000000..68217a75 --- /dev/null +++ b/docs/reference/components/can_wrap_error.md @@ -0,0 +1,211 @@ +--- +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 +--- + +# `CanWrapError` + +Attach a piece of detail to an error the context already holds, enriching it as it propagates. + +## Overview + +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 +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 +[`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 { + #[track_caller] + 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]`](../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`. + +## 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 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): + +```rust +delegate_components! { + App { + open ErrorWrapperComponent; + + @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)] +#[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}")) + } +} + +#[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. `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 + +**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/) + +--- + +*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/_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..074af326 --- /dev/null +++ b/docs/reference/components/handler/async_computer.md @@ -0,0 +1,163 @@ +--- +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. + +## Overview + +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 +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 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 + +`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, 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]`](../../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`, `AsyncComputerComponent`, and the 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 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