From 60234576f88411f0d0791331c1f939d13da4b93d Mon Sep 17 00:00:00 2001 From: Vaiz <4908982+Vaiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:33:05 +0000 Subject: [PATCH 1/4] feat: add Copilot marketplace with rust-guidelines skill Package the public Pragmatic Rust Guidelines as an on-demand skill and document marketplace installation for Copilot clients. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/plugin/marketplace.json | 16 ++++++ README.md | 45 +++++++++++++++ ai-skill/plugin.json | 10 ++++ ai-skill/skills/rust-guidelines/SKILL.md | 73 ++++++++++++++++++++++++ 4 files changed, 144 insertions(+) create mode 100644 .github/plugin/marketplace.json create mode 100644 ai-skill/plugin.json create mode 100644 ai-skill/skills/rust-guidelines/SKILL.md diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json new file mode 100644 index 0000000..2b770e7 --- /dev/null +++ b/.github/plugin/marketplace.json @@ -0,0 +1,16 @@ +{ + "name": "pragmatic-rust-guidelines", + "owner": { + "name": "Vaiz" + }, + "metadata": { + "description": "Pragmatic Rust Guidelines for GitHub Copilot." + }, + "plugins": [ + { + "name": "rust-guidelines", + "description": "Apply the Pragmatic Rust Guidelines when writing or reviewing Rust.", + "source": "./ai-skill" + } + ] +} diff --git a/README.md b/README.md index 1581353..aee43c0 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,51 @@ A collection of pragmatic design guidelines helping developers to produce idioma 👉 [**Pragmatic Rust Guidelines**](https://microsoft.github.io/rust-guidelines) +## Use with GitHub Copilot + +This repository is also a Copilot plugin marketplace with one plugin, +`rust-guidelines`, containing one skill of the same name. The plugin lives in +[`ai-skill`](ai-skill); the discovery catalog is +[`.github/plugin/marketplace.json`](.github/plugin/marketplace.json). +The skill reads the public guidelines on demand, so internet access is required. + +### Copilot CLI + +With a current [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli) +installed and signed in, register this fork's marketplace and install the plugin: + +```shell +copilot plugin marketplace add Vaiz/rust-guidelines +copilot plugin install rust-guidelines@pragmatic-rust-guidelines +``` + +Start a new Copilot session and run `/skills list` to confirm that +`rust-guidelines` is available. Ask Copilot to use the skill, for example: + +```text +Use the rust-guidelines skill to review the Rust code in this project. +``` + +To try a local checkout before publishing, register the repository root as a +local marketplace instead of the GitHub repository: + +```shell +copilot plugin marketplace add . +copilot plugin install rust-guidelines@pragmatic-rust-guidelines +``` + +Run these commands from the repository root. Local marketplace plugins load +directly from the checkout; start a new session after editing the skill. + +### Other Copilot clients + +In a Copilot client that supports plugin marketplaces, add +`https://github.com/Vaiz/rust-guidelines` as a marketplace and install +`rust-guidelines`. See the +[client-specific installation instructions](https://docs.github.com/en/copilot/reference/plugin-and-marketplace-reference#use-plugins). +Marketplace support varies by client; this plugin contains a standard +`skills/rust-guidelines/SKILL.md` skill and does not require MCP servers or hooks. + ## Development The guidelines use [mdbook](https://github.com/rust-lang/mdBook). Once installed you can view them locally via diff --git a/ai-skill/plugin.json b/ai-skill/plugin.json new file mode 100644 index 0000000..aac55fb --- /dev/null +++ b/ai-skill/plugin.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "rust-guidelines", + "version": "0.1.0", + "description": "Apply the Pragmatic Rust Guidelines when writing or reviewing Rust.", + "homepage": "https://microsoft.github.io/rust-guidelines", + "repository": "https://github.com/Vaiz/rust-guidelines", + "license": "MIT", + "keywords": ["rust", "guidelines", "code-review"] +} diff --git a/ai-skill/skills/rust-guidelines/SKILL.md b/ai-skill/skills/rust-guidelines/SKILL.md new file mode 100644 index 0000000..b53068a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/SKILL.md @@ -0,0 +1,73 @@ +--- +name: rust-guidelines +description: Apply the Pragmatic Rust Guidelines when writing, refactoring, or reviewing Rust code, designing Rust APIs, or changing Rust tests, documentation, Cargo workspaces, unsafe code, or FFI. +license: MIT +--- + +# Pragmatic Rust Guidelines + +Use the [Pragmatic Rust Guidelines](https://microsoft.github.io/rust-guidelines/) +as the source of truth. This skill covers both application and library code. + +## Workflow + +1. Read the repository's instructions and the code affected by the task. + Identify the intended behavior, public contracts, and supported Rust version. +2. Read the [applicability and golden rule](https://microsoft.github.io/rust-guidelines/guidelines/). + Distinguish requirements from recommendations and respect their exceptions. +3. Use the topic map below to read the relevant guidelines before changing or + reviewing code. Start with universal guidelines; add topics as needed. + Use the [checklist](https://microsoft.github.io/rust-guidelines/guidelines/checklist/) + for broader reviews, not as a substitute for reading a guideline's rationale. +4. Apply the relevant guidance to each changed type, signature, implementation, + and test. Preserve existing behavior unless the task calls for changing it. +5. Run the repository's appropriate formatting, lint, and targeted test commands. + Report concrete findings and any validation that could not be completed. + +## Topic map + +All links point to the public book. Read only the topics needed for the task. + +| Topic | Reference | Focus | +| --- | --- | --- | +| Baseline | [Universal](https://microsoft.github.io/rust-guidelines/guidelines/universal/) | Idioms, names, diagnostics, lint exceptions, public types | +| AI-assisted code | [AI](https://microsoft.github.io/rust-guidelines/guidelines/ai/) | Idiomatic APIs, focused paths, meaningful tests | +| Errors and panics | [Correctness](https://microsoft.github.io/rust-guidelines/guidelines/correctness/) | Expected failures versus bugs, panic contracts, soundness | +| Ownership and API design | [Library UX](https://microsoft.github.io/rust-guidelines/guidelines/libs/ux/) | Simple abstractions, builders, canonical errors, async APIs | +| Types and testability | [Library resilience](https://microsoft.github.io/rust-guidelines/guidelines/libs/resilience/) | Strong types and guarded invariants, injectable I/O, integration tests | +| Conversions and interoperability | [Library interoperability](https://microsoft.github.io/rust-guidelines/guidelines/libs/interop/) | Standard traits, borrowed views, ranges, Send, exposed dependencies | +| Cargo and features | [Library building](https://microsoft.github.io/rust-guidelines/guidelines/libs/building/) | Additive features, usable defaults, native dependencies | +| Workspace layout and toolchain | [Project](https://microsoft.github.io/rust-guidelines/guidelines/project/) | Workspaces, crate layout, edition, MSRV | +| Unsafe code | [Correctness](https://microsoft.github.io/rust-guidelines/guidelines/correctness/) | Safety obligations, undefined behavior, sound abstractions | +| FFI | [FFI](https://microsoft.github.io/rust-guidelines/guidelines/ffi/) | Boundary translation, names, isolated library state | +| Performance and concurrency | [Performance](https://microsoft.github.io/rust-guidelines/guidelines/performance/) | Measured hot paths, allocation, throughput, async stacks and yield points | +| Documentation | [Documentation](https://microsoft.github.io/rust-guidelines/guidelines/docs/) | Canonical docs, first sentences, inline and module documentation | +| Macros | [Macros](https://microsoft.github.io/rust-guidelines/guidelines/macros/) | Simpler alternatives, predictable expansion, procedural macro structure | +| Applications | [Applications](https://microsoft.github.io/rust-guidelines/guidelines/apps/) | Application errors, allocator and target choices | + +For a task spanning many topics, the complete +[agent-readable guidelines](https://microsoft.github.io/rust-guidelines/agents/all.txt) +are available as plain text. Prefer topic pages when the full document is not +needed. Follow relevant Rust API Guidelines links from the book as appropriate. + +## Applying and reviewing guidance + +- Check applicability before enforcing a rule. Explain a repository-policy + conflict or a justified exception rather than silently overriding it. +- Use the guideline's actual identifier, such as `M-STRONG-TYPES`, when explaining + a design choice or reporting a violation. Do not invent identifiers. +- For a finding, identify the affected file and location, the guideline, the + concrete consequence, and the smallest useful correction. Distinguish defects + from recommendations; do not report a preference as a correctness failure. +- Inspect constructors, conversions, deserialization, and mutation when checking + invariants. Inspect error paths and tests as well as the happy path. +- Keep fixes within scope. Reuse existing abstractions and avoid gratuitous + dependency changes, migrations, or unrelated cleanup. +- Verify dependency APIs against the project's pinned versions. A guideline or + upstream example does not establish that an API exists in the version in use. +- If a referenced page cannot be read, say which guidance is unavailable. Use + accessible repository documentation, but do not claim to have checked unread + guidelines or reconstruct their contents from their names. + +The book remains authoritative; this skill intentionally links to it instead of +maintaining a second, potentially divergent set of Rust rules. From 5f445ef37f9d79ddc7dd2078cf1a06a4f7c0191c Mon Sep 17 00:00:00 2001 From: Vaiz <4908982+Vaiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:41:17 +0000 Subject: [PATCH 2/4] fix: base skill on current rust-dev core guidelines Replace the link-only skill with the rust-core-guidelines trigger index, all 144 bundled rules, and original license notices from rust-dev at 0dca309355d50ee610b1b3c45f283019592b40d1. Rename the skill and remove the unbundled rust-task-docs dependency. Preserve upstream rule text verbatim and scope Markdown formatting exceptions to that imported snapshot. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 14 +- ai-skill/skills/rust-guidelines/SKILL.md | 217 ++++++++++++------ .../licenses/pragmatic-LICENSE.md.txt | 21 ++ .../licenses/rust-api-LICENSE-APACHE.txt | 201 ++++++++++++++++ .../licenses/rust-api-LICENSE-MIT.txt | 25 ++ .../rust-guidelines/rules/.markdownlint.json | 9 + .../rust-guidelines/rules/C-ANYWHERE.md | 38 +++ .../skills/rust-guidelines/rules/C-BITFLAG.md | 53 +++++ .../skills/rust-guidelines/rules/C-BUILDER.md | 173 ++++++++++++++ .../rust-guidelines/rules/C-CALLER-CONTROL.md | 36 +++ .../skills/rust-guidelines/rules/C-CASE.md | 41 ++++ .../skills/rust-guidelines/rules/C-COLLECT.md | 21 ++ .../rust-guidelines/rules/C-COMMON-TRAITS.md | 35 +++ .../rust-guidelines/rules/C-CONV-SPECIFIC.md | 20 ++ .../rust-guidelines/rules/C-CONV-TRAITS.md | 30 +++ .../skills/rust-guidelines/rules/C-CONV.md | 77 +++++++ .../rust-guidelines/rules/C-CRATE-DOC.md | 5 + .../skills/rust-guidelines/rules/C-CTOR.md | 85 +++++++ .../rust-guidelines/rules/C-CUSTOM-TYPE.md | 28 +++ .../rust-guidelines/rules/C-DEBUG-NONEMPTY.md | 12 + .../skills/rust-guidelines/rules/C-DEBUG.md | 3 + .../skills/rust-guidelines/rules/C-DEREF.md | 17 ++ .../rust-guidelines/rules/C-DTOR-BLOCK.md | 5 + .../rust-guidelines/rules/C-DTOR-FAIL.md | 9 + .../rust-guidelines/rules/C-EVOCATIVE.md | 60 +++++ .../skills/rust-guidelines/rules/C-EXAMPLE.md | 25 ++ .../skills/rust-guidelines/rules/C-FAILURE.md | 78 +++++++ .../skills/rust-guidelines/rules/C-FEATURE.md | 51 ++++ .../skills/rust-guidelines/rules/C-GENERIC.md | 82 +++++++ .../skills/rust-guidelines/rules/C-GETTER.md | 58 +++++ .../rust-guidelines/rules/C-GOOD-ERR.md | 94 ++++++++ .../skills/rust-guidelines/rules/C-HIDDEN.md | 33 +++ .../rust-guidelines/rules/C-INTERMEDIATE.md | 26 +++ .../skills/rust-guidelines/rules/C-ITER-TY.md | 36 +++ .../skills/rust-guidelines/rules/C-ITER.md | 41 ++++ .../skills/rust-guidelines/rules/C-LINK.md | 31 +++ .../rust-guidelines/rules/C-MACRO-ATTR.md | 29 +++ .../rust-guidelines/rules/C-MACRO-TY.md | 30 +++ .../rust-guidelines/rules/C-MACRO-VIS.md | 20 ++ .../rust-guidelines/rules/C-METADATA.md | 28 +++ .../skills/rust-guidelines/rules/C-METHOD.md | 27 +++ .../rust-guidelines/rules/C-NEWTYPE-HIDE.md | 60 +++++ .../skills/rust-guidelines/rules/C-NEWTYPE.md | 31 +++ .../skills/rust-guidelines/rules/C-NO-OUT.md | 26 +++ .../skills/rust-guidelines/rules/C-NUM-FMT.md | 14 ++ .../skills/rust-guidelines/rules/C-OBJECT.md | 57 +++++ .../rust-guidelines/rules/C-OVERLOAD.md | 9 + .../rust-guidelines/rules/C-PERMISSIVE.md | 67 ++++++ .../rust-guidelines/rules/C-QUESTION-MARK.md | 22 ++ .../rust-guidelines/rules/C-RELNOTES.md | 31 +++ .../rust-guidelines/rules/C-RW-VALUE.md | 31 +++ .../skills/rust-guidelines/rules/C-SEALED.md | 48 ++++ .../rust-guidelines/rules/C-SEND-SYNC.md | 26 +++ .../skills/rust-guidelines/rules/C-SERDE.md | 58 +++++ .../rust-guidelines/rules/C-SMART-PTR.md | 34 +++ .../skills/rust-guidelines/rules/C-STABLE.md | 37 +++ .../rust-guidelines/rules/C-STRUCT-BOUNDS.md | 74 ++++++ .../rust-guidelines/rules/C-STRUCT-PRIVATE.md | 9 + .../rust-guidelines/rules/C-VALIDATE.md | 69 ++++++ .../rust-guidelines/rules/C-WORD-ORDER.md | 19 ++ .../rust-guidelines/rules/M-APP-ERROR.md | 28 +++ .../rust-guidelines/rules/M-ASYNC-FN.md | 17 ++ .../rules/M-ASYNC-STACK-SIZE.md | 75 ++++++ .../rules/M-AVOID-INDIRECTION.md | 43 ++++ .../rust-guidelines/rules/M-AVOID-STATICS.md | 59 +++++ .../rust-guidelines/rules/M-AVOID-WRAPPERS.md | 29 +++ .../rules/M-BALANCED-MODULES.md | 13 ++ .../skills/rust-guidelines/rules/M-BOX-DST.md | 27 +++ .../rust-guidelines/rules/M-BUILD-RESULT.md | 24 ++ .../rust-guidelines/rules/M-CANONICAL-DOCS.md | 51 ++++ .../rules/M-CARGO-WORKSPACE.md | 7 + .../rules/M-COLLECTION-TRAITS.md | 17 ++ .../rules/M-CRATES-FLAT-FOLDER.md | 43 ++++ .../rules/M-CRATES-IN-WORKSPACE.md | 19 ++ .../rust-guidelines/rules/M-DESIGN-FOR-AI.md | 40 ++++ .../rust-guidelines/rules/M-DI-HIERARCHY.md | 85 +++++++ .../rust-guidelines/rules/M-DOC-INLINE.md | 31 +++ .../rules/M-DOCUMENTED-MAGIC.md | 32 +++ .../rules/M-DONT-LEAK-TYPES.md | 28 +++ .../rules/M-ERRORS-CANONICAL-STRUCTS.md | 119 ++++++++++ .../rust-guidelines/rules/M-ESCAPE-HATCHES.md | 30 +++ .../rules/M-ESSENTIAL-FN-INHERENT.md | 43 ++++ .../rules/M-EXAMPLE-OVER-PROC.md | 17 ++ .../rust-guidelines/rules/M-FAST-HASHER.md | 15 ++ .../rules/M-FEATURES-ADDITIVE.md | 16 ++ .../rust-guidelines/rules/M-FFI-NAMING.md | 10 + .../rust-guidelines/rules/M-FFI-TRANSLATES.md | 48 ++++ .../rules/M-FIRST-DOC-SENTENCE.md | 26 +++ .../rules/M-FOREIGN-REEXPORTS.md | 11 + .../rust-guidelines/rules/M-FROM-ERROR.md | 27 +++ .../skills/rust-guidelines/rules/M-HOTPATH.md | 41 ++++ .../rust-guidelines/rules/M-IMPL-ASREF.md | 44 ++++ .../skills/rust-guidelines/rules/M-IMPL-IO.md | 30 +++ .../rules/M-IMPL-RANGEBOUNDS.md | 25 ++ .../rust-guidelines/rules/M-INIT-BUILDER.md | 124 ++++++++++ .../rust-guidelines/rules/M-INIT-CASCADED.md | 33 +++ .../rules/M-INITIAL-CAPACITY.md | 28 +++ .../rules/M-INTEGRATION-TESTS.md | 7 + .../rules/M-ISOLATE-DLL-STATE.md | 50 ++++ .../rust-guidelines/rules/M-LATEST-EDITION.md | 7 + .../rules/M-LINT-OVERRIDE-EXPECT.md | 17 ++ .../rust-guidelines/rules/M-LOG-NOT-PRINT.md | 5 + .../rust-guidelines/rules/M-LOG-OVERHEAD.md | 25 ++ .../rust-guidelines/rules/M-LOG-STRUCTURED.md | 113 +++++++++ .../rust-guidelines/rules/M-MACRO-HELPERS.md | 22 ++ .../rules/M-MACRO-LAST-RESORT.md | 17 ++ .../rules/M-MACRO-MAIN-CRATE.md | 15 ++ .../rules/M-MACRO-VERSION-PIN.md | 21 ++ .../rules/M-MACROS-DONT-LIE.md | 23 ++ .../rust-guidelines/rules/M-MEM-REUSE.md | 47 ++++ .../rust-guidelines/rules/M-MIMALLOC-APPS.md | 22 ++ .../rules/M-MOCKABLE-SYSCALLS.md | 123 ++++++++++ .../rust-guidelines/rules/M-MODULE-DOCS.md | 33 +++ .../skills/rust-guidelines/rules/M-MSRV.md | 9 + .../rules/M-NO-GLOB-REEXPORTS.md | 30 +++ .../rules/M-NO-META-DESIGN-DOCUMENTATION.md | 20 ++ .../rust-guidelines/rules/M-NO-PRELUDE.md | 25 ++ .../skills/rust-guidelines/rules/M-OOBE.md | 63 +++++ .../rules/M-PANIC-CONTINUATION.md | 31 +++ .../rust-guidelines/rules/M-PANIC-IS-STOP.md | 28 +++ .../rust-guidelines/rules/M-PANIC-MESSAGE.md | 17 ++ .../rust-guidelines/rules/M-PANIC-ON-BUG.md | 41 ++++ .../rules/M-PARAMETER-CONSISTENCY.md | 23 ++ .../rust-guidelines/rules/M-PROC-IMPL.md | 30 +++ .../rules/M-PROC-IMPLIED-ITEMS.md | 50 ++++ .../rust-guidelines/rules/M-PUBLIC-DEBUG.md | 35 +++ .../rust-guidelines/rules/M-PUBLIC-DISPLAY.md | 13 ++ .../rust-guidelines/rules/M-REGULAR-FN.md | 42 ++++ .../rust-guidelines/rules/M-RUST-SHAPED.md | 21 ++ .../rust-guidelines/rules/M-SERVICES-CLONE.md | 57 +++++ .../rust-guidelines/rules/M-SHORT-NAMES.md | 11 + .../rust-guidelines/rules/M-SHRINK-TO-FIT.md | 20 ++ .../rules/M-SIMPLE-ABSTRACTIONS.md | 60 +++++ .../rules/M-SINGLE-ITEM-PATH.md | 31 +++ .../rust-guidelines/rules/M-SMALLER-CRATES.md | 36 +++ .../rules/M-STATIC-VERIFICATION.md | 78 +++++++ .../rules/M-STRONG-TYPES-GUARD.md | 39 ++++ .../rust-guidelines/rules/M-STRONG-TYPES.md | 18 ++ .../rust-guidelines/rules/M-SYS-CRATES.md | 27 +++ .../rust-guidelines/rules/M-TARGET-CPU.md | 19 ++ .../rules/M-TAUTOLOGICAL-TESTS.md | 20 ++ .../rust-guidelines/rules/M-TEST-UTIL.md | 23 ++ .../rust-guidelines/rules/M-THROUGHPUT.md | 28 +++ .../rust-guidelines/rules/M-TYPES-SEND.md | 93 ++++++++ .../rules/M-UNSAFE-IMPLIES-UB.md | 14 ++ .../skills/rust-guidelines/rules/M-UNSAFE.md | 55 +++++ .../skills/rust-guidelines/rules/M-UNSOUND.md | 63 +++++ .../rules/M-UPSTREAM-GUIDELINES.md | 24 ++ .../rust-guidelines/rules/M-WEASEL-WORDS.md | 24 ++ .../rust-guidelines/rules/M-YIELD-POINTS.md | 41 ++++ 150 files changed, 5742 insertions(+), 65 deletions(-) create mode 100644 ai-skill/skills/rust-guidelines/licenses/pragmatic-LICENSE.md.txt create mode 100644 ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-APACHE.txt create mode 100644 ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-MIT.txt create mode 100644 ai-skill/skills/rust-guidelines/rules/.markdownlint.json create mode 100644 ai-skill/skills/rust-guidelines/rules/C-ANYWHERE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-BITFLAG.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-BUILDER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CALLER-CONTROL.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CASE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-COLLECT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-COMMON-TRAITS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CONV-SPECIFIC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CONV-TRAITS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CONV.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CRATE-DOC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CTOR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-CUSTOM-TYPE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-DEBUG-NONEMPTY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-DEBUG.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-DEREF.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-DTOR-BLOCK.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-DTOR-FAIL.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-EVOCATIVE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-EXAMPLE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-FAILURE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-FEATURE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-GENERIC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-GETTER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-GOOD-ERR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-HIDDEN.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-INTERMEDIATE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-ITER-TY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-ITER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-LINK.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-MACRO-ATTR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-MACRO-TY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-MACRO-VIS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-METADATA.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-METHOD.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-NEWTYPE-HIDE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-NEWTYPE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-NO-OUT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-NUM-FMT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-OBJECT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-OVERLOAD.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-PERMISSIVE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-QUESTION-MARK.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-RELNOTES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-RW-VALUE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-SEALED.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-SEND-SYNC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-SERDE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-SMART-PTR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-STABLE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-STRUCT-BOUNDS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-STRUCT-PRIVATE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-VALIDATE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/C-WORD-ORDER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-APP-ERROR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ASYNC-FN.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ASYNC-STACK-SIZE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-AVOID-INDIRECTION.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-AVOID-STATICS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-AVOID-WRAPPERS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-BALANCED-MODULES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-BOX-DST.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-BUILD-RESULT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-CANONICAL-DOCS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-CARGO-WORKSPACE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-COLLECTION-TRAITS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-CRATES-FLAT-FOLDER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-CRATES-IN-WORKSPACE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-DESIGN-FOR-AI.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-DI-HIERARCHY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-DOC-INLINE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-DOCUMENTED-MAGIC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-DONT-LEAK-TYPES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ERRORS-CANONICAL-STRUCTS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ESCAPE-HATCHES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ESSENTIAL-FN-INHERENT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-EXAMPLE-OVER-PROC.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FAST-HASHER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FEATURES-ADDITIVE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FFI-NAMING.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FFI-TRANSLATES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FIRST-DOC-SENTENCE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FOREIGN-REEXPORTS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-FROM-ERROR.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-HOTPATH.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-IMPL-ASREF.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-IMPL-IO.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-IMPL-RANGEBOUNDS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-INIT-BUILDER.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-INIT-CASCADED.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-INITIAL-CAPACITY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-INTEGRATION-TESTS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-ISOLATE-DLL-STATE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-LATEST-EDITION.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-LINT-OVERRIDE-EXPECT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-LOG-NOT-PRINT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-LOG-OVERHEAD.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-LOG-STRUCTURED.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MACRO-HELPERS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MACRO-LAST-RESORT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MACRO-MAIN-CRATE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MACRO-VERSION-PIN.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MACROS-DONT-LIE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MEM-REUSE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MIMALLOC-APPS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MOCKABLE-SYSCALLS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MODULE-DOCS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-MSRV.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-NO-GLOB-REEXPORTS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-NO-META-DESIGN-DOCUMENTATION.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-NO-PRELUDE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-OOBE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PANIC-CONTINUATION.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PANIC-IS-STOP.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PANIC-MESSAGE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PANIC-ON-BUG.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PARAMETER-CONSISTENCY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PROC-IMPL.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PROC-IMPLIED-ITEMS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DEBUG.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DISPLAY.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-REGULAR-FN.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-RUST-SHAPED.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SERVICES-CLONE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SHORT-NAMES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SHRINK-TO-FIT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SIMPLE-ABSTRACTIONS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SINGLE-ITEM-PATH.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SMALLER-CRATES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-STATIC-VERIFICATION.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES-GUARD.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-SYS-CRATES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-TARGET-CPU.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-TAUTOLOGICAL-TESTS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-TEST-UTIL.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-THROUGHPUT.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-TYPES-SEND.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-UNSAFE-IMPLIES-UB.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-UNSAFE.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-UNSOUND.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-UPSTREAM-GUIDELINES.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-WEASEL-WORDS.md create mode 100644 ai-skill/skills/rust-guidelines/rules/M-YIELD-POINTS.md diff --git a/README.md b/README.md index aee43c0..94aed5f 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,19 @@ This repository is also a Copilot plugin marketplace with one plugin, `rust-guidelines`, containing one skill of the same name. The plugin lives in [`ai-skill`](ai-skill); the discovery catalog is [`.github/plugin/marketplace.json`](.github/plugin/marketplace.json). -The skill reads the public guidelines on demand, so internet access is required. +The skill bundles a trigger index and individual `rules/.md` files, loading +only the guidelines applicable to the current task. It works offline after +installation; the rules do not need to be fetched from the web. + +The skill is adapted from rust-dev's +[`rust-core-guidelines`](https://github.com/agency-microsoft/playground/tree/0dca309355d50ee610b1b3c45f283019592b40d1/plugins/rust-dev/skills/rust-core-guidelines): +the index and all 144 rule files are retained, the skill is renamed to +`rust-guidelines`, and the dependency on the separate `rust-task-docs` skill is +removed. The bundled rules cover the Pragmatic Rust Guidelines and the Rust API +Guidelines. Their original +[license notices](ai-skill/skills/rust-guidelines/licenses) are included. +The rule files are a verbatim snapshot; their local Markdown lint configuration +preserves upstream formatting without relaxing linting for the skill entry point. ### Copilot CLI diff --git a/ai-skill/skills/rust-guidelines/SKILL.md b/ai-skill/skills/rust-guidelines/SKILL.md index b53068a..5bd7a99 100644 --- a/ai-skill/skills/rust-guidelines/SKILL.md +++ b/ai-skill/skills/rust-guidelines/SKILL.md @@ -1,73 +1,162 @@ --- name: rust-guidelines -description: Apply the Pragmatic Rust Guidelines when writing, refactoring, or reviewing Rust code, designing Rust APIs, or changing Rust tests, documentation, Cargo workspaces, unsafe code, or FFI. -license: MIT +description: Always load when working on a Rust project. --- -# Pragmatic Rust Guidelines +# Rust guidelines -Use the [Pragmatic Rust Guidelines](https://microsoft.github.io/rust-guidelines/) -as the source of truth. This skill covers both application and library code. +Scan the [index](#index) before Rust work. Automatically load applicable +`rules/.md` files, relative to this skill, as the task changes. -## Workflow +After loading a guideline, print `🦀 - `. +Name the concrete change, code or request; do not repeat the index's generic trigger. +Report missing files; do not guess or refresh. -1. Read the repository's instructions and the code affected by the task. - Identify the intended behavior, public contracts, and supported Rust version. -2. Read the [applicability and golden rule](https://microsoft.github.io/rust-guidelines/guidelines/). - Distinguish requirements from recommendations and respect their exceptions. -3. Use the topic map below to read the relevant guidelines before changing or - reviewing code. Start with universal guidelines; add topics as needed. - Use the [checklist](https://microsoft.github.io/rust-guidelines/guidelines/checklist/) - for broader reviews, not as a substitute for reading a guideline's rationale. -4. Apply the relevant guidance to each changed type, signature, implementation, - and test. Preserve existing behavior unless the task calls for changing it. -5. Run the repository's appropriate formatting, lint, and targeted test commands. - Report concrete findings and any validation that could not be completed. +## Index -## Topic map +Format: `ID - trigger` -All links point to the public book. Read only the topics needed for the task. - -| Topic | Reference | Focus | -| --- | --- | --- | -| Baseline | [Universal](https://microsoft.github.io/rust-guidelines/guidelines/universal/) | Idioms, names, diagnostics, lint exceptions, public types | -| AI-assisted code | [AI](https://microsoft.github.io/rust-guidelines/guidelines/ai/) | Idiomatic APIs, focused paths, meaningful tests | -| Errors and panics | [Correctness](https://microsoft.github.io/rust-guidelines/guidelines/correctness/) | Expected failures versus bugs, panic contracts, soundness | -| Ownership and API design | [Library UX](https://microsoft.github.io/rust-guidelines/guidelines/libs/ux/) | Simple abstractions, builders, canonical errors, async APIs | -| Types and testability | [Library resilience](https://microsoft.github.io/rust-guidelines/guidelines/libs/resilience/) | Strong types and guarded invariants, injectable I/O, integration tests | -| Conversions and interoperability | [Library interoperability](https://microsoft.github.io/rust-guidelines/guidelines/libs/interop/) | Standard traits, borrowed views, ranges, Send, exposed dependencies | -| Cargo and features | [Library building](https://microsoft.github.io/rust-guidelines/guidelines/libs/building/) | Additive features, usable defaults, native dependencies | -| Workspace layout and toolchain | [Project](https://microsoft.github.io/rust-guidelines/guidelines/project/) | Workspaces, crate layout, edition, MSRV | -| Unsafe code | [Correctness](https://microsoft.github.io/rust-guidelines/guidelines/correctness/) | Safety obligations, undefined behavior, sound abstractions | -| FFI | [FFI](https://microsoft.github.io/rust-guidelines/guidelines/ffi/) | Boundary translation, names, isolated library state | -| Performance and concurrency | [Performance](https://microsoft.github.io/rust-guidelines/guidelines/performance/) | Measured hot paths, allocation, throughput, async stacks and yield points | -| Documentation | [Documentation](https://microsoft.github.io/rust-guidelines/guidelines/docs/) | Canonical docs, first sentences, inline and module documentation | -| Macros | [Macros](https://microsoft.github.io/rust-guidelines/guidelines/macros/) | Simpler alternatives, predictable expansion, procedural macro structure | -| Applications | [Applications](https://microsoft.github.io/rust-guidelines/guidelines/apps/) | Application errors, allocator and target choices | - -For a task spanning many topics, the complete -[agent-readable guidelines](https://microsoft.github.io/rust-guidelines/agents/all.txt) -are available as plain text. Prefer topic pages when the full document is not -needed. Follow relevant Rust API Guidelines links from the book as appropriate. - -## Applying and reviewing guidance - -- Check applicability before enforcing a rule. Explain a repository-policy - conflict or a justified exception rather than silently overriding it. -- Use the guideline's actual identifier, such as `M-STRONG-TYPES`, when explaining - a design choice or reporting a violation. Do not invent identifiers. -- For a finding, identify the affected file and location, the guideline, the - concrete consequence, and the smallest useful correction. Distinguish defects - from recommendations; do not report a preference as a correctness failure. -- Inspect constructors, conversions, deserialization, and mutation when checking - invariants. Inspect error paths and tests as well as the happy path. -- Keep fixes within scope. Reuse existing abstractions and avoid gratuitous - dependency changes, migrations, or unrelated cleanup. -- Verify dependency APIs against the project's pinned versions. A guideline or - upstream example does not establish that an API exists in the version in use. -- If a referenced page cannot be read, say which guidance is unavailable. Use - accessible repository documentation, but do not claim to have checked unread - guidelines or reconstruct their contents from their names. - -The book remains authoritative; this skill intentionally links to it instead of -maintaining a second, potentially divergent set of Rust rules. +C-ANYWHERE - when defining or testing macros that expand to items in different scopes +C-BITFLAG - when an API accepts combinations of independent flags +C-BUILDER - when constructing values with many inputs, optional settings, or side effects +C-CALLER-CONTROL - when choosing owned or borrowed parameters, internal clones, or Copy bounds +C-CASE - when naming Rust items, variables, type parameters, lifetimes, or Cargo features +C-COLLECT - when adding collection types that can be built or extended from iterators +C-COMMON-TRAITS - when defining types and choosing their standard trait implementations +C-CONV - when naming conversions between representations or extracting wrapped values +C-CONV-SPECIFIC - when choosing which type owns a conversion method or constructor +C-CONV-TRAITS - when adding owned, borrowed, mutable, or fallible conversions between types +C-CRATE-DOC - when creating or revising a crate's top-level documentation +C-CTOR - when adding constructors, conversion constructors, or Default implementations +C-CUSTOM-TYPE - when API arguments use primitives or Option with ambiguous domain meanings +C-DEBUG - when adding or changing publicly exposed types +C-DEBUG-NONEMPTY - when implementing Debug, including for empty values +C-DEREF - when considering Deref or DerefMut for a wrapper or smart pointer +C-DTOR-BLOCK - when resource cleanup or Drop may perform blocking operations +C-DTOR-FAIL - when resource cleanup or Drop can fail or panic +C-EVOCATIVE - when designing macro input syntax for generated Rust constructs +C-EXAMPLE - when adding public items or revising their rustdoc usage examples +C-FAILURE - when functions or trait methods can fail, panic, or require safety invariants +C-FEATURE - when naming Cargo features, including optional dependencies and std support +C-GENERIC - when choosing concrete inputs, generic parameters, or trait bounds for functions +C-GETTER - when adding getters, mutable accessors, or checked and unchecked element access +C-GOOD-ERR - when designing errors returned by public APIs, including error trait objects +C-HIDDEN - when internal types, helpers, or trait impls appear in public rustdoc +C-INTERMEDIATE - when an operation computes related results that callers might otherwise recompute +C-ITER - when adding iteration methods to homogeneous collections +C-ITER-TY - when naming iterator types returned by methods or functions +C-LINK - when documentation mentions related types, methods, modules, or external resources +C-MACRO-ATTR - when item-generating macros need per-item attributes, cfg, or derives +C-MACRO-TY - when macros accept type fragments or emit them in a different scope +C-MACRO-VIS - when macros generate items whose visibility callers may need to control +C-METADATA - when creating or preparing a crate's Cargo.toml package metadata +C-METHOD - when placing an operation clearly associated with a particular receiver type +C-NEWTYPE - when the same underlying type represents distinct units or domain concepts +C-NEWTYPE-HIDE - when API return types expose implementation details or complex iterator composition +C-NO-OUT - when returning multiple values or considering mutable output parameters +C-NUM-FMT - when defining numeric or bitflag types used in bitwise operations +C-OBJECT - when designing traits that may be used through dyn Trait +C-OVERLOAD - when implementing operator traits such as Add, Mul, or BitOr +C-PERMISSIVE - when choosing crate licenses or dependencies for ecosystem distribution +C-QUESTION-MARK - when writing documentation examples that perform fallible operations +C-RELNOTES - when publishing crate versions or documenting significant and breaking changes +C-RW-VALUE - when designing or documenting functions accepting generic Read or Write inputs +C-SEALED - when public traits should only have implementations inside their defining crate +C-SEND-SYNC - when type changes, raw pointers, or tests affect Send and Sync guarantees +C-SERDE - when defining data structures callers may store, serialize, or exchange +C-SMART-PTR - when adding operations to smart pointers that also expose pointee methods +C-STABLE - when stabilizing a crate or exposing dependency types through public APIs or impls +C-STRUCT-BOUNDS - when adding generic data structures, derived traits, or type-level bounds +C-STRUCT-PRIVATE - when choosing field visibility for structs exposed to callers +C-VALIDATE - when API inputs have validity constraints or checked and unchecked entry points +C-WORD-ORDER - when naming related items, especially families of error types +M-APP-ERROR - when choosing error handling for applications and their app-only internal crates +M-ASYNC-FN - when choosing async fn versus an explicit Future-returning signature +M-ASYNC-STACK-SIZE - when async functions are called frequently or retain large data across await points +M-AVOID-INDIRECTION - when hot data structures use nested heap pointers or shared ownership +M-AVOID-STATICS - when library correctness depends on static or thread-local state +M-AVOID-WRAPPERS - when public APIs accept or return smart pointers or generic wrappers +M-BALANCED-MODULES - when organizing a library's crate root, public items, and submodules +M-BOX-DST - when storing many internal immutable owned strings or sequences +M-BUILD-RESULT - when builder settings need validation or can fail in combination +M-CANONICAL-DOCS - when documenting public library items and their error or safety contracts +M-CARGO-WORKSPACE - when configuring shared metadata, lints, dependencies, or features across crates +M-COLLECTION-TRAITS - when exposing custom collections and their iterators to downstream users +M-CRATES-FLAT-FOLDER - when adding crates or reorganizing a repository's workspace directories +M-CRATES-IN-WORKSPACE - when adding workspace members or dependencies between sibling crates +M-DESIGN-FOR-AI - when designing APIs, examples, or testability for human and agent consumers +M-DI-HIERARCHY - when injecting async dependencies or choosing concrete, generic, or dynamic services +M-DOC-INLINE - when re-exporting items and deciding how they appear in rustdoc +M-DOCUMENTED-MAGIC - when introducing or changing hardcoded production values or constants +M-DONT-LEAK-TYPES - when public library APIs expose types from dependency crates +M-ERRORS-CANONICAL-STRUCTS - when defining reusable library errors, their context, causes, or backtraces +M-ESCAPE-HATCHES - when wrapping native handles that callers may need to import or pass over FFI +M-ESSENTIAL-FN-INHERENT - when exposing a type's core functionality through inherent methods or traits +M-EXAMPLE-OVER-PROC - when choosing declarative versus procedural macros for code generation +M-FAST-HASHER - when hashing trusted internal keys or choosing hash collection implementations +M-FEATURES-ADDITIVE - when adding library features or changing feature-gated APIs and dependencies +M-FFI-NAMING - when naming crates that import native APIs or export Rust APIs over FFI +M-FFI-TRANSLATES - when exposing Rust business logic through C-compatible FFI entry points +M-FIRST-DOC-SENTENCE - when writing rustdoc summaries shown in module item listings +M-FOREIGN-REEXPORTS - when considering re-exports of items defined in other crates +M-FROM-ERROR - when converting upstream errors into owned error types or repeating map_err calls +M-HOTPATH - when developing or changing code with performance or operating-cost impact +M-IMPL-ASREF - when accepting strings, paths, or byte sequences and choosing reference bounds +M-IMPL-IO - when APIs parse, emit, or initialize data through synchronous or asynchronous I/O +M-IMPL-RANGEBOUNDS - when function parameters represent numeric ranges or bounds +M-INIT-BUILDER - when construction has many optional settings, required dependencies, or runtime variants +M-INIT-CASCADED - when constructors require four or more parameters or nested initialization +M-INITIAL-CAPACITY - when building collections with known or estimable sizes, including via iterators +M-INTEGRATION-TESTS - when adding tests that can exercise behavior through public APIs +M-ISOLATE-DLL-STATE - when exchanging data or services between separately compiled Rust dynamic libraries +M-LATEST-EDITION - when creating a Rust crate or workspace and choosing its edition +M-LINT-OVERRIDE-EXPECT - when suppressing project lints on items, modules, macros, or generated code +M-LOG-NOT-PRINT - when adding production diagnostics or distinguishing them from intentional CLI output +M-LOG-OVERHEAD - when libraries emit logs or metrics on hot paths or under sustained load +M-LOG-STRUCTURED - when adding log events, their names and properties, or potentially sensitive values +M-MACRO-HELPERS - when macro expansions refer to types or traits from third-party dependencies +M-MACRO-LAST-RESORT - when considering a macro to replace repeated or complex ordinary Rust code +M-MACRO-MAIN-CRATE - when procedural macros generate crate paths or are re-exported through a facade +M-MACRO-VERSION-PIN - when wiring or publishing companion proc-macro crates and their main library +M-MACROS-DONT-LIE - when macros transform item kinds, function signatures, or async behavior +M-MEM-REUSE - when repeated operations allocate buffers or APIs could let callers reuse resources +M-MIMALLOC-APPS - when creating applications or choosing their global memory allocator +M-MOCKABLE-SYSCALLS - when user-facing types access I/O, clocks, randomness, hardware, or external state +M-MODULE-DOCS - when adding public library modules or changing subsystem behavior and guarantees +M-MSRV - when creating libraries or adopting language features that raise compiler requirements +M-NO-GLOB-REEXPORTS - when re-exporting items from modules, dependencies, or platform-specific backends +M-NO-META-DESIGN-DOCUMENTATION - when writing crate or module docs after design work or refactoring +M-NO-PRELUDE - when designing convenience imports or a prelude namespace for a crate +M-OOBE - when adding library build steps, dependencies, code generation, or platform requirements +M-PANIC-CONTINUATION - when catching panics or designing request isolation and recovery +M-PANIC-IS-STOP - when deciding to panic, unwrap, or propagate a runtime failure +M-PANIC-MESSAGE - when adding explicit panics, assertions, or unreachable and unfinished-code markers +M-PANIC-ON-BUG - when distinguishing detected contract violations from expected input failures +M-PARAMETER-CONSISTENCY - when related functions share parameters or accept closures and common dependencies +M-PROC-IMPL - when implementing, organizing, or testing procedural macros +M-PROC-IMPLIED-ITEMS - when procedural macros introduce additional types or items into caller scopes +M-PUBLIC-DEBUG - when exposing types or implementing Debug, especially for sensitive data +M-PUBLIC-DISPLAY - when public types, errors, or string wrappers need human-readable formatting +M-REGULAR-FN - when placing helper computations without a clear receiver or constructor role +M-RUST-SHAPED - when porting code or architecture from object-oriented or other language ecosystems +M-SERVICES-CLONE - when service types or per-thread resources must be shared by multiple consumers +M-SHORT-NAMES - when naming items whose context may already be conveyed by a module or crate +M-SHRINK-TO-FIT - when storing large long-lived collections built without exact capacity reservations +M-SIMPLE-ABSTRACTIONS - when public types expose nested generics, complex bounds, or service abstractions +M-SINGLE-ITEM-PATH - when moving public items or constructing their re-export paths within a crate +M-SMALLER-CRATES - when modules could be consumed independently or crate boundaries affect build times +M-STATIC-VERIFICATION - when configuring Rust project checks, lint sets, or CI quality gates +M-STRONG-TYPES - when choosing standard types for domain data, especially OS paths and numeric APIs +M-STRONG-TYPES-GUARD - when constructing or converting newtypes whose valid values are restricted +M-SYS-CRATES - when building and packaging native library bindings in a sys crate +M-TARGET-CPU - when configuring server application builds for known deployment hardware +M-TAUTOLOGICAL-TESTS - when designing test assertions or tests to satisfy mutation coverage +M-TEST-UTIL - when exposing mocks, fake data, sensitive inspection, or test-only safety overrides +M-THROUGHPUT - when designing library work batching, shared state, task scheduling, or throughput +M-TYPES-SEND - when exposing library types or futures and changing data held across await points +M-UNSAFE - when introducing or modifying unsafe code, FFI calls, or unchecked operations +M-UNSAFE-IMPLIES-UB - when deciding whether a function or trait should be marked unsafe +M-UNSOUND - when safe interfaces rely on unsafe internals, module invariants, or manual Send/Sync +M-UPSTREAM-GUIDELINES - when reviewing Rust API conventions, style, design patterns, or safety guarantees +M-WEASEL-WORDS - when naming types or traits, or designing factories and repeated instantiation +M-YIELD-POINTS - when async tasks perform long CPU-bound work or process large batches diff --git a/ai-skill/skills/rust-guidelines/licenses/pragmatic-LICENSE.md.txt b/ai-skill/skills/rust-guidelines/licenses/pragmatic-LICENSE.md.txt new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/licenses/pragmatic-LICENSE.md.txt @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-APACHE.txt b/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-APACHE.txt new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-APACHE.txt @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + +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/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-MIT.txt b/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-MIT.txt new file mode 100644 index 0000000..52d8241 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/licenses/rust-api-LICENSE-MIT.txt @@ -0,0 +1,25 @@ +Copyright (c) 2017 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/ai-skill/skills/rust-guidelines/rules/.markdownlint.json b/ai-skill/skills/rust-guidelines/rules/.markdownlint.json new file mode 100644 index 0000000..4553a2e --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/.markdownlint.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../../.markdownlint.json", + "MD001": false, + "MD004": false, + "MD009": false, + "MD034": false, + "MD040": false, + "MD053": false +} diff --git a/ai-skill/skills/rust-guidelines/rules/C-ANYWHERE.md b/ai-skill/skills/rust-guidelines/rules/C-ANYWHERE.md new file mode 100644 index 0000000..0c5f1a9 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-ANYWHERE.md @@ -0,0 +1,38 @@ +## Item macros work anywhere that items are allowed (C-ANYWHERE) + +Rust allows items to be placed at the module level or within a tighter scope +like a function. Item macros should work equally well as ordinary items in all +of these places. The test suite should include invocations of the macro in at +least the module scope and function scope. + +``` +#[cfg(test)] +mod tests { + test_your_macro_in_a!(module); + + #[test] + fn anywhere() { + test_your_macro_in_a!(function); + } +} +``` + +As a simple example of how things can go wrong, this macro works great in a +module scope but fails in a function scope. + +``` +macro_rules! broken { + ($m:ident :: $t:ident) => { + pub struct $t; + pub mod $m { + pub use super::$t; + } + } +} + +broken!(m::T); // okay, expands to T and m::T + +fn g() { + broken!(m::U); // fails to compile, super::U refers to the containing module not g +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-BITFLAG.md b/ai-skill/skills/rust-guidelines/rules/C-BITFLAG.md new file mode 100644 index 0000000..cf16e6a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-BITFLAG.md @@ -0,0 +1,53 @@ +## Types for a set of flags are `bitflags`, not enums (C-BITFLAG) + +Rust supports `enum` types with explicitly specified discriminants: + +``` +enum Color { + Red = 0xff0000, + Green = 0x00ff00, + Blue = 0x0000ff, +} +``` + +Custom discriminants are useful when an `enum` type needs to be serialized to an +integer value compatibly with some other system/language. They support +"typesafe" APIs: by taking a `Color`, rather than an integer, a function is +guaranteed to get well-formed inputs, even if it later views those inputs as +integers. + +An `enum` allows an API to request exactly one choice from among many. Sometimes +an API's input is instead the presence or absence of a set of flags. In C code, +this is often done by having each flag correspond to a particular bit, allowing +a single integer to represent, say, 32 or 64 flags. Rust's [`bitflags`] crate +provides a typesafe representation of this pattern. + +[`bitflags`]: https://github.com/bitflags/bitflags + +``` +use bitflags::bitflags; + +bitflags! { + struct Flags: u32 { + const FLAG_A = 0b00000001; + const FLAG_B = 0b00000010; + const FLAG_C = 0b00000100; + } +} + +fn f(settings: Flags) { + if settings.contains(Flags::FLAG_A) { + println!("doing thing A"); + } + if settings.contains(Flags::FLAG_B) { + println!("doing thing B"); + } + if settings.contains(Flags::FLAG_C) { + println!("doing thing C"); + } +} + +fn main() { + f(Flags::FLAG_A | Flags::FLAG_C); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-BUILDER.md b/ai-skill/skills/rust-guidelines/rules/C-BUILDER.md new file mode 100644 index 0000000..40b6c77 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-BUILDER.md @@ -0,0 +1,173 @@ +## Builders enable construction of complex values (C-BUILDER) + +Some data structures are complicated to construct, due to their construction +needing: + +* a large number of inputs +* compound data (e.g. slices) +* optional configuration data +* choice between several flavors + +which can easily lead to a large number of distinct constructors with many +arguments each. + +If `T` is such a data structure, consider introducing a `T` _builder_: + +1. Introduce a separate data type `TBuilder` for incrementally configuring a `T` + value. When possible, choose a better name: e.g. [`Command`] is the builder + for a [child process], [`Url`] can be created from a [`ParseOptions`]. +2. The builder constructor should take as parameters only the data _required_ to + make a `T`. +3. The builder should offer a suite of convenient methods for configuration, + including setting up compound inputs (like slices) incrementally. These + methods should return `self` to allow chaining. +4. The builder should provide one or more "_terminal_" methods for actually + building a `T`. + +[`Command`]: https://doc.rust-lang.org/std/process/struct.Command.html +[child process]: https://doc.rust-lang.org/std/process/struct.Child.html +[`Url`]: https://docs.rs/url/1.4.0/url/struct.Url.html +[`ParseOptions`]: https://docs.rs/url/1.4.0/url/struct.ParseOptions.html + +The builder pattern is especially appropriate when building a `T` involves side +effects, such as spawning a task or launching a process. + +In Rust, there are two variants of the builder pattern, differing in the +treatment of ownership, as described below. + +### Non-consuming builders (preferred) + +In some cases, constructing the final `T` does not require the builder itself to +be consumed. The following variant on [`std::process::Command`] is one example: + +[`std::process::Command`]: https://doc.rust-lang.org/std/process/struct.Command.html + +``` +// NOTE: the actual Command API does not use owned Strings; +// this is a simplified version. + +pub struct Command { + program: String, + args: Vec, + cwd: Option, + // etc +} + +impl Command { + pub fn new(program: String) -> Command { + Command { + program: program, + args: Vec::new(), + cwd: None, + } + } + + /// Add an argument to pass to the program. + pub fn arg(&mut self, arg: String) -> &mut Command { + self.args.push(arg); + self + } + + /// Add multiple arguments to pass to the program. + pub fn args(&mut self, args: &[String]) -> &mut Command { + self.args.extend_from_slice(args); + self + } + + /// Set the working directory for the child process. + pub fn current_dir(&mut self, dir: String) -> &mut Command { + self.cwd = Some(dir); + self + } + + /// Executes the command as a child process, which is returned. + pub fn spawn(&self) -> io::Result { + /* ... */ + } +} +``` + +Note that the `spawn` method, which actually uses the builder configuration to +spawn a process, takes the builder by shared reference. This is possible because +spawning the process does not require ownership of the configuration data. + +Because the terminal `spawn` method only needs a reference, the configuration +methods take and return a mutable borrow of `self`. + +#### The benefit + +By using borrows throughout, `Command` can be used conveniently for both +one-liner and more complex constructions: + +``` +// One-liners +Command::new("/bin/cat").arg("file.txt").spawn(); + +// Complex configuration +let mut cmd = Command::new("/bin/ls"); +if size_sorted { + cmd.arg("-S"); +} +cmd.arg("."); +cmd.spawn(); +``` + +### Consuming builders + +Sometimes builders must transfer ownership when constructing the final type `T`, +meaning that the terminal methods must take `self` rather than `&self`. + +``` +impl TaskBuilder { + /// Name the task-to-be. + pub fn named(mut self, name: String) -> TaskBuilder { + self.name = Some(name); + self + } + + /// Redirect task-local stdout. + pub fn stdout(mut self, stdout: Box) -> TaskBuilder { + self.stdout = Some(stdout); + self + } + + /// Creates and executes a new child task. + pub fn spawn(self, f: F) where F: FnOnce() + Send { + /* ... */ + } +} +``` + +Here, the `stdout` configuration involves passing ownership of an `io::Write`, +which must be transferred to the task upon construction (in `spawn`). + +When the terminal methods of the builder require ownership, there is a basic +tradeoff: + +* If the other builder methods take/return a mutable borrow, the complex + configuration case will work well, but one-liner configuration becomes + impossible. + +* If the other builder methods take/return an owned `self`, one-liners continue + to work well but complex configuration is less convenient. + +Under the rubric of making easy things easy and hard things possible, all +builder methods for a consuming builder should take and return an owned +`self`. Then client code works as follows: + +``` +// One-liners +TaskBuilder::new("my_task").spawn(|| { /* ... */ }); + +// Complex configuration +let mut task = TaskBuilder::new(); +task = task.named("my_task_2"); // must re-assign to retain ownership +if reroute { + task = task.stdout(mywriter); +} +task.spawn(|| { /* ... */ }); +``` + +One-liners work as before, because ownership is threaded through each of the +builder methods until being consumed by `spawn`. Complex configuration, however, +is more verbose: it requires re-assigning the builder at each step. diff --git a/ai-skill/skills/rust-guidelines/rules/C-CALLER-CONTROL.md b/ai-skill/skills/rust-guidelines/rules/C-CALLER-CONTROL.md new file mode 100644 index 0000000..77851a8 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CALLER-CONTROL.md @@ -0,0 +1,36 @@ +## Caller decides where to copy and place data (C-CALLER-CONTROL) + +If a function requires ownership of an argument, it should take ownership of the +argument rather than borrowing and cloning the argument. + +``` +// Prefer this: +fn foo(b: Bar) { + /* use b as owned, directly */ +} + +// Over this: +fn foo(b: &Bar) { + let b = b.clone(); + /* use b as owned after cloning */ +} +``` + +If a function *does not* require ownership of an argument, it should take a +shared or exclusive borrow of the argument rather than taking ownership and +dropping the argument. + +``` +// Prefer this: +fn foo(b: &Bar) { + /* use b as borrowed */ +} + +// Over this: +fn foo(b: Bar) { + /* use b as borrowed, it is implicitly dropped before function returns */ +} +``` + +The `Copy` trait should only be used as a bound when absolutely needed, not as a +way of signaling that copies should be cheap to make. diff --git a/ai-skill/skills/rust-guidelines/rules/C-CASE.md b/ai-skill/skills/rust-guidelines/rules/C-CASE.md new file mode 100644 index 0000000..5fd32fc --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CASE.md @@ -0,0 +1,41 @@ +## Casing conforms to RFC 430 (C-CASE) + +Basic Rust naming conventions are described in [RFC 430]. + +In general, Rust tends to use `UpperCamelCase` for "type-level" constructs (types and +traits) and `snake_case` for "value-level" constructs. More precisely: + +| Item | Convention | +| ---- | ---------- | +| Crates | [unclear](https://github.com/rust-lang/api-guidelines/issues/29) | +| Modules | `snake_case` | +| Types | `UpperCamelCase` | +| Traits | `UpperCamelCase` | +| Enum variants | `UpperCamelCase` | +| Functions | `snake_case` | +| Methods | `snake_case` | +| General constructors | `new` or `with_more_details` | +| Conversion constructors | `from_some_other_type` | +| Macros | `snake_case!` | +| Local variables | `snake_case` | +| Statics | `SCREAMING_SNAKE_CASE` | +| Constants | `SCREAMING_SNAKE_CASE` | +| Type parameters | concise `UpperCamelCase`, usually single uppercase letter: `T` | +| Lifetimes | short `lowercase`, usually a single letter: `'a`, `'de`, `'src` | +| Features | [unclear](https://github.com/rust-lang/api-guidelines/issues/101) but see [C-FEATURE] | + +In `UpperCamelCase`, acronyms and contractions of compound words count as one word: use `Uuid` rather than `UUID`, `Usize` rather than `USize` or `Stdin` rather than `StdIn`. In `snake_case`, acronyms and contractions are lower-cased: `is_xid_start`. + +In `snake_case` or `SCREAMING_SNAKE_CASE`, a "word" should never consist of a +single letter unless it is the last "word". So, we have `btree_map` rather than +`b_tree_map`, but `PI_2` rather than `PI2`. + +Crate names should not use `-rs` or `-rust` as a suffix or prefix. Every crate +is Rust! It serves no purpose to remind users of this constantly. + +[RFC 430]: https://github.com/rust-lang/rfcs/blob/master/text/0430-finalizing-naming-conventions.md +[C-FEATURE]: C-FEATURE.md + +### Examples from the standard library + +The whole standard library. This guideline should be easy! diff --git a/ai-skill/skills/rust-guidelines/rules/C-COLLECT.md b/ai-skill/skills/rust-guidelines/rules/C-COLLECT.md new file mode 100644 index 0000000..eeb3acd --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-COLLECT.md @@ -0,0 +1,21 @@ +## Collections implement `FromIterator` and `Extend` (C-COLLECT) + +[`FromIterator`] and [`Extend`] enable collections to be used conveniently with +the following iterator methods: + +[`FromIterator`]: https://doc.rust-lang.org/std/iter/trait.FromIterator.html +[`Extend`]: https://doc.rust-lang.org/std/iter/trait.Extend.html + +- [`Iterator::collect`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect) +- [`Iterator::partition`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.partition) +- [`Iterator::unzip`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.unzip) + +`FromIterator` is for creating a new collection containing items from an +iterator, and `Extend` is for adding items from an iterator onto an existing +collection. + +### Examples from the standard library + +- [`Vec`] implements both `FromIterator` and `Extend`. + +[`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-COMMON-TRAITS.md b/ai-skill/skills/rust-guidelines/rules/C-COMMON-TRAITS.md new file mode 100644 index 0000000..cca2470 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-COMMON-TRAITS.md @@ -0,0 +1,35 @@ +## Types eagerly implement common traits (C-COMMON-TRAITS) + +Rust's trait system does not allow _orphans_: roughly, every `impl` must live +either in the crate that defines the trait or the implementing type. +Consequently, crates that define new types should eagerly implement all +applicable, common traits. + +To see why, consider the following situation: + +* Crate `std` defines trait `Display`. +* Crate `url` defines type `Url`, without implementing `Display`. +* Crate `webapp` imports from both `std` and `url`, + +There is no way for `webapp` to add `Display` to `Url`, since it defines +neither. (Note: the newtype pattern can provide an efficient, but inconvenient +workaround.) + +The most important common traits to implement from `std` are: + +- [`Copy`](https://doc.rust-lang.org/std/marker/trait.Copy.html) +- [`Clone`](https://doc.rust-lang.org/std/clone/trait.Clone.html) +- [`Eq`](https://doc.rust-lang.org/std/cmp/trait.Eq.html) +- [`PartialEq`](https://doc.rust-lang.org/std/cmp/trait.PartialEq.html) +- [`Ord`](https://doc.rust-lang.org/std/cmp/trait.Ord.html) +- [`PartialOrd`](https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html) +- [`Hash`](https://doc.rust-lang.org/std/hash/trait.Hash.html) +- [`Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html) +- [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html) +- [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) + +Note that it is common and expected for types to implement both +`Default` and an empty `new` constructor. `new` is the constructor +convention in Rust, and users expect it to exist, so if it is +reasonable for the basic constructor to take no arguments, then it +should, even if it is functionally identical to `default`. diff --git a/ai-skill/skills/rust-guidelines/rules/C-CONV-SPECIFIC.md b/ai-skill/skills/rust-guidelines/rules/C-CONV-SPECIFIC.md new file mode 100644 index 0000000..5007b21 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CONV-SPECIFIC.md @@ -0,0 +1,20 @@ +## Conversions live on the most specific type involved (C-CONV-SPECIFIC) + +When in doubt, prefer `to_`/`as_`/`into_` to `from_`, because they are more +ergonomic to use (and can be chained with other methods). + +For many conversions between two types, one of the types is clearly more +"specific": it provides some additional invariant or interpretation that is not +present in the other type. For example, [`str`] is more specific than `&[u8]`, +since it is a UTF-8 encoded sequence of bytes. + +[`str`]: https://doc.rust-lang.org/std/primitive.str.html + +Conversions should live with the more specific of the involved types. Thus, +`str` provides both the [`as_bytes`] method and the [`from_utf8`] constructor +for converting to and from `&[u8]` values. Besides being intuitive, this +convention avoids polluting concrete types like `&[u8]` with endless conversion +methods. + +[`as_bytes`]: https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes +[`from_utf8`]: https://doc.rust-lang.org/std/str/fn.from_utf8.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-CONV-TRAITS.md b/ai-skill/skills/rust-guidelines/rules/C-CONV-TRAITS.md new file mode 100644 index 0000000..5eef8e8 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CONV-TRAITS.md @@ -0,0 +1,30 @@ +## Conversions use the standard traits `From`, `AsRef`, `AsMut` (C-CONV-TRAITS) + +The following conversion traits should be implemented where it makes sense: + +- [`From`](https://doc.rust-lang.org/std/convert/trait.From.html) +- [`TryFrom`](https://doc.rust-lang.org/std/convert/trait.TryFrom.html) +- [`AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) +- [`AsMut`](https://doc.rust-lang.org/std/convert/trait.AsMut.html) + +The following conversion traits should never be implemented: + +- [`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) +- [`TryInto`](https://doc.rust-lang.org/std/convert/trait.TryInto.html) + +These traits have a blanket impl based on `From` and `TryFrom`. Implement those +instead. + +### Examples from the standard library + +- `From` is implemented for `u32` because a smaller integer can always be + converted to a bigger integer. +- `From` is *not* implemented for `u16` because the conversion may not be + possible if the integer is too big. +- `TryFrom` is implemented for `u16` and returns an error if the integer is + too big to fit in `u16`. +- [`From`] is implemented for [`IpAddr`], which is a type that can + represent both v4 and v6 IP addresses. + +[`From`]: https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html +[`IpAddr`]: https://doc.rust-lang.org/std/net/enum.IpAddr.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-CONV.md b/ai-skill/skills/rust-guidelines/rules/C-CONV.md new file mode 100644 index 0000000..e1f874a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CONV.md @@ -0,0 +1,77 @@ +## Ad-hoc conversions follow `as_`, `to_`, `into_` conventions (C-CONV) + +Conversions should be provided as methods, with names prefixed as follows: + +| Prefix | Cost | Ownership | +| ------ | ---- | --------- | +| `as_` | Free | borrowed -\> borrowed | +| `to_` | Expensive | borrowed -\> borrowed; borrowed -\> owned (non-Copy types); owned -\> owned (Copy types) | +| `into_` | Variable | owned -\> owned (non-Copy types) | + +For example: + +- [`str::as_bytes()`] gives a view of a `str` as a slice of UTF-8 bytes, which + is free. The input is a borrowed `&str` and the output is a borrowed `&[u8]`. +- [`Path::to_str`] performs an expensive UTF-8 check on the bytes of an + operating system path. The input and output are both borrowed. It would not be + correct to call this `as_str` because this method has nontrivial cost at + runtime. +- [`str::to_lowercase()`] produces the Unicode-correct lowercase equivalent of a + `str`, which involves iterating through characters of the string and may + require memory allocation. The input is a borrowed `&str` and the output is an + owned `String`. +- [`f64::to_radians()`] converts a floating point quantity from degrees to + radians. The input is `f64`. Passing a reference `&f64` is not warranted + because `f64` is cheap to copy. Calling the function `into_radians` would be + misleading because the input is not consumed. +- [`String::into_bytes()`] extracts the underlying `Vec` of a `String`, + which is free. It takes ownership of a `String` and returns an owned + `Vec`. +- [`BufReader::into_inner()`] takes ownership of a buffered reader and extracts + out the underlying reader, which is free. Data in the buffer is discarded. +- [`BufWriter::into_inner()`] takes ownership of a buffered writer and extracts + out the underlying writer, which requires a potentially expensive flush of any + buffered data. + +[`str::as_bytes()`]: https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes +[`Path::to_str`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str +[`str::to_lowercase()`]: https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase +[`f64::to_radians()`]: https://doc.rust-lang.org/std/primitive.f64.html#method.to_radians +[`String::into_bytes()`]: https://doc.rust-lang.org/std/string/struct.String.html#method.into_bytes +[`BufReader::into_inner()`]: https://doc.rust-lang.org/std/io/struct.BufReader.html#method.into_inner +[`BufWriter::into_inner()`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html#method.into_inner + +Conversions prefixed `as_` and `into_` typically _decrease abstraction_, either +exposing a view into the underlying representation (`as`) or deconstructing data +into its underlying representation (`into`). Conversions prefixed `to_`, on the +other hand, typically stay at the same level of abstraction but do some work to +change from one representation to another. + +When a type wraps a single value to associate it with higher-level semantics, +access to the wrapped value should be provided by an `into_inner()` method. This +applies to wrappers that provide buffering like [`BufReader`], encoding or +decoding like [`GzDecoder`], atomic access like [`AtomicBool`], or any similar +semantics. + +[`BufReader`]: https://doc.rust-lang.org/std/io/struct.BufReader.html#method.into_inner +[`GzDecoder`]: https://docs.rs/flate2/0.2.19/flate2/read/struct.GzDecoder.html#method.into_inner +[`AtomicBool`]: https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.into_inner + +If the `mut` qualifier in the name of a conversion method constitutes part of +the return type, it should appear as it would appear in the type. For example +[`Vec::as_mut_slice`] returns a mut slice; it does what it says. This name is +preferred over `as_slice_mut`. + +[`Vec::as_mut_slice`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_slice + +``` +// Return type is a mut slice. +fn as_mut_slice(&mut self) -> &mut [T]; +``` + +##### More examples from the standard library + +- [`Result::as_ref`](https://doc.rust-lang.org/std/result/enum.Result.html#method.as_ref) +- [`RefCell::as_ptr`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.as_ptr) +- [`slice::to_vec`](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec) +- [`Option::into_iter`](https://doc.rust-lang.org/std/option/enum.Option.html#method.into_iter) diff --git a/ai-skill/skills/rust-guidelines/rules/C-CRATE-DOC.md b/ai-skill/skills/rust-guidelines/rules/C-CRATE-DOC.md new file mode 100644 index 0000000..09a313f --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CRATE-DOC.md @@ -0,0 +1,5 @@ +## Crate level docs are thorough and include examples (C-CRATE-DOC) + +See [RFC 1687]. + +[RFC 1687]: https://github.com/rust-lang/rfcs/pull/1687 diff --git a/ai-skill/skills/rust-guidelines/rules/C-CTOR.md b/ai-skill/skills/rust-guidelines/rules/C-CTOR.md new file mode 100644 index 0000000..1b6c60d --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CTOR.md @@ -0,0 +1,85 @@ +## Constructors are static, inherent methods (C-CTOR) + +In Rust, "constructors" are just a convention. There are a variety of +conventions around constructor naming, and the distinctions are often +subtle. + +A constructor in its most basic form is a `new` method with no arguments. + +``` +impl Example { + pub fn new() -> Example { /* ... */ } +} +``` + +Constructors are static (no `self`) inherent methods for the type that they +construct. Combined with the practice of fully importing type names, this +convention leads to informative but concise construction: + +``` +use example::Example; + +// Construct a new Example. +let ex = Example::new(); +``` + +The name `new` should generally be used for the primary method of instantiating +a type. Sometimes it takes no arguments, as in the examples above. Sometimes it +does take arguments, like [`Box::new`] which is passed the value to place in the +`Box`. + +Some types' constructors, most notably I/O resource types, use distinct naming +conventions for their constructors, as in [`File::open`], [`Mmap::open`], +[`TcpStream::connect`], and [`UdpSocket::bind`]. In these cases names are chosen +as appropriate for the domain. + +Often there are multiple ways to construct a type. It's common in these cases +for secondary constructors to be suffixed `_with_foo`, as in +[`Mmap::open_with_offset`]. If your type has a multiplicity of construction +options though, consider the builder pattern ([C-BUILDER]) instead. + +Some constructors are "conversion constructors", methods that create a new type +from an existing value of a different type. These typically have names beginning +with `from_` as in [`std::io::Error::from_raw_os_error`]. Note also though the +`From` trait ([C-CONV-TRAITS]), which is quite similar. There are three +distinctions between a `from_`-prefixed conversion constructor and a `From` +impl. + +- A `from_` constructor can be unsafe; a `From` impl cannot. One example of this + is [`Box::from_raw`]. +- A `from_` constructor can accept additional arguments to disambiguate the + meaning of the source data, as in [`u64::from_str_radix`]. +- A `From` impl is only appropriate when the source data type is sufficient to + determine the encoding of the output data type. When the input is just a bag + of bits like in [`u64::from_be`] or [`String::from_utf8`], the conversion + constructor name is able to identify their meaning. + +[`Box::from_raw`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw +[`u64::from_str_radix`]: https://doc.rust-lang.org/std/primitive.u64.html#method.from_str_radix +[`u64::from_be`]: https://doc.rust-lang.org/std/primitive.u64.html#method.from_be +[`String::from_utf8`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8 + +Note that it is common and expected for types to implement both `Default` and a +`new` constructor. For types that have both, they should have the same behavior. +Either one may be implemented in terms of the other. + +[C-BUILDER]: C-BUILDER.md +[C-CONV-TRAITS]: C-CONV-TRAITS.md + +### Examples from the standard library + +- [`std::io::Error::new`] is the commonly used constructor for an IO error. +- [`std::io::Error::from_raw_os_error`] is a conversion constructor + based on an error code received from the operating system. +- [`Box::new`] creates a new container type, taking a single argument. +- [`File::open`] opens a file resource. +- [`Mmap::open_with_offset`] opens a memory-mapped file, with additional options. + +[`File::open`]: https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.open +[`Mmap::open`]: https://docs.rs/memmap/0.5.2/memmap/struct.Mmap.html#method.open +[`Mmap::open_with_offset`]: https://docs.rs/memmap/0.5.2/memmap/struct.Mmap.html#method.open_with_offset +[`TcpStream::connect`]: https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.connect +[`UdpSocket::bind`]: https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html#method.bind +[`std::io::Error::new`]: https://doc.rust-lang.org/std/io/struct.Error.html#method.new +[`std::io::Error::from_raw_os_error`]: https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error +[`Box::new`]: https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new diff --git a/ai-skill/skills/rust-guidelines/rules/C-CUSTOM-TYPE.md b/ai-skill/skills/rust-guidelines/rules/C-CUSTOM-TYPE.md new file mode 100644 index 0000000..7ef4da6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-CUSTOM-TYPE.md @@ -0,0 +1,28 @@ +## Arguments convey meaning through types, not `bool` or `Option` (C-CUSTOM-TYPE) + +Prefer + +``` +let w = Widget::new(Small, Round) +``` + +over + +``` +let w = Widget::new(true, false) +``` + +Core types like `bool`, `u8` and `Option` have many possible interpretations. + +Use a deliberate type (whether enum, struct, or tuple) to convey interpretation +and invariants. In the above example, it is not immediately clear what `true` +and `false` are conveying without looking up the argument names, but `Small` and +`Round` are more suggestive. + +Using custom types makes it easier to expand the options later on, for example +by adding an `ExtraLarge` variant. + +See the newtype pattern ([C-NEWTYPE]) for a no-cost way to wrap existing types +with a distinguished name. + +[C-NEWTYPE]: C-NEWTYPE.md diff --git a/ai-skill/skills/rust-guidelines/rules/C-DEBUG-NONEMPTY.md b/ai-skill/skills/rust-guidelines/rules/C-DEBUG-NONEMPTY.md new file mode 100644 index 0000000..439e894 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-DEBUG-NONEMPTY.md @@ -0,0 +1,12 @@ +## `Debug` representation is never empty (C-DEBUG-NONEMPTY) + +Even for conceptually empty values, the `Debug` representation should never be +empty. + +``` +let empty_str = ""; +assert_eq!(format!("{:?}", empty_str), "\"\""); + +let empty_vec = Vec::::new(); +assert_eq!(format!("{:?}", empty_vec), "[]"); +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-DEBUG.md b/ai-skill/skills/rust-guidelines/rules/C-DEBUG.md new file mode 100644 index 0000000..4269869 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-DEBUG.md @@ -0,0 +1,3 @@ +## All public types implement `Debug` (C-DEBUG) + +If there are exceptions, they are rare. diff --git a/ai-skill/skills/rust-guidelines/rules/C-DEREF.md b/ai-skill/skills/rust-guidelines/rules/C-DEREF.md new file mode 100644 index 0000000..bd12003 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-DEREF.md @@ -0,0 +1,17 @@ +## Only smart pointers implement `Deref` and `DerefMut` (C-DEREF) + +The `Deref` traits are used implicitly by the compiler in many circumstances, +and interact with method resolution. The relevant rules are designed +specifically to accommodate smart pointers, and so the traits should be used +only for that purpose. + +### Examples from the standard library + +- [`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) +- [`String`](https://doc.rust-lang.org/std/string/struct.String.html) is a smart + pointer to [`str`](https://doc.rust-lang.org/std/primitive.str.html) +- [`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) +- [`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) +- [`Cow<'a, T>`](https://doc.rust-lang.org/std/borrow/enum.Cow.html) + +[`str`]: https://doc.rust-lang.org/std/primitive.str.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-DTOR-BLOCK.md b/ai-skill/skills/rust-guidelines/rules/C-DTOR-BLOCK.md new file mode 100644 index 0000000..f348272 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-DTOR-BLOCK.md @@ -0,0 +1,5 @@ +## Destructors that may block have alternatives (C-DTOR-BLOCK) + +Similarly, destructors should not invoke blocking operations, which can make +debugging much more difficult. Again, consider providing a separate method for +preparing for an infallible, nonblocking teardown. diff --git a/ai-skill/skills/rust-guidelines/rules/C-DTOR-FAIL.md b/ai-skill/skills/rust-guidelines/rules/C-DTOR-FAIL.md new file mode 100644 index 0000000..af8e9f3 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-DTOR-FAIL.md @@ -0,0 +1,9 @@ +## Destructors never fail (C-DTOR-FAIL) + +Destructors are executed while panicking, and in that context a failing +destructor causes the program to abort. + +Instead of failing in a destructor, provide a separate method for checking for +clean teardown, e.g. a `close` method, that returns a `Result` to signal +problems. If that `close` method is not called, the `Drop` implementation +should do the teardown and ignore or log/trace any errors it produces. diff --git a/ai-skill/skills/rust-guidelines/rules/C-EVOCATIVE.md b/ai-skill/skills/rust-guidelines/rules/C-EVOCATIVE.md new file mode 100644 index 0000000..dd33572 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-EVOCATIVE.md @@ -0,0 +1,60 @@ +## Input syntax is evocative of the output (C-EVOCATIVE) + +Rust macros let you dream up practically whatever input syntax you want. Aim to +keep input syntax familiar and cohesive with the rest of your users' code by +mirroring existing Rust syntax where possible. Pay attention to the choice and +placement of keywords and punctuation. + +A good guide is to use syntax, especially keywords and punctuation, that is +similar to what will be produced in the output of the macro. + +For example if your macro declares a struct with a particular name given in the +input, preface the name with the keyword `struct` to signal to readers that a +struct is being declared with the given name. + +``` +// Prefer this... +bitflags! { + struct S: u32 { /* ... */ } +} + +// ...over no keyword... +bitflags! { + S: u32 { /* ... */ } +} + +// ...or some ad-hoc word. +bitflags! { + flags S: u32 { /* ... */ } +} +``` + +Another example is semicolons vs commas. Constants in Rust are followed by +semicolons so if your macro declares a chain of constants, they should likely be +followed by semicolons even if the syntax is otherwise slightly different from +Rust's. + +``` +// Ordinary constants use semicolons. +const A: u32 = 0b000001; +const B: u32 = 0b000010; + +// So prefer this... +bitflags! { + struct S: u32 { + const C = 0b000100; + const D = 0b001000; + } +} + +// ...over this. +bitflags! { + struct S: u32 { + const E = 0b010000, + const F = 0b100000, + } +} +``` + +Macros are so diverse that these specific examples won't be relevant, but think +about how to apply the same principles to your situation. diff --git a/ai-skill/skills/rust-guidelines/rules/C-EXAMPLE.md b/ai-skill/skills/rust-guidelines/rules/C-EXAMPLE.md new file mode 100644 index 0000000..2d7c557 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-EXAMPLE.md @@ -0,0 +1,25 @@ +## All items have a rustdoc example (C-EXAMPLE) + +Every public module, trait, struct, enum, function, method, macro, and type +definition should have an example that exercises the functionality. + +This guideline should be applied within reason. + +A link to an applicable example on another item may be sufficient. For example +if exactly one function uses a particular type, it may be appropriate to write a +single example on either the function or the type and link to it from the other. + +The purpose of an example is not always to show *how to use* the item. Readers +can be expected to understand how to invoke functions, match on enums, and other +fundamental tasks. Rather, an example is often intended to show *why someone +would want to use* the item. + +``` +// This would be a poor example of using clone(). It mechanically shows *how* to +// call clone(), but does nothing to show *why* somebody would want this. +fn main() { + let hello = "hello"; + + hello.clone(); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-FAILURE.md b/ai-skill/skills/rust-guidelines/rules/C-FAILURE.md new file mode 100644 index 0000000..5c08c4b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-FAILURE.md @@ -0,0 +1,78 @@ +## Function docs include error, panic, and safety considerations (C-FAILURE) + +Error conditions should be documented in an "Errors" section. This applies to +trait methods as well -- trait methods for which the implementation is allowed +or expected to return an error should be documented with an "Errors" section. + +For example in the standard library, Some implementations of the +[`std::io::Read::read`] trait method may return an error. + +[`std::io::Read::read`]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read + +``` +/// Pull some bytes from this source into the specified buffer, returning +/// how many bytes were read. +/// +/// ... lots more info ... +/// +/// # Errors +/// +/// If this function encounters any form of I/O or other error, an error +/// variant will be returned. If an error is returned then it must be +/// guaranteed that no bytes were read. +``` + +Panic conditions should be documented in a "Panics" section. This applies to +trait methods as well -- traits methods for which the implementation is allowed +or expected to panic should be documented with a "Panics" section. + +In the standard library the [`Vec::insert`] method may panic. + +[`Vec::insert`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert + +``` +/// Inserts an element at position `index` within the vector, shifting all +/// elements after it to the right. +/// +/// # Panics +/// +/// Panics if `index` is out of bounds. +``` + +It is not necessary to document all conceivable panic cases, especially if the +panic occurs in logic provided by the caller. For example documenting the +`Display` panic in the following code seems excessive. But when in doubt, err on +the side of documenting more panic cases. + +``` +/// # Panics +/// +/// This function panics if `T`'s implementation of `Display` panics. +pub fn print(t: T) { + println!("{}", t.to_string()); +} +``` + +Unsafe functions should be documented with a "Safety" section that explains all +invariants that the caller is responsible for upholding to use the function +correctly. + +The unsafe [`std::ptr::read`] requires the following of the caller. + +[`std::ptr::read`]: https://doc.rust-lang.org/std/ptr/fn.read.html + +``` +/// Reads the value from `src` without moving it. This leaves the +/// memory in `src` unchanged. +/// +/// # Safety +/// +/// Beyond accepting a raw pointer, this is unsafe because it semantically +/// moves the value out of `src` without preventing further usage of `src`. +/// If `T` is not `Copy`, then care must be taken to ensure that the value at +/// `src` is not used before the data is overwritten again (e.g. with `write`, +/// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use +/// because it will attempt to drop the value previously at `*src`. +/// +/// The pointer must be aligned; use `read_unaligned` if that is not the case. +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-FEATURE.md b/ai-skill/skills/rust-guidelines/rules/C-FEATURE.md new file mode 100644 index 0000000..43e1c84 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-FEATURE.md @@ -0,0 +1,51 @@ +## Feature names are free of placeholder words (C-FEATURE) + +Do not include words in the name of a [Cargo feature] that convey zero meaning, +as in `use-abc` or `with-abc`. Name the feature `abc` directly. + +[Cargo feature]: http://doc.crates.io/manifest.html#the-features-section + +This arises most commonly for crates that have an optional dependency on the +Rust standard library. The canonical way to do this correctly is: + +```toml +# In Cargo.toml + +[features] +default = ["std"] +std = [] +``` + +``` +// In lib.rs +#![no_std] + +#[cfg(feature = "std")] +extern crate std; +``` + +Do not call the feature `use-std` or `with-std` or any creative name that is not +`std`. This naming convention aligns with the naming of implicit features +inferred by Cargo for optional dependencies. Consider crate `x` with optional +dependencies on Serde and on the Rust standard library: + +```toml +[package] +name = "x" +version = "0.1.0" + +[features] +std = ["serde/std"] + +[dependencies] +serde = { version = "1.0", optional = true } +``` + +When we depend on `x`, we can enable the optional Serde dependency with +`features = ["serde"]`. Similarly we can enable the optional standard library +dependency with `features = ["std"]`. The implicit feature inferred by Cargo for +the optional dependency is called `serde`, not `use-serde` or `with-serde`, so +we like for explicit features to behave the same way. + +As a related note, Cargo requires that features are additive so a feature named +negatively like `no-abc` is practically never correct. diff --git a/ai-skill/skills/rust-guidelines/rules/C-GENERIC.md b/ai-skill/skills/rust-guidelines/rules/C-GENERIC.md new file mode 100644 index 0000000..5a59a6a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-GENERIC.md @@ -0,0 +1,82 @@ +## Functions minimize assumptions about parameters by using generics (C-GENERIC) + +The fewer assumptions a function makes about its inputs, the more widely usable +it becomes. + +Prefer + +``` +fn foo>(iter: I) { /* ... */ } +``` + +over any of + +``` +fn foo(c: &[i64]) { /* ... */ } +fn foo(c: &Vec) { /* ... */ } +fn foo(c: &SomeOtherCollection) { /* ... */ } +``` + +if the function only needs to iterate over the data. + +More generally, consider using generics to pinpoint the assumptions a function +needs to make about its arguments. + +### Advantages of generics + +* _Reusability_. Generic functions can be applied to an open-ended collection of + types, while giving a clear contract for the functionality those types must + provide. + +* _Static dispatch and optimization_. Each use of a generic function is + specialized ("monomorphized") to the particular types implementing the trait + bounds, which means that (1) invocations of trait methods are static, direct + calls to the implementation and (2) the compiler can inline and otherwise + optimize these calls. + +* _Inline layout_. If a `struct` and `enum` type is generic over some type + parameter `T`, values of type `T` will be laid out inline in the + `struct`/`enum`, without any indirection. + +* _Inference_. Since the type parameters to generic functions can usually be + inferred, generic functions can help cut down on verbosity in code where + explicit conversions or other method calls would usually be necessary. + +* _Precise types_. Because generics give a _name_ to the specific type + implementing a trait, it is possible to be precise about places where that + exact type is required or produced. For example, a function + + ``` + fn binary(x: T, y: T) -> T + ``` + + is guaranteed to consume and produce elements of exactly the same type `T`; it + cannot be invoked with parameters of different types that both implement + `Trait`. + +### Disadvantages of generics + +* _Code size_. Specializing generic functions means that the function body is + duplicated. The increase in code size must be weighed against the performance + benefits of static dispatch. + +* _Homogeneous types_. This is the other side of the "precise types" coin: if + `T` is a type parameter, it stands for a _single_ actual type. So for example + a `Vec` contains elements of a single concrete type (and, indeed, the + vector representation is specialized to lay these out in line). Sometimes + heterogeneous collections are useful; see [trait objects][C-OBJECT]. + +* _Signature verbosity_. Heavy use of generics can make it more difficult to + read and understand a function's signature. + +[C-OBJECT]: C-OBJECT.md + +### Examples from the standard library + +- [`std::fs::File::open`] takes an argument of generic type `AsRef`. This + allows files to be opened conveniently from a string literal `"f.txt"`, a + [`Path`], an [`OsString`], and a few other types. + +[`std::fs::File::open`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.open +[`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html +[`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-GETTER.md b/ai-skill/skills/rust-guidelines/rules/C-GETTER.md new file mode 100644 index 0000000..1f6e39d --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-GETTER.md @@ -0,0 +1,58 @@ +## Getter names follow Rust convention (C-GETTER) + +With a few exceptions, the `get_` prefix is not used for getters in Rust code. + +``` +pub struct S { + first: First, + second: Second, +} + +impl S { + // Not get_first. + pub fn first(&self) -> &First { + &self.first + } + + // Not get_first_mut, get_mut_first, or mut_first. + pub fn first_mut(&mut self) -> &mut First { + &mut self.first + } +} +``` + +The `get` naming is used only when there is a single and obvious thing that +could reasonably be gotten by a getter. For example [`Cell::get`] accesses the +content of a `Cell`. + +[`Cell::get`]: https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get + +For getters that do runtime validation such as bounds checking, consider adding +unsafe `_unchecked` variants. Typically those will have the following +signatures. + +``` +fn get(&self, index: K) -> Option<&V>; +fn get_mut(&mut self, index: K) -> Option<&mut V>; +unsafe fn get_unchecked(&self, index: K) -> &V; +unsafe fn get_unchecked_mut(&mut self, index: K) -> &mut V; +``` + +The difference between getters and conversions ([C-CONV](C-CONV.md)) can be subtle +and is not always clear-cut. For example [`TempDir::path`] can be understood as +a getter for the filesystem path of the temporary directory, while +[`TempDir::into_path`] is a conversion that transfers responsibility for +deleting the temporary directory to the caller. Since `path` is a getter, it +would not be correct to call it `get_path` or `as_path`. + +[`TempDir::path`]: https://docs.rs/tempdir/0.3.5/tempdir/struct.TempDir.html#method.path +[`TempDir::into_path`]: https://docs.rs/tempdir/0.3.5/tempdir/struct.TempDir.html#method.into_path + +### Examples from the standard library + +- [`std::io::Cursor::get_mut`](https://doc.rust-lang.org/std/io/struct.Cursor.html#method.get_mut) +- [`std::pin::Pin::get_mut`](https://doc.rust-lang.org/std/pin/struct.Pin.html#method.get_mut) +- [`std::sync::PoisonError::get_mut`](https://doc.rust-lang.org/std/sync/struct.PoisonError.html#method.get_mut) +- [`std::sync::atomic::AtomicBool::get_mut`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.get_mut) +- [`std::collections::hash_map::OccupiedEntry::get_mut`](https://doc.rust-lang.org/std/collections/hash_map/struct.OccupiedEntry.html#method.get_mut) +- [`<[T]>::get_unchecked`](https://doc.rust-lang.org/std/primitive.slice.html#method.get_unchecked) diff --git a/ai-skill/skills/rust-guidelines/rules/C-GOOD-ERR.md b/ai-skill/skills/rust-guidelines/rules/C-GOOD-ERR.md new file mode 100644 index 0000000..88e3b61 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-GOOD-ERR.md @@ -0,0 +1,94 @@ +## Error types are meaningful and well-behaved (C-GOOD-ERR) + +An error type is any type `E` used in a `Result` returned by any public +function of your crate. Error types should always implement the +[`std::error::Error`] trait which is the mechanism by which error handling +libraries like [`error-chain`] abstract over different types of errors, and +which allows the error to be used as the [`source()`] of another error. + +[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html +[`error-chain`]: https://docs.rs/error-chain +[`source()`]: https://doc.rust-lang.org/std/error/trait.Error.html#method.source + +Additionally, error types should implement the [`Send`] and [`Sync`] traits. An +error that is not `Send` cannot be returned by a thread run with +[`thread::spawn`]. An error that is not `Sync` cannot be passed across threads +using an [`Arc`]. These are common requirements for basic error handling in a +multithreaded application. + +[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +[`thread::spawn`]: https://doc.rust-lang.org/std/thread/fn.spawn.html +[`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html + +`Send` and `Sync` are also important for being able to package a custom error +into an IO error using [`std::io::Error::new`], which requires a trait bound of +`Error + Send + Sync`. + +[`std::io::Error::new`]: https://doc.rust-lang.org/std/io/struct.Error.html#method.new + +One place to be vigilant about this guideline is in functions that return Error +trait objects, for example [`reqwest::Error::get_ref`]. Typically `Error + +Send + Sync + 'static` will be the most useful for callers. The addition of +`'static` allows the trait object to be used with [`Error::downcast_ref`]. + +[`reqwest::Error::get_ref`]: https://docs.rs/reqwest/0.7.2/reqwest/struct.Error.html#method.get_ref +[`Error::downcast_ref`]: https://doc.rust-lang.org/std/error/trait.Error.html#method.downcast_ref-2 + +Never use `()` as an error type, even where there is no useful additional +information for the error to carry. + +- `()` does not implement `Error` so it cannot be used with error handling + libraries like `error-chain`. +- `()` does not implement `Display` so a user would need to write an error + message of their own if they want to fail because of the error. +- `()` has an unhelpful `Debug` representation for users that decide to + `unwrap()` the error. +- It would not be semantically meaningful for a downstream library to implement + `From<()>` for their error type, so `()` as an error type cannot be used with + the `?` operator. + +Instead, define a meaningful error type specific to your crate or to the +individual function. Provide appropriate `Error` and `Display` impls. If there +is no useful information for the error to carry, it can be implemented as a unit +struct. + +``` +use std::error::Error; +use std::fmt::Display; + +// Instead of this... +fn do_the_thing() -> Result + +// Prefer this... +fn do_the_thing() -> Result + +#[derive(Debug)] +struct DoError; + +impl Display for DoError { /* ... */ } +impl Error for DoError { /* ... */ } +``` + +The error message given by the `Display` representation of an error type should +be lowercase without trailing punctuation, and typically concise. + +[`Error::description()`] should not be implemented. It has been deprecated and users should +always use `Display` instead of `description()` to print the error. + +[`Error::description()`]: https://doc.rust-lang.org/std/error/trait.Error.html#tymethod.description + +### Examples from the standard library + +- [`ParseBoolError`] is returned when failing to parse a bool from a string. + +[`ParseBoolError`]: https://doc.rust-lang.org/std/str/struct.ParseBoolError.html + +### Examples of error messages + +- "unexpected end of file" +- "provided string was not \`true\` or \`false\`" +- "invalid IP address syntax" +- "second time provided was later than self" +- "invalid UTF-8 sequence of {} bytes from index {}" +- "environment variable was not valid unicode: {:?}" diff --git a/ai-skill/skills/rust-guidelines/rules/C-HIDDEN.md b/ai-skill/skills/rust-guidelines/rules/C-HIDDEN.md new file mode 100644 index 0000000..296f6fe --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-HIDDEN.md @@ -0,0 +1,33 @@ +## Rustdoc does not show unhelpful implementation details (C-HIDDEN) + +Rustdoc is supposed to include everything users need to use the crate fully and +nothing more. It is fine to explain relevant implementation details in prose but +they should not be real entries in the documentation. + +Especially be selective about which impls are visible in rustdoc -- all the ones +that users would need for using the crate fully, but no others. In the following +code the rustdoc of `PublicError` by default would show the `From` +impl. We choose to hide it with `#[doc(hidden)]` because users can never have a +`PrivateError` in their code so this impl would never be relevant to them. + +``` +// This error type is returned to users. +pub struct PublicError { /* ... */ } + +// This error type is returned by some private helper functions. +struct PrivateError { /* ... */ } + +// Enable use of `?` operator. +#[doc(hidden)] +impl From for PublicError { + fn from(err: PrivateError) -> PublicError { + /* ... */ + } +} +``` + +[`pub(crate)`] is another great tool for removing implementation details from +the public API. It allows items to be used from outside of their own module but +not outside of the same crate. + +[`pub(crate)`]: https://github.com/rust-lang/rfcs/blob/master/text/1422-pub-restricted.md diff --git a/ai-skill/skills/rust-guidelines/rules/C-INTERMEDIATE.md b/ai-skill/skills/rust-guidelines/rules/C-INTERMEDIATE.md new file mode 100644 index 0000000..11a432b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-INTERMEDIATE.md @@ -0,0 +1,26 @@ +## Functions expose intermediate results to avoid duplicate work (C-INTERMEDIATE) + +Many functions that answer a question also compute interesting related data. If +this data is potentially of interest to the client, consider exposing it in the +API. + +### Examples from the standard library + +- [`Vec::binary_search`] does not return a `bool` of whether the value was + found, nor an `Option` of the index at which the value was maybe found. + Instead it returns information about the index if found, and also the index at + which the value would need to be inserted if not found. + +- [`String::from_utf8`] may fail if the input bytes are not UTF-8. In the error + case it returns an intermediate result that exposes the byte offset up to + which the input was valid UTF-8, as well as handing back ownership of the + input bytes. + +- [`HashMap::insert`] returns an `Option` that returns the preexisting value + for a given key, if any. For cases where the user wants to recover this value + having it returned by the insert operation avoids the user having to do a second + hash table lookup. + +[`Vec::binary_search`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search +[`String::from_utf8`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8 +[`HashMap::insert`]: https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.insert diff --git a/ai-skill/skills/rust-guidelines/rules/C-ITER-TY.md b/ai-skill/skills/rust-guidelines/rules/C-ITER-TY.md new file mode 100644 index 0000000..3954fe8 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-ITER-TY.md @@ -0,0 +1,36 @@ +## Iterator type names match the methods that produce them (C-ITER-TY) + +A method called `into_iter()` should return a type called `IntoIter` and +similarly for all other methods that return iterators. + +This guideline applies chiefly to methods, but often makes sense for functions +as well. For example the [`percent_encode`] function from the `url` crate +returns an iterator type called [`PercentEncode`][PercentEncode-type]. + +[PercentEncode-type]: https://docs.rs/url/1.4.0/url/percent_encoding/struct.PercentEncode.html + +These type names make the most sense when prefixed with their owning module, for +example [`vec::IntoIter`]. + +[`vec::IntoIter`]: https://doc.rust-lang.org/std/vec/struct.IntoIter.html + +### Examples from the standard library + +* [`Vec::iter`] returns [`Iter`][slice::Iter] +* [`Vec::iter_mut`] returns [`IterMut`][slice::IterMut] +* [`Vec::into_iter`] returns [`IntoIter`][vec::IntoIter] +* [`BTreeMap::keys`] returns [`Keys`][btree_map::Keys] +* [`BTreeMap::values`] returns [`Values`][btree_map::Values] + +[`Vec::iter`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter +[slice::Iter]: https://doc.rust-lang.org/std/slice/struct.Iter.html +[`Vec::iter_mut`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter_mut +[slice::IterMut]: https://doc.rust-lang.org/std/slice/struct.IterMut.html +[`Vec::into_iter`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_iter +[vec::IntoIter]: https://doc.rust-lang.org/std/vec/struct.IntoIter.html +[`BTreeMap::keys`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.keys +[btree_map::Keys]: https://doc.rust-lang.org/std/collections/btree_map/struct.Keys.html +[`BTreeMap::values`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.values +[btree_map::Values]: https://doc.rust-lang.org/std/collections/btree_map/struct.Values.html + +[`percent_encode`]: https://docs.rs/url/1.4.0/url/percent_encoding/fn.percent_encode.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-ITER.md b/ai-skill/skills/rust-guidelines/rules/C-ITER.md new file mode 100644 index 0000000..0d6b945 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-ITER.md @@ -0,0 +1,41 @@ +## Methods on collections that produce iterators follow `iter`, `iter_mut`, `into_iter` (C-ITER) + +Per [RFC 199]. + +For a container with elements of type `U`, iterator methods should be named: + +``` +fn iter(&self) -> Iter // Iter implements Iterator +fn iter_mut(&mut self) -> IterMut // IterMut implements Iterator +fn into_iter(self) -> IntoIter // IntoIter implements Iterator +``` + +This guideline applies to data structures that are conceptually homogeneous +collections. As a counterexample, the `str` type is slice of bytes that are +guaranteed to be valid UTF-8. This is conceptually more nuanced than a +homogeneous collection so rather than providing the +`iter`/`iter_mut`/`into_iter` group of iterator methods, it provides +[`str::bytes`] to iterate as bytes and [`str::chars`] to iterate as chars. + +[`str::bytes`]: https://doc.rust-lang.org/std/primitive.str.html#method.bytes +[`str::chars`]: https://doc.rust-lang.org/std/primitive.str.html#method.chars + +This guideline applies to methods only, not functions. For example +[`percent_encode`] from the `url` crate returns an iterator over percent-encoded +string fragments. There would be no clarity to be had by using an +`iter`/`iter_mut`/`into_iter` convention. + +[`percent_encode`]: https://docs.rs/url/1.4.0/url/percent_encoding/fn.percent_encode.html +[RFC 199]: https://github.com/rust-lang/rfcs/blob/master/text/0199-ownership-variants.md + +### Examples from the standard library + +- [`Vec::iter`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter) +- [`Vec::iter_mut`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter_mut) +- [`Vec::into_iter`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_iter) +- [`BTreeMap::iter`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.iter) +- [`BTreeMap::iter_mut`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.iter_mut) + +[`Vec::iter`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter +[`Vec::iter_mut`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter_mut +[`Vec::into_iter`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_iter diff --git a/ai-skill/skills/rust-guidelines/rules/C-LINK.md b/ai-skill/skills/rust-guidelines/rules/C-LINK.md new file mode 100644 index 0000000..ac4dda4 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-LINK.md @@ -0,0 +1,31 @@ +## Prose contains hyperlinks to relevant things (C-LINK) + +Regular links can be added inline with the usual markdown syntax of +`[text](https://rust-lang.github.io/api-guidelines/url)`. Links to other types can be added by marking them with +``[`text`]``, then adding the link target in a new line at the end of +the docstring with ``[`text`]: ``, where `` is +described below. + +Link targets to methods within the same type usually look like this: + +```md +[`serialize_struct`]: #method.serialize_struct +``` + +Link targets to other types usually look like this: + +```md +[`Deserialize`]: trait.Deserialize.html +``` + +Link targets may also point to a parent or child module: + +```md +[`Value`]: ../enum.Value.html +[`DeserializeOwned`]: de/trait.DeserializeOwned.html +``` + +This guideline is officially recommended by RFC 1574 under the heading ["Link +all the things"]. + +["Link all the things"]: https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#link-all-the-things diff --git a/ai-skill/skills/rust-guidelines/rules/C-MACRO-ATTR.md b/ai-skill/skills/rust-guidelines/rules/C-MACRO-ATTR.md new file mode 100644 index 0000000..5cc7ae3 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-MACRO-ATTR.md @@ -0,0 +1,29 @@ +## Item macros compose well with attributes (C-MACRO-ATTR) + +Macros that produce more than one output item should support adding attributes +to any one of those items. One common use case would be putting individual items +behind a cfg. + +``` +bitflags! { + struct Flags: u8 { + #[cfg(windows)] + const ControlCenter = 0b001; + #[cfg(unix)] + const Terminal = 0b010; + } +} +``` + +Macros that produce a struct or enum as output should support attributes so that +the output can be used with derive. + +``` +bitflags! { + #[derive(Default, Serialize)] + struct Flags: u8 { + const ControlCenter = 0b001; + const Terminal = 0b010; + } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-MACRO-TY.md b/ai-skill/skills/rust-guidelines/rules/C-MACRO-TY.md new file mode 100644 index 0000000..ca27a52 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-MACRO-TY.md @@ -0,0 +1,30 @@ +## Type fragments are flexible (C-MACRO-TY) + +If your macro accepts a type fragment like `$t:ty` in the input, it should be +usable with all of the following: + +- Primitives: `u8`, `&str` +- Relative paths: `m::Data` +- Absolute paths: `::base::Data` +- Upward relative paths: `super::Data` +- Generics: `Vec` + +As a simple example of how things can go wrong, this macro works great with +primitives and absolute paths but fails with relative paths. + +``` +macro_rules! broken { + ($m:ident => $t:ty) => { + pub mod $m { + pub struct Wrapper($t); + } + } +} + +broken!(a => u8); // okay + +broken!(b => ::std::marker::PhantomData<()>); // okay + +struct S; +broken!(c => S); // fails to compile +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-MACRO-VIS.md b/ai-skill/skills/rust-guidelines/rules/C-MACRO-VIS.md new file mode 100644 index 0000000..5842885 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-MACRO-VIS.md @@ -0,0 +1,20 @@ +## Item macros support visibility specifiers (C-MACRO-VIS) + +Follow Rust syntax for visibility of items produced by a macro. Private by +default, public if `pub` is specified. + +``` +bitflags! { + struct PrivateFlags: u8 { + const A = 0b0001; + const B = 0b0010; + } +} + +bitflags! { + pub struct PublicFlags: u8 { + const C = 0b0100; + const D = 0b1000; + } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-METADATA.md b/ai-skill/skills/rust-guidelines/rules/C-METADATA.md new file mode 100644 index 0000000..2c132c8 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-METADATA.md @@ -0,0 +1,28 @@ +## Cargo.toml includes all common metadata (C-METADATA) + +The `[package]` section of `Cargo.toml` should include the following +values: + +- `authors` +- `description` +- `license` +- `repository` +- `keywords` +- `categories` + +In addition, there are two optional metadata fields: + +- `documentation` +- `homepage` + +By default, *crates.io* links to documentation for the crate on [*docs.rs*]. The +`documentation` metadata only needs to be set if the documentation is hosted +somewhere other than *docs.rs*, for example because the crate links against a +shared library that is not available in the build environment of *docs.rs*. + +[*docs.rs*]: https://docs.rs + +The `homepage` metadata should only be set if there is a unique website for the +crate other than the source repository or API documentation. Do not make +`homepage` redundant with either the `documentation` or `repository` values. For +example, serde sets `homepage` to *https://serde.rs*, a dedicated website. diff --git a/ai-skill/skills/rust-guidelines/rules/C-METHOD.md b/ai-skill/skills/rust-guidelines/rules/C-METHOD.md new file mode 100644 index 0000000..4a57e56 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-METHOD.md @@ -0,0 +1,27 @@ +## Functions with a clear receiver are methods (C-METHOD) + +Prefer + +``` +impl Foo { + pub fn frob(&self, w: widget) { /* ... */ } +} +``` + +over + +``` +pub fn frob(foo: &Foo, w: widget) { /* ... */ } +``` + +for any operation that is clearly associated with a particular type. + +Methods have numerous advantages over functions: + +* They do not need to be imported or qualified to be used: all you need is a + value of the appropriate type. +* Their invocation performs autoborrowing (including mutable borrows). +* They make it easy to answer the question "what can I do with a value of type + `T`" (especially when using rustdoc). +* They provide `self` notation, which is more concise and often more clearly + conveys ownership distinctions. diff --git a/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE-HIDE.md b/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE-HIDE.md new file mode 100644 index 0000000..fe882b2 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE-HIDE.md @@ -0,0 +1,60 @@ +## Newtypes encapsulate implementation details (C-NEWTYPE-HIDE) + +A newtype can be used to hide representation details while making precise +promises to the client. + +For example, consider a function `my_transform` that returns a compound iterator +type. + +``` +use std::iter::{Enumerate, Skip}; + +pub fn my_transform(input: I) -> Enumerate> { + input.skip(3).enumerate() +} +``` + +We wish to hide this type from the client, so that the client's view of the +return type is roughly `Iterator`. We can do so using the +newtype pattern: + +``` +use std::iter::{Enumerate, Skip}; + +pub struct MyTransformResult(Enumerate>); + +impl Iterator for MyTransformResult { + type Item = (usize, I::Item); + + fn next(&mut self) -> Option { + self.0.next() + } +} + +pub fn my_transform(input: I) -> MyTransformResult { + MyTransformResult(input.skip(3).enumerate()) +} +``` + +Aside from simplifying the signature, this use of newtypes allows us to promise +less to the client. The client does not know _how_ the result iterator is +constructed or represented, which means the representation can change in the +future without breaking client code. + +Rust 1.26 also introduces the [`impl Trait`][] feature, which is more concise +than the newtype pattern but with some additional trade offs, namely with `impl +Trait` you are limited in what you can express. For example, returning an +iterator that impls `Debug` or `Clone` or some combination of the other iterator +extension traits can be problematic. In summary `impl Trait` as a return type +is probably great for internal APIs and may even be appropriate for public APIs, +but probably not in all cases. See the ["`impl Trait` for returning complex +types with ease"][impl-trait-2] section of the Edition Guide for more details. + +[`impl Trait`]: https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md +[impl-trait-2]: https://rust-lang.github.io/edition-guide/rust-2018/trait-system/impl-trait-for-returning-complex-types-with-ease.html + +``` +pub fn my_transform(input: I) -> impl Iterator { + input.skip(3).enumerate() +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE.md b/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE.md new file mode 100644 index 0000000..9d2d044 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-NEWTYPE.md @@ -0,0 +1,31 @@ +## Newtypes provide static distinctions (C-NEWTYPE) + +Newtypes can statically distinguish between different interpretations of an +underlying type. + +For example, a `f64` value might be used to represent a quantity in miles or in +kilometers. Using newtypes, we can keep track of the intended interpretation: + +``` +struct Miles(pub f64); +struct Kilometers(pub f64); + +impl Miles { + fn to_kilometers(self) -> Kilometers { /* ... */ } +} +impl Kilometers { + fn to_miles(self) -> Miles { /* ... */ } +} +``` + +Once we have separated these two types, we can statically ensure that we do not +confuse them. For example, the function + +``` +fn are_we_there_yet(distance_travelled: Miles) -> bool { /* ... */ } +``` + +cannot accidentally be called with a `Kilometers` value. The compiler will +remind us to perform the conversion, thus averting certain [catastrophic bugs]. + +[catastrophic bugs]: http://en.wikipedia.org/wiki/Mars_Climate_Orbiter diff --git a/ai-skill/skills/rust-guidelines/rules/C-NO-OUT.md b/ai-skill/skills/rust-guidelines/rules/C-NO-OUT.md new file mode 100644 index 0000000..83534c3 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-NO-OUT.md @@ -0,0 +1,26 @@ +## Functions do not take out-parameters (C-NO-OUT) + +Prefer + +``` +fn foo() -> (Bar, Bar) +``` + +over + +``` +fn foo(output: &mut Bar) -> Bar +``` + +for returning multiple `Bar` values. + +Compound return types like tuples and structs are efficiently compiled and do +not require heap allocation. If a function needs to return multiple values, it +should do so via one of these types. + +The primary exception: sometimes a function is meant to modify data that the +caller already owns, for example to re-use a buffer: + +``` +fn read(&mut self, buf: &mut [u8]) -> io::Result +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-NUM-FMT.md b/ai-skill/skills/rust-guidelines/rules/C-NUM-FMT.md new file mode 100644 index 0000000..9b1dc24 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-NUM-FMT.md @@ -0,0 +1,14 @@ +## Binary number types provide `Hex`, `Octal`, `Binary` formatting (C-NUM-FMT) + +- [`std::fmt::UpperHex`](https://doc.rust-lang.org/std/fmt/trait.UpperHex.html) +- [`std::fmt::LowerHex`](https://doc.rust-lang.org/std/fmt/trait.LowerHex.html) +- [`std::fmt::Octal`](https://doc.rust-lang.org/std/fmt/trait.Octal.html) +- [`std::fmt::Binary`](https://doc.rust-lang.org/std/fmt/trait.Binary.html) + +These traits control the representation of a type under the `{:X}`, `{:x}`, +`{:o}`, and `{:b}` format specifiers. + +Implement these traits for any number type on which you would consider doing +bitwise manipulations like `|` or `&`. This is especially appropriate for +bitflag types. Numeric quantity types like `struct Nanoseconds(u64)` probably do +not need these. diff --git a/ai-skill/skills/rust-guidelines/rules/C-OBJECT.md b/ai-skill/skills/rust-guidelines/rules/C-OBJECT.md new file mode 100644 index 0000000..14112f3 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-OBJECT.md @@ -0,0 +1,57 @@ +## Traits are object-safe if they may be useful as a trait object (C-OBJECT) + +Trait objects have some significant limitations: methods invoked through a trait +object cannot use generics, and cannot use `Self` except in receiver position. + +When designing a trait, decide early on whether the trait will be used as an +object or as a bound on generics. + +If a trait is meant to be used as an object, its methods should take and return +trait objects rather than use generics. + +A `where` clause of `Self: Sized` may be used to exclude specific methods from +the trait's object. The following trait is not object-safe due to the generic +method. + +``` +trait MyTrait { + fn object_safe(&self, i: i32); + + fn not_object_safe(&self, t: T); +} +``` + +Adding a requirement of `Self: Sized` to the generic method excludes it from the +trait object and makes the trait object-safe. + +``` +trait MyTrait { + fn object_safe(&self, i: i32); + + fn not_object_safe(&self, t: T) where Self: Sized; +} +``` + +### Advantages of trait objects + +* _Heterogeneity_. When you need it, you really need it. +* _Code size_. Unlike generics, trait objects do not generate specialized + (monomorphized) versions of code, which can greatly reduce code size. + +### Disadvantages of trait objects + +* _No generic methods_. Trait objects cannot currently provide generic methods. +* _Dynamic dispatch and fat pointers_. Trait objects inherently involve + indirection and vtable dispatch, which can carry a performance penalty. +* _No Self_. Except for the method receiver argument, methods on trait objects + cannot use the `Self` type. + +### Examples from the standard library + +- The [`io::Read`] and [`io::Write`] traits are often used as objects. +- The [`Iterator`] trait has several generic methods marked with `where Self: + Sized` to retain the ability to use `Iterator` as an object. + +[`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html +[`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +[`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-OVERLOAD.md b/ai-skill/skills/rust-guidelines/rules/C-OVERLOAD.md new file mode 100644 index 0000000..36f6a1b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-OVERLOAD.md @@ -0,0 +1,9 @@ +## Operator overloads are unsurprising (C-OVERLOAD) + +Operators with built in syntax (`*`, `|`, and so on) can be provided for a type +by implementing the traits in [`std::ops`]. These operators come with strong +expectations: implement `Mul` only for an operation that bears some resemblance +to multiplication (and shares the expected properties, e.g. associativity), and +so on for the other traits. + +[`std::ops`]: https://doc.rust-lang.org/std/ops/index.html#traits diff --git a/ai-skill/skills/rust-guidelines/rules/C-PERMISSIVE.md b/ai-skill/skills/rust-guidelines/rules/C-PERMISSIVE.md new file mode 100644 index 0000000..369dc9a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-PERMISSIVE.md @@ -0,0 +1,67 @@ +## Crate and its dependencies have a permissive license (C-PERMISSIVE) + +The software produced by the Rust project is dual-licensed, under either the +[MIT] or [Apache 2.0] licenses. Crates that simply need the maximum +compatibility with the Rust ecosystem are recommended to do the same, in the +manner described herein. Other options are described below. + +These API guidelines do not provide a detailed explanation of Rust's license, +but there is a small amount said in the [Rust FAQ]. These guidelines are +concerned with matters of interoperability with Rust, and are not comprehensive +over licensing options. + +[MIT]: https://github.com/rust-lang/rust/blob/master/LICENSE-MIT +[Apache 2.0]: https://github.com/rust-lang/rust/blob/master/LICENSE-APACHE +[Rust FAQ]: https://github.com/dtolnay/rust-faq#why-a-dual-mitasl2-license + +To apply the Rust license to your project, define the `license` field in your +`Cargo.toml` as: + +```toml +[package] +name = "..." +version = "..." +authors = ["..."] +license = "MIT OR Apache-2.0" +``` + +Then add the files `LICENSE-APACHE` and `LICENSE-MIT` in the repository root, +containing the text of the licenses (which you can obtain, for instance, from +choosealicense.com, for [Apache-2.0](https://choosealicense.com/licenses/apache-2.0/) +and [MIT](https://choosealicense.com/licenses/mit/)). + +And toward the end of your README.md: + +``` +## License + +Licensed under either of + + * Apache License, Version 2.0 + ([LICENSE-APACHE](LICENSE-APACHE) or ) + * MIT license + ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. +``` + +Besides the dual MIT/Apache-2.0 license, another common licensing approach used +by Rust crate authors is to apply a single permissive license such as MIT or +BSD. This license scheme is also entirely compatible with Rust's, because it +imposes the minimal restrictions of Rust's MIT license. + +Crates that desire perfect license compatibility with Rust are not recommended +to choose only the Apache license. The Apache license, though it is a permissive +license, imposes restrictions beyond the MIT and BSD licenses that can +discourage or prevent their use in some scenarios, so Apache-only software +cannot be used in some situations where most of the Rust runtime stack can. + +The license of a crate's dependencies can affect the restrictions on +distribution of the crate itself, so a permissively-licensed crate should +generally only depend on permissively-licensed crates. diff --git a/ai-skill/skills/rust-guidelines/rules/C-QUESTION-MARK.md b/ai-skill/skills/rust-guidelines/rules/C-QUESTION-MARK.md new file mode 100644 index 0000000..ba851e3 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-QUESTION-MARK.md @@ -0,0 +1,22 @@ +## Examples use `?`, not `try!`, not `unwrap` (C-QUESTION-MARK) + +Like it or not, example code is often copied verbatim by users. Unwrapping an +error should be a conscious decision that the user needs to make. + +A common way of structuring fallible example code is the following. The lines +beginning with `#` are compiled by `cargo test` when building the example but +will not appear in user-visible rustdoc. + +``` +/// ```rust +/// # use std::error::Error; +/// # +/// # fn main() -> Result<(), Box> { +/// your; +/// example?; +/// code; +/// # +/// # Ok(()) +/// # } +/// ``` +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-RELNOTES.md b/ai-skill/skills/rust-guidelines/rules/C-RELNOTES.md new file mode 100644 index 0000000..29d7da2 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-RELNOTES.md @@ -0,0 +1,31 @@ +## Release notes document all significant changes (C-RELNOTES) + +Users of the crate can read the release notes to find a summary of what +changed in each published release of the crate. A link to the release notes, +or the notes themselves, should be included in the crate-level documentation +and/or the repository linked in Cargo.toml. + +Breaking changes (as defined in [RFC 1105]) should be clearly identified in the +release notes. + +If using Git to track the source of a crate, every release published to +*crates.io* should have a corresponding tag identifying the commit that was +published. A similar process should be used for non-Git VCS tools as well. + +```bash +# Tag the current commit +GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0 +git push --tags +``` + +Annotated tags are preferred because some Git commands ignore unannotated tags +if any annotated tags exist. + +[RFC 1105]: https://github.com/rust-lang/rfcs/blob/master/text/1105-api-evolution.md + +### Examples + +- [Serde 1.0.0 release notes](https://github.com/serde-rs/serde/releases/tag/v1.0.0) +- [Serde 0.9.8 release notes](https://github.com/serde-rs/serde/releases/tag/v0.9.8) +- [Serde 0.9.0 release notes](https://github.com/serde-rs/serde/releases/tag/v0.9.0) +- [Diesel change log](https://github.com/diesel-rs/diesel/blob/master/CHANGELOG.md) diff --git a/ai-skill/skills/rust-guidelines/rules/C-RW-VALUE.md b/ai-skill/skills/rust-guidelines/rules/C-RW-VALUE.md new file mode 100644 index 0000000..6b3e519 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-RW-VALUE.md @@ -0,0 +1,31 @@ +## Generic reader/writer functions take `R: Read` and `W: Write` by value (C-RW-VALUE) + +The standard library contains these two impls: + +``` +impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ } + +impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ } +``` + +That means any function that accepts `R: Read` or `W: Write` generic parameters +by value can be called with a mut reference if necessary. + +In the documentation of such functions, briefly remind users that a mut +reference can be passed. New Rust users often struggle with this. They may have +opened a file and want to read multiple pieces of data out of it, but the +function to read one piece consumes the reader by value, so they are stuck. The +solution would be to leverage one of the above impls and pass `&mut f` instead +of `f` as the reader parameter. + +### Examples + +- [`flate2::read::GzDecoder::new`] +- [`flate2::write::GzEncoder::new`] +- [`serde_json::from_reader`] +- [`serde_json::to_writer`] + +[`flate2::read::GzDecoder::new`]: https://docs.rs/flate2/0.2/flate2/read/struct.GzDecoder.html#method.new +[`flate2::write::GzEncoder::new`]: https://docs.rs/flate2/0.2/flate2/write/struct.GzEncoder.html#method.new +[`serde_json::from_reader`]: https://docs.serde.rs/serde_json/fn.from_reader.html +[`serde_json::to_writer`]: https://docs.serde.rs/serde_json/fn.to_writer.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-SEALED.md b/ai-skill/skills/rust-guidelines/rules/C-SEALED.md new file mode 100644 index 0000000..d802b46 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-SEALED.md @@ -0,0 +1,48 @@ +## Sealed traits protect against downstream implementations (C-SEALED) + +Some traits are only meant to be implemented within the crate that defines them. +In such cases, we can retain the ability to make changes to the trait in a +non-breaking way by using the sealed trait pattern. + +``` +/// This trait is sealed and cannot be implemented for types outside this crate. +pub trait TheTrait: private::Sealed { + // Zero or more methods that the user is allowed to call. + fn ...(); + + // Zero or more private methods, not allowed for user to call. + #[doc(hidden)] + fn ...(); +} + +// Implement for some types. +impl TheTrait for usize { + /* ... */ +} + +mod private { + pub trait Sealed {} + + // Implement for those same types, but no others. + impl Sealed for usize {} +} +``` + +The empty private `Sealed` supertrait cannot be named by downstream crates, so +we are guaranteed that implementations of `Sealed` (and therefore `TheTrait`) +only exist in the current crate. We are free to add methods to `TheTrait` in a +non-breaking release even though that would ordinarily be a breaking change for +traits that are not sealed. Also we are free to change the signature of methods +that are not publicly documented. + +Note that removing a public method or changing the signature of a public method +in a sealed trait are still breaking changes. + +To avoid frustrated users trying to implement the trait, it should be documented +in rustdoc that the trait is sealed and not meant to be implemented outside of +the current crate. + +### Examples + +- [`serde_json::value::Index`](https://docs.serde.rs/serde_json/value/trait.Index.html) +- [`byteorder::ByteOrder`](https://docs.rs/byteorder/1.1.0/byteorder/trait.ByteOrder.html) diff --git a/ai-skill/skills/rust-guidelines/rules/C-SEND-SYNC.md b/ai-skill/skills/rust-guidelines/rules/C-SEND-SYNC.md new file mode 100644 index 0000000..95bec38 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-SEND-SYNC.md @@ -0,0 +1,26 @@ +## Types are `Send` and `Sync` where possible (C-SEND-SYNC) + +[`Send`] and [`Sync`] are automatically implemented when the compiler determines +it is appropriate. + +[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html +[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html + +In types that manipulate raw pointers, be vigilant that the `Send` and `Sync` +status of your type accurately reflects its thread safety characteristics. Tests +like the following can help catch unintentional regressions in whether the type +implements `Send` or `Sync`. + +``` +#[test] +fn test_send() { + fn assert_send() {} + assert_send::(); +} + +#[test] +fn test_sync() { + fn assert_sync() {} + assert_sync::(); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-SERDE.md b/ai-skill/skills/rust-guidelines/rules/C-SERDE.md new file mode 100644 index 0000000..4468759 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-SERDE.md @@ -0,0 +1,58 @@ +## Data structures implement Serde's `Serialize`, `Deserialize` (C-SERDE) + +Types that play the role of a data structure should implement [`Serialize`] and +[`Deserialize`]. + +[`Serialize`]: https://docs.serde.rs/serde/trait.Serialize.html +[`Deserialize`]: https://docs.serde.rs/serde/trait.Deserialize.html + +There is a continuum of types between things that are clearly a data structure +and things that are clearly not, with gray area in between. [`LinkedHashMap`] +and [`IpAddr`] are data structures. It would be completely reasonable for +somebody to want to read in a `LinkedHashMap` or `IpAddr` from a JSON file, or +send one over IPC to another process. [`LittleEndian`] is not a data structure. +It is a marker used by the `byteorder` crate to optimize at compile time for +bytes in a particular order, and in fact an instance of `LittleEndian` can never +exist at runtime. So these are clear-cut examples; the #rust or #serde IRC +channels can help assess more ambiguous cases if necessary. + +[`LinkedHashMap`]: https://docs.rs/linked-hash-map/0.4.2/linked_hash_map/struct.LinkedHashMap.html +[`IpAddr`]: https://doc.rust-lang.org/std/net/enum.IpAddr.html +[`LittleEndian`]: https://docs.rs/byteorder/1.0.0/byteorder/enum.LittleEndian.html + +If a crate does not already depend on Serde for other reasons, it may wish to +gate Serde impls behind a Cargo cfg. This way downstream libraries only need to +pay the cost of compiling Serde if they need those impls to exist. + +For consistency with other Serde-based libraries, the name of the Cargo cfg +should be simply `"serde"`. Do not use a different name for the cfg like +`"serde_impls"` or `"serde_serialization"`. + +The canonical implementation looks like this when not using derive: + +```toml +[dependencies] +serde = { version = "1.0", optional = true } +``` + +``` +pub struct T { /* ... */ } + +#[cfg(feature = "serde")] +impl Serialize for T { /* ... */ } + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for T { /* ... */ } +``` + +And when using derive: + +```toml +[dependencies] +serde = { version = "1.0", optional = true, features = ["derive"] } +``` + +``` +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct T { /* ... */ } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-SMART-PTR.md b/ai-skill/skills/rust-guidelines/rules/C-SMART-PTR.md new file mode 100644 index 0000000..bbb4f36 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-SMART-PTR.md @@ -0,0 +1,34 @@ +## Smart pointers do not add inherent methods (C-SMART-PTR) + +For example, this is why the [`Box::into_raw`] function is defined the way it +is. + +[`Box::into_raw`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw + +``` +impl Box where T: ?Sized { + fn into_raw(b: Box) -> *mut T { /* ... */ } +} + +let boxed_str: Box = /* ... */; +let ptr = Box::into_raw(boxed_str); +``` + +If this were defined as an inherent method instead, it would be confusing at the +call site whether the method being called is a method on `Box` or a method on +`T`. + +``` +impl Box where T: ?Sized { + // Do not do this. + fn into_raw(self) -> *mut T { /* ... */ } +} + +let boxed_str: Box = /* ... */; + +// This is a method on str accessed through the smart pointer Deref impl. +boxed_str.chars() + +// This is a method on Box...? +boxed_str.into_raw() +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-STABLE.md b/ai-skill/skills/rust-guidelines/rules/C-STABLE.md new file mode 100644 index 0000000..eed7663 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-STABLE.md @@ -0,0 +1,37 @@ +## Public dependencies of a stable crate are stable (C-STABLE) + +A crate cannot be stable (>=1.0.0) without all of its public dependencies being +stable. + +Public dependencies are crates from which types are used in the public API of +the current crate. + +``` +pub fn do_my_thing(arg: other_crate::TheirThing) { /* ... */ } +``` + +A crate containing this function cannot be stable unless `other_crate` is also +stable. + +Be careful because public dependencies can sneak in at unexpected places. + +``` +pub struct Error { + private: ErrorImpl, +} + +enum ErrorImpl { + Io(io::Error), + // Should be okay even if other_crate isn't + // stable, because ErrorImpl is private. + Dep(other_crate::Error), +} + +// Oh no! This puts other_crate into the public API +// of the current crate. +impl From for Error { + fn from(err: other_crate::Error) -> Self { + Error { private: ErrorImpl::Dep(err) } + } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/C-STRUCT-BOUNDS.md b/ai-skill/skills/rust-guidelines/rules/C-STRUCT-BOUNDS.md new file mode 100644 index 0000000..f7f678c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-STRUCT-BOUNDS.md @@ -0,0 +1,74 @@ +## Data structures do not duplicate derived trait bounds (C-STRUCT-BOUNDS) + +Generic data structures should not use trait bounds that can be derived or do +not otherwise add semantic value. Each trait in the `derive` attribute will be +expanded into a separate `impl` block that only applies to generic arguments +that implement that trait. + +``` +// Prefer this: +#[derive(Clone, Debug, PartialEq)] +struct Good { /* ... */ } + +// Over this: +#[derive(Clone, Debug, PartialEq)] +struct Bad { /* ... */ } +``` + +Duplicating derived traits as bounds on `Bad` is unnecessary and a +backwards-compatibiliity hazard. To illustrate this point, consider deriving +`PartialOrd` on the structures in the previous example: + +``` +// Non-breaking change: +#[derive(Clone, Debug, PartialEq, PartialOrd)] +struct Good { /* ... */ } + +// Breaking change: +#[derive(Clone, Debug, PartialEq, PartialOrd)] +struct Bad { /* ... */ } +``` + +Generally speaking, adding a trait bound to a data structure is a breaking +change because every consumer of that structure will need to start satisfying +the additional bound. Deriving more traits from the standard library using the +`derive` attribute is not a breaking change. + +The following traits should never be used in bounds on data structures: + +- `Clone` +- `PartialEq` +- `PartialOrd` +- `Debug` +- `Display` +- `Default` +- `Error` +- `Serialize` +- `Deserialize` +- `DeserializeOwned` + +There is a grey area around other non-derivable trait bounds that are not +strictly required by the structure definition, like `Read` or `Write`. They may +communicate the intended behavior of the type better in its definition but also +limits future extensibility. Including semantically useful trait bounds on data +structures is still less problematic than including derivable traits as bounds. + +### Exceptions + +There are three exceptions where trait bounds on structures are required: + +1. The data structure refers to an associated type on the trait. +1. The bound is `?Sized`. +1. The data structure has a `Drop` impl that requires trait bounds. +Rust currently requires all trait bounds on the `Drop` impl are also present +on the data structure. + +### Examples from the standard library + +- [`std::borrow::Cow`] refers to an associated type on the `Borrow` trait. +- [`std::boxed::Box`] opts out of the implicit `Sized` bound. +- [`std::io::BufWriter`] requires a trait bound in its `Drop` impl. + +[`std::borrow::Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html +[`std::boxed::Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html +[`std::io::BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html diff --git a/ai-skill/skills/rust-guidelines/rules/C-STRUCT-PRIVATE.md b/ai-skill/skills/rust-guidelines/rules/C-STRUCT-PRIVATE.md new file mode 100644 index 0000000..4ae9189 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-STRUCT-PRIVATE.md @@ -0,0 +1,9 @@ +## Structs have private fields (C-STRUCT-PRIVATE) + +Making a field public is a strong commitment: it pins down a representation +choice, _and_ prevents the type from providing any validation or maintaining any +invariants on the contents of the field, since clients can mutate it arbitrarily. + +Public fields are most appropriate for `struct` types in the C spirit: compound, +passive data structures. Otherwise, consider providing getter/setter methods and +hiding fields instead. diff --git a/ai-skill/skills/rust-guidelines/rules/C-VALIDATE.md b/ai-skill/skills/rust-guidelines/rules/C-VALIDATE.md new file mode 100644 index 0000000..53421d8 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-VALIDATE.md @@ -0,0 +1,69 @@ +## Functions validate their arguments (C-VALIDATE) + +Rust APIs do _not_ generally follow the [robustness principle]: "be conservative +in what you send; be liberal in what you accept". + +[robustness principle]: http://en.wikipedia.org/wiki/Robustness_principle + +Instead, Rust code should _enforce_ the validity of input whenever practical. + +Enforcement can be achieved through the following mechanisms (listed in order of +preference). + +### Static enforcement + +Choose an argument type that rules out bad inputs. + +For example, prefer + +``` +fn foo(a: Ascii) { /* ... */ } +``` + +over + +``` +fn foo(a: u8) { /* ... */ } +``` + +where `Ascii` is a _wrapper_ around `u8` that guarantees the highest bit is +zero; see newtype patterns ([C-NEWTYPE]) for more details on creating typesafe +wrappers. + +Static enforcement usually comes at little run-time cost: it pushes the costs to +the boundaries (e.g. when a `u8` is first converted into an `Ascii`). It also +catches bugs early, during compilation, rather than through run-time failures. + +On the other hand, some properties are difficult or impossible to express using +types. + +[C-NEWTYPE]: C-NEWTYPE.md + +### Dynamic enforcement + +Validate the input as it is processed (or ahead of time, if necessary). Dynamic +checking is often easier to implement than static checking, but has several +downsides: + +1. Runtime overhead (unless checking can be done as part of processing the + input). +2. Delayed detection of bugs. +3. Introduces failure cases, either via `panic!` or `Result`/`Option` types, + which must then be dealt with by client code. + +#### Dynamic enforcement with `debug_assert!` + +Same as dynamic enforcement, but with the possibility of easily turning off +expensive checks for production builds. + +#### Dynamic enforcement with opt-out + +Same as dynamic enforcement, but adds sibling functions that opt out of the +checking. + +The convention is to mark these opt-out functions with a suffix like +`_unchecked` or by placing them in a `raw` submodule. + +The unchecked functions can be used judiciously in cases where (1) performance +dictates avoiding checks and (2) the client is otherwise confident that the +inputs are valid. diff --git a/ai-skill/skills/rust-guidelines/rules/C-WORD-ORDER.md b/ai-skill/skills/rust-guidelines/rules/C-WORD-ORDER.md new file mode 100644 index 0000000..cde5001 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/C-WORD-ORDER.md @@ -0,0 +1,19 @@ +## Names use a consistent word order (C-WORD-ORDER) + +Here are some error types from the standard library: + +- [`JoinPathsError`](https://doc.rust-lang.org/std/env/struct.JoinPathsError.html) +- [`ParseBoolError`](https://doc.rust-lang.org/std/str/struct.ParseBoolError.html) +- [`ParseCharError`](https://doc.rust-lang.org/std/char/struct.ParseCharError.html) +- [`ParseFloatError`](https://doc.rust-lang.org/std/num/struct.ParseFloatError.html) +- [`ParseIntError`](https://doc.rust-lang.org/std/num/struct.ParseIntError.html) +- [`RecvTimeoutError`](https://doc.rust-lang.org/std/sync/mpsc/enum.RecvTimeoutError.html) +- [`StripPrefixError`](https://doc.rust-lang.org/std/path/struct.StripPrefixError.html) + +All of these use verb-object-error word order. If we were adding an error to +represent an address failing to parse, for consistency we would want to name it +in verb-object-error order like `ParseAddrError` rather than `AddrParseError`. + +The particular choice of word order is not important, but pay attention to +consistency within the crate and consistency with similar functionality in the +standard library. diff --git a/ai-skill/skills/rust-guidelines/rules/M-APP-ERROR.md b/ai-skill/skills/rust-guidelines/rules/M-APP-ERROR.md new file mode 100644 index 0000000..a17d505 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-APP-ERROR.md @@ -0,0 +1,28 @@ +## Applications may use Anyhow or derivatives (M-APP-ERROR) + +Why: simple application-level error handling. + +> Note, this guideline is primarily a relaxation and clarification of [M-ERRORS-CANONICAL-STRUCTS]. + +Applications, and crates in your own repository exclusively used from your application, may use [ohno::AppError](https://docs.rs/crate/ohno/latest#structs), [anyhow](https://github.com/dtolnay/anyhow), +[eyre](https://github.com/eyre-rs/eyre) or similar application-level error crates instead of implementing their own types. + +For example, in your application crates you may just re-export and use eyre's common `Result` type, which should be able to automatically +handle all third party library errors, in particular the ones following +[M-ERRORS-CANONICAL-STRUCTS]. + +``` +use ohno::AppError; + +fn start_application() -> Result<(), AppError> { + start_server()?; + Ok(()) +} +``` + +Once you selected your application error crate you should switch all application-level errors to that type, and you should not mix multiple +application-level error types. + +Libraries (crates used by more than one crate) should always follow [M-ERRORS-CANONICAL-STRUCTS] instead. + +[M-ERRORS-CANONICAL-STRUCTS]: M-ERRORS-CANONICAL-STRUCTS.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-ASYNC-FN.md b/ai-skill/skills/rust-guidelines/rules/M-ASYNC-FN.md new file mode 100644 index 0000000..80b1fea --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ASYNC-FN.md @@ -0,0 +1,17 @@ +## Functions are `async` over returning a Future (M-ASYNC-FN) + +Why: simpler code and easier-to-understand APIs. + +Functions should be declared `async fn foo()` over `fn foo() -> impl Future` when both are viable. + +Functions marked `async` are more idiomatic and easier to read. An explicit `Future`-returning signature should only be used when required, for example inside traits or for _hot 'n heavy_ async functions, compare [M-ASYNC-STACK-SIZE](M-ASYNC-STACK-SIZE.md). + +``` +impl Foo { + // Bad, signature is noisier and the body needs an extra `async` block + fn foo() -> impl Future> { async { Ok(t) } } + + // Good, method and implementation reads normally + async fn foo() -> Result { Ok(t) } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-ASYNC-STACK-SIZE.md b/ai-skill/skills/rust-guidelines/rules/M-ASYNC-STACK-SIZE.md new file mode 100644 index 0000000..7048bc6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ASYNC-STACK-SIZE.md @@ -0,0 +1,75 @@ +## Hot `async` functions reduce stack size (M-ASYNC-STACK-SIZE) + +Why: small async stack sizes and low memcpy overhead. + +Functions marked `async` in the hot path should track their future sizes, and take one or more of the following steps to reduce their impact: + +- reduction of parameter and rval type size, +- reduction of type size of items held across `.await` points, +- returning `impl Future` and extracting setup logic from `async {}` capture. + +> ### Future 'Stack' Sizes +> +> In Futures, what would naively be considered _their stack_, is actually part of a significantly more complicated machinery under their hood. +> +> Regular locals, that only live momentarily between two `.await` points, still remain part of the runtime thread's regular stack. However, any locals that live across `.await` points, or parameters passed during construction, become part of that Future's state machine type, and the layout of this type is currently not as optimized as it could be. +> +> This not only can cause stack-to-heap memcpy operations when creating or boxing Futures, it can also force large upfront stack sizes of the hypothetical most deeply nested cross-async call stack of the involved async function (which, on a side note, is why they can't simply recurse). +> +> ```rust,ignore +> async fn foo(_large: Large) { +> let within_future = [0_u8; 1024]; // Crosses .await below, embedded in `foo` type +> let on_stack = [0_u8; 1024]; // Does not cross .await points, lives on stack +> let sneaky = Droppable::with_size(1024); // Secretly crosses .await point! +> dbg!(&on_stack, &sneaky); +> bar(&within_future).await; +> dbg!(&within_future); +> // <- `sneaky` dropped here, despite otherwise not being used! +> } +> +> let future = foo(Large::new()); // `Large` becomes embedded in `foo` type, +> // blowing up its size, despite it not even +> // being used. +> +> // Here, despite `foo` not running yet, we might consume up to `Large` + +> // 2kb of this thread's stack memory. Once we spawn this is memcpy'ed +> // to runtime Task structure: +> rt.spawn(future); +>``` + +For many async functions this isn't an issue, as their associated `Future`-cost is negligible. However, functions used along the hot path, that are either called or instantiated frequently (e.g., 1000's of calls per second or concurrent tasks) might benefit from monitoring and optimizations. + +Hot futures should be tracked via `size_of_val`: + +``` +async fn hot() { ... } + +#[test] +fn has_reasonable_size() { + let f = hot(); + assert!(size_of_val(&f) < ...); // Determine value / limit at first run. +} +``` + +Then consider a combination of the following: + +``` +// 1) Return an `impl Future` instead, this prevents large arguments +// from infecting the future size, among others. +fn hot(args: Args) -> impl Future> { + // 2) Process arguments outside async context if processing does + // not require async functionality. + let args = args.do_something(); + + if args.invalid() { + // 3) Use `Either` to return a single `impl Future` type, as + // otherwise you'd have to invent a new type. + async { Err(InvalidArgs) }.left_future() + } else { + // 4) Chain future invocations via future helpers, which again + // prevents heavy locals from being passed through the state + // machine. + read(args).then(|x| foo(x)).right_future() + } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-AVOID-INDIRECTION.md b/ai-skill/skills/rust-guidelines/rules/M-AVOID-INDIRECTION.md new file mode 100644 index 0000000..6299a13 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-AVOID-INDIRECTION.md @@ -0,0 +1,43 @@ +## Nested type hierarchies should avoid needless indirection (M-AVOID-INDIRECTION) + +Why: fast, cache-friendly memory access. + +Hot types should avoid nested heap indirection and consider lifting hot, cacheable deep fields to improve cache utilization. + +While the gold standard is to benchmark, a pattern that emerges repeatedly when porting C# code to Rust is to reflexively `Arc` nested types, often multiple layers deep. Although this can make sense on very wide or heavyweight types that genuinely need to be shared by multiple owners, this pattern can ruin access latency when multiple rounds of DRAM lookup have to be performed sequentially. + +Where nested, shared ownership isn't strictly needed, it is usually better to start with local, embedded data, and lift cacheable fields. + +``` +// Bad, `print` (assuming it is reasonably hot) needs 2 indirections +// to query whether it is enabled. +struct Item { + config: Arc, + payload: Payload, +} + +struct Config { + feature: Arc +} + +impl Item { + fn print(&self) { + if self.config.feature.is_enabled() { ... } + } +} + +// Better: `enabled` resides nearby and is likely immediately available +// once `print` is called. +struct Item { + config: Arc, + payload: Payload, + enabled: bool, +} + +impl Item { + fn print(&self) { + if self.enabled { ... } + } +} + +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-AVOID-STATICS.md b/ai-skill/skills/rust-guidelines/rules/M-AVOID-STATICS.md new file mode 100644 index 0000000..8118fe6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-AVOID-STATICS.md @@ -0,0 +1,59 @@ +## Avoid statics (M-AVOID-STATICS) + +Why: consistency and correctness across crate versions. + +Libraries should avoid `static` and thread-local items, if a consistent view of the item is relevant for correctness. +Essentially, any code that would be incorrect if the static _magically_ had another value must not use them. Statics +only used for performance optimizations are ok. + +The fundamental issue with statics in Rust is the secret duplication of state. + +Consider a crate `core` with the following function: + +``` +# use std::sync::atomic::AtomicUsize; +# use std::sync::atomic::Ordering; +static GLOBAL_COUNTER: AtomicUsize = AtomicUsize::new(0); + +pub fn increase_counter() -> usize { + GLOBAL_COUNTER.fetch_add(1, Ordering::Relaxed) +} +``` + +Now assume you have a crate `main`, calling two libraries `library_a` and `library_b`, each invoking that counter: + +``` +// Increase global static counter 2 times +library_a::count_up(); +library_a::count_up(); + +// Increase global static counter 3 more times +library_b::count_up(); +library_b::count_up(); +library_b::count_up(); +``` + +They eventually report their result: + +``` +library_a::print_counter(); +library_b::print_counter(); +main::print_counter(); +``` + +At this point, what is _the_ value of said counter; `0`, `2`, `3` or `5`? + +The answer is, possibly any (even multiple!) of the above, depending on the crate's version resolution! + +Under the hood Rust may link to multiple versions of the same crate, independently instantiated, to satisfy declared +dependencies. This is especially observable during a crate's `0.x` version timeline, where each `x` constitutes a separate _major_ version. + +If `main`, `library_a` and `library_b` all declared the same version of `core`, e.g. `0.5`, then the reported result will be `5`, since all +crates actually _see_ the same version of `GLOBAL_COUNTER`. + +However, if `library_a` declared `0.4` instead, then it would be linked against a separate version of `core`; thus `main` and `library_b` would +agree on a value of `3`, while `library_a` reported `2`. + +Although `static` items can be useful, they are particularly dangerous before a library's stabilization, and for any state where _secret duplication_ would +cause consistency issues when static and non-static variable use interacts. In addition, statics interfere with unit testing, and are a contention point in +thread-per-core designs. diff --git a/ai-skill/skills/rust-guidelines/rules/M-AVOID-WRAPPERS.md b/ai-skill/skills/rust-guidelines/rules/M-AVOID-WRAPPERS.md new file mode 100644 index 0000000..58c260e --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-AVOID-WRAPPERS.md @@ -0,0 +1,29 @@ +## Avoid smart pointers and wrappers in APIs (M-AVOID-WRAPPERS) + +Why: low cognitive load and ergonomic APIs. + +As a specialization of [M-ABSTRACTIONS-DONT-NEST], generic wrappers and smart pointers like +`Rc`, `Arc`, `Box`, or `RefCell` should be avoided in public APIs. + +From a user perspective these are mostly implementation details, and introduce infectious complexity that users have to +resolve. In fact, these might even be impossible to resolve once multiple crates disagree about the required type of wrapper. + +If wrappers are needed internally, they should be hidden behind a clean API that uses simple types like `&T`, `&mut T`, or `T` directly. Compare: + +``` +// Good: simple API +pub fn process_data(data: &Data) -> State { ... } +pub fn store_config(config: Config) -> Result<(), Error> { ... } + +// Bad: Exposing implementation details +pub fn process_shared(data: Arc>) -> Box { ... } +pub fn initialize(config: Rc>) -> Arc { ... } +``` + +Smart pointers in APIs are acceptable when: + +- The smart pointer is fundamental to the API's purpose (e.g., a new container lib) + +- The smart pointer, based on benchmarks, significantly improves performance and the complexity is justified. + +[M-ABSTRACTIONS-DONT-NEST]: https://microsoft.github.io/rust-guidelines/guidelines/libs/ux/#M-ABSTRACTIONS-DONT-NEST diff --git a/ai-skill/skills/rust-guidelines/rules/M-BALANCED-MODULES.md b/ai-skill/skills/rust-guidelines/rules/M-BALANCED-MODULES.md new file mode 100644 index 0000000..4630801 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-BALANCED-MODULES.md @@ -0,0 +1,13 @@ +## Modules are balanced in size and scope (M-BALANCED-MODULES) + +Why: discoverable functionality and clear API usage. + +Your module design should approximately follow established UX practices of menu design: A _reasonable_ number of your most important items should be placed in the crate root, and a comprehensible grouping of the remaining functionality into subordinate modules. + +Two violations of that rule are encountered most frequently: flat module roots containing dozens of items without clear ordering, or the excessive use of submodules without items in the crate root. While there are crates where this makes sense (e.g., automatically generated `-sys` crates defining 100s of C items, or umbrella crates like `std` and `tokio`), the majority of library crates are not among them. + +When designing your module layout, consider these factors: + +- Essential items users must find in order to use a crate should go into its root. For example, a `foo_client` crate should probably have its main `Client` struct inside the root. +- Other items should be grouped semantically by use case. Modules named `traits` and `errors` don't help anyone, but `account`, `network` and `status` do. +- Also take into account that modules are the perfect place for module-level documentation that further explains the respective subsystem. diff --git a/ai-skill/skills/rust-guidelines/rules/M-BOX-DST.md b/ai-skill/skills/rust-guidelines/rules/M-BOX-DST.md new file mode 100644 index 0000000..fa8140e --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-BOX-DST.md @@ -0,0 +1,27 @@ +## Use boxed slices and strings for immutable owned sequences (M-BOX-DST) + +Why: low memory consumption and good cache utilization. + +Frequently used, internal, immutable sequences that will not be resized after construction should be stored as `Box<[T]>`, `Arc` or similar, rather than their original `Vec` or `String` counterparts. + +Regular growable collections consist of a `(ptr, len, capacity)` triple. Converting them to boxed slices makes them immutable, executes a [shrink-to-fit](M-SHRINK-TO-FIT.md), and drops the `capacity` bit, reducing their handle size by 1/3. For this pattern to be useful, the following preconditions should apply: + +- the sequence should be frequently instantiated (e.g., >1000's of instances), +- it must be immutable, +- it should not be user-visible, i.e., regular users would just deal with `&str` or similar. + +Some collections provide dedicated methods for this, e.g., `String::into_boxed_str`. + +``` +// Bad, with many entries this wastes space and makes +// traversal ultimately slower. +struct Data { + ids: Vec +} + +// Good, reduces memory consumption and fits more elements +// into cache. +struct Data { + ids: Vec> +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-BUILD-RESULT.md b/ai-skill/skills/rust-guidelines/rules/M-BUILD-RESULT.md new file mode 100644 index 0000000..2528979 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-BUILD-RESULT.md @@ -0,0 +1,24 @@ +## Builders validate in final `.build()` (M-BUILD-RESULT) + +Why: clean builder error handling. + +A builder's per-field setters should accept input without failing, final validation should be done by `.build()`. + +Fallible setters add noise, and still don't guard against interdependent error conditions. Where builders are fallible they should offer a `Result`-carrying `.build()` instead. + +``` +// Bad, forces repeated error checks that provide no value. +Foo::builder() + .name("Foo")? + .distance(42)? + .build(); + +// Good, consolidates sanity checking and allows for cross-checks +// between properties. +Foo::builder() + .name("Foo") + .distance(42) + .build()?; +``` + +That said, individual settings should prefer strong types carrying their own validation where applicable, compare M-STRONG-TYPES-GUARD. diff --git a/ai-skill/skills/rust-guidelines/rules/M-CANONICAL-DOCS.md b/ai-skill/skills/rust-guidelines/rules/M-CANONICAL-DOCS.md new file mode 100644 index 0000000..0472191 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-CANONICAL-DOCS.md @@ -0,0 +1,51 @@ +## Documentation has canonical sections (M-CANONICAL-DOCS) + +Why: established Rust documentation practices. + +Public library items must contain the canonical doc sections. The summary sentence must always be present. Extended documentation and examples +are strongly encouraged. The other sections must be present when applicable. + +``` +/// Summary sentence < 15 words. +/// +/// Extended documentation in free form. +/// +/// # Examples +/// One or more examples that show API usage like so. +/// +/// # Errors +/// If fn returns `Result`, list known error conditions +/// +/// # Panics +/// If fn may panic, list when this may happen +/// +/// # Safety +/// If fn is `unsafe` or may otherwise cause UB, this section must list +/// all conditions a caller must uphold. +/// +/// # Abort +/// If fn may abort the process, list when this may happen. +pub fn foo() {} +``` + +In contrast to other languages, you should not create a table of parameters. Instead parameter use is explained in plain text. In other words, do not + +``` +/// Copies a file. +/// +/// # Parameters +/// - src: The source. +/// - dst: The destination. +fn copy(src: File, dst: File) {} +``` + +but instead: + +``` +/// Copies a file from `src` to `dst`. +fn copy(src: File, dst: File) {} +``` + +### Related Reading + +- Function docs include error, panic, and safety considerations ([C-FAILURE](https://rust-lang.github.io/api-guidelines/documentation.html#c-failure)) diff --git a/ai-skill/skills/rust-guidelines/rules/M-CARGO-WORKSPACE.md b/ai-skill/skills/rust-guidelines/rules/M-CARGO-WORKSPACE.md new file mode 100644 index 0000000..f1a550e --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-CARGO-WORKSPACE.md @@ -0,0 +1,7 @@ +## Common settings come from the workspace Cargo.toml (M-CARGO-WORKSPACE) + +Why: consistent, maintainable project configuration. + +Any repo with two or more crates that somehow belong together should unify these crates with a workspace `Cargo.toml`. Members then inherit shared metadata and dependency versions from the workspace root via `[workspace.dependencies]`, `[workspace.lints]`, ... rather than duplicating these values in each crate. + +Where a dependency is crate-specific, it should still be defined in the workspace. Workspace definitions should generally not enable dependency features (except basic ones such as `["std"]`), and should instead use `default-features = false`. diff --git a/ai-skill/skills/rust-guidelines/rules/M-COLLECTION-TRAITS.md b/ai-skill/skills/rust-guidelines/rules/M-COLLECTION-TRAITS.md new file mode 100644 index 0000000..441fb6b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-COLLECTION-TRAITS.md @@ -0,0 +1,17 @@ +## Collections implement the appropriate iter traits (M-COLLECTION-TRAITS) + +Why: composable collections. + +Custom collections should implement the iterator-facing traits the standard library offers. + +Whenever you define a new collection type `Collection` for consumption by third parties, the following traits and types should also be implemented, [see here](https://cheats.rs/#iterators) for more details: + +- the structs `IntoIter`, `Iter` and `IterMut`, +- an `impl Iterator` for all of them, +- the methods `c.iter()` and `c.iter_mut()`, +- an `impl IntoIterator` for `Collection`, `&Collection` and `&mut Collection`, +- an `impl FromIterator` for `Collection`, +- an `Extend` for `Collection`, +- `DoubleEndedIterator`, `ExactSizeIterator`, ... as applicable + +In addition, make sure you implement `size_hint()` on all iterators and do so truthfully. diff --git a/ai-skill/skills/rust-guidelines/rules/M-CRATES-FLAT-FOLDER.md b/ai-skill/skills/rust-guidelines/rules/M-CRATES-FLAT-FOLDER.md new file mode 100644 index 0000000..321533b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-CRATES-FLAT-FOLDER.md @@ -0,0 +1,43 @@ +## All crates are siblings in one folder (M-CRATES-FLAT-FOLDER) + +Why: simple project navigation and a standard Rust layout. + +A repository should contain a single workspace `Cargo.toml`, and all Rust crates should be subordinate to it. All crates should then live in a single, direct subdirectory (e.g., `crates/`) below the workspace (for up to 1-2 dozen of crates), beyond that some folder hierarchy should be used (e.g., `common/`, `server/`, `client/`) to organize siblings. + +```bash +# Ideal for most workspaces +Cargo.toml +crates/ + foo/Cargo.toml + foo_core/Cargo.toml + foo_proc/Cargo.toml + foo_tests/Cargo.toml + bar/Cargo.toml + baz/Cargo.toml + + +# Ok for large workspaces +Cargo.toml +crates/ + server/ + main/Cargo.toml + routes/Cargo.toml + client/ + foo/Cargo.toml + bar/Cargo.toml + common/ + error/Cargo.toml +``` + +Placing crates inside other crates (at or below their `Cargo.toml`), or even inside their `src/` folder is never acceptable. If a crate relationship should be expressed, this is done via common prefixes instead (e.g., `foo`, `foo_util`, `foo_build`). + +```bash +# Never acceptable, crates inside `src/` folder +Cargo.toml +crates/ + foo/Cargo.toml + src/lib.rs + deps/bar/Cargo.toml +``` + +Rare exceptions to this rule can occur if your crate is in the business of processing workspaces and has a collection of UI tests or similar it relies on; but even then these are usually dummy crates in nature. diff --git a/ai-skill/skills/rust-guidelines/rules/M-CRATES-IN-WORKSPACE.md b/ai-skill/skills/rust-guidelines/rules/M-CRATES-IN-WORKSPACE.md new file mode 100644 index 0000000..ffcd429 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-CRATES-IN-WORKSPACE.md @@ -0,0 +1,19 @@ +## The workspace lists and versions all crates (M-CRATES-IN-WORKSPACE) + +Why: simple inter-crate dependencies and debugging. + +Every crate produced by the project should be listed as a workspace member, and its version should be declared in `[workspace.dependencies]` so that intra-workspace dependencies resolve to a single canonical version. + +```toml +# Bad, crate links its sibling directly +[dependencies] +sibling.path = "../sibling" + + +# Good, going through workspace +[dependencies] +sibling.workspace = true + +[workspace.dependencies] +sibling = { path = "crates/sibling", version = "0.5.2" } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-DESIGN-FOR-AI.md b/ai-skill/skills/rust-guidelines/rules/M-DESIGN-FOR-AI.md new file mode 100644 index 0000000..32a86f0 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-DESIGN-FOR-AI.md @@ -0,0 +1,40 @@ +## Design with AI use in mind (M-DESIGN-FOR-AI) + +Why: maximum utility from agents working in your codebase. + +As a general rule, making APIs easier to use for humans also makes them easier to use by AI. +If you follow the guidelines in this book, you should be in good shape. + +Rust's strong type system is a boon for agents, as their lack of genuine understanding can often be +counterbalanced by comprehensive compiler checks, which Rust provides in abundance. + +With that said, there are a few guidelines which are particularly important to help make AI coding in Rust more effective: + +* **Create Idiomatic Rust API Patterns**. The more your APIs, whether public or internal, look and feel like the majority of +Rust code in the world, the better it is for AI. Follow the [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/checklist.html) +along with the guidelines from [Library / UX](https://microsoft.github.io/rust-guidelines/guidelines/libs/ux). + +* **Provide Thorough Docs**. Agents love good detailed docs. Include docs for all of your modules and public items in your crate. +Assume the reader has a solid, but not expert, level of understanding of Rust, and that the reader understands the standard library. +Follow +[C-CRATE-DOC](https://rust-lang.github.io/api-guidelines/checklist.html#c-crate-doc), +[C-FAILURE](https://rust-lang.github.io/api-guidelines/checklist.html#c-failure), +[C-LINK](https://rust-lang.github.io/api-guidelines/checklist.html#c-link), and +[M-MODULE-DOCS](M-MODULE-DOCS.md) +[M-CANONICAL-DOCS](M-CANONICAL-DOCS.md). + +* **Provide Thorough Examples**. Your documentation should have directly usable examples, the repository should include more elaborate ones. +Follow +[C-EXAMPLE](https://rust-lang.github.io/api-guidelines/checklist.html#c-example) +[C-QUESTION-MARK](https://rust-lang.github.io/api-guidelines/checklist.html#c-question-mark). + +* **Use Strong Types**. Avoid [primitive obsession](https://refactoring.guru/smells/primitive-obsession) by using strong types with strict well-documented semantics. +Follow +[C-NEWTYPE](https://rust-lang.github.io/api-guidelines/checklist.html#c-newtype). + +* **Make Your APIs Testable**. Design APIs which allow your customers to test their use of your API in unit tests. This might involve introducing some mocks, fakes, +or cargo features. AI agents need to be able to iterate quickly to prove that the code they are writing that calls your API is working +correctly. + +* **Ensure Test Coverage**. Your own code should have good test coverage over observable behavior. +This enables agents to work in a mostly hands-off mode when refactoring. diff --git a/ai-skill/skills/rust-guidelines/rules/M-DI-HIERARCHY.md b/ai-skill/skills/rust-guidelines/rules/M-DI-HIERARCHY.md new file mode 100644 index 0000000..7513096 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-DI-HIERARCHY.md @@ -0,0 +1,85 @@ +## Prefer types over generics, generics over dyn traits (M-DI-HIERARCHY) + +Why: composable patterns and freedom from design lock-in. + +When asking for async dependencies, prefer concrete types over generics, and generics over `dyn Trait`. + +It is easy to accidentally deviate from this pattern when porting code from languages like C# that heavily rely on interfaces. +Consider you are porting a service called `Database` from C# to Rust and, inspired by the original `IDatabase` interface, you naively translate it into: + +``` +trait Database { + async fn update_config(&self, file: PathBuf); + async fn store_object(&self, id: Id, obj: Object); + async fn load_object(&self, id: Id) -> Object; +} + +impl Database for MyDatabase { ... } + +// Intended to be used like this: +async fn start_service(b: Rc) { ... } +``` + +Apart from not feeling idiomatic, this approach precludes other Rust constructs that conflict with object safety, +can cause issues with asynchronous code, and exposes wrappers (compare [M-AVOID-WRAPPERS]). + +Instead, when more than one implementation is needed, this _design escalation ladder_ should be followed: + +If the other implementation is only concerned with providing a _sans-io_ implementation for testing, implement your type as an +enum, following [M-MOCKABLE-SYSCALLS] instead. + +If users are expected to provide custom implementations, you should introduce one or more traits, and implement them for your own types +_on top_ of your inherent functions. Each trait should be relatively narrow, e.g., `StoreObject`, `LoadObject`. If eventually a single +trait is needed it should be made a subtrait, e.g., `trait DataAccess: StoreObject + LoadObject {}`. + +Code working with these traits should ideally accept them as generic type parameters as long as their use does not contribute to significant nesting +(compare [M-ABSTRACTIONS-DONT-NEST]). + +``` +// Good, generic does not have infectious impact, uses only most specific trait +async fn read_database(x: impl LoadObject) { ... } + +// Acceptable, unless further nesting makes this excessive. +struct MyService { + db: T, +} +``` + +Once generics become a nesting problem, `dyn Trait` can be considered. Even in this case, visible wrapping should be avoided, and custom wrappers should be preferred. + +``` +# use std::sync::Arc; +# trait DataAccess { +# fn foo(&self); +# } +// This allows you to expand or change `DynamicDataAccess` later. You can also +// implement `DataAccess` for `DynamicDataAccess` if needed, and use it with +// regular generic functions. +struct DynamicDataAccess(Arc); + +impl DynamicDataAccess { + fn new(db: T) -> Self { + Self(Arc::new(db)) + } +} + +struct MyService { + db: DynamicDataAccess, +} +``` + +The generic wrapper can also be combined with the enum approach from [M-MOCKABLE-SYSCALLS]: + +``` +enum DataAccess { + MyDatabase(MyDatabase), + Mock(mock::MockCtrl), + Dynamic(DynamicDataAccess) +} + +async fn read_database(x: &DataAccess) { ... } +``` + +[M-AVOID-WRAPPERS]: M-AVOID-WRAPPERS.md +[M-MOCKABLE-SYSCALLS]: M-MOCKABLE-SYSCALLS.md +[M-ABSTRACTIONS-DONT-NEST]: https://microsoft.github.io/rust-guidelines/guidelines/libs/ux/#M-ABSTRACTIONS-DONT-NEST diff --git a/ai-skill/skills/rust-guidelines/rules/M-DOC-INLINE.md b/ai-skill/skills/rust-guidelines/rules/M-DOC-INLINE.md new file mode 100644 index 0000000..7b162f2 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-DOC-INLINE.md @@ -0,0 +1,31 @@ +## Mark `pub use` items with `#[doc(inline)]` (M-DOC-INLINE) + +Why: re-exported items that fit in with their siblings. + +When publicly re-exporting crate items via `pub use foo::Foo` or `pub use foo::*`, they show up in an opaque re-export block. In most cases, this is not +helpful to the reader: + +![TEXT](https://microsoft.github.io/rust-guidelines/guidelines/docs/M-DOC-INLINE_BAD.png) + +Instead, you should annotate them with `#[doc(inline)]` at the `use` site, for them to be inlined organically: + +``` +# pub(crate) mod foo { pub struct Foo; } +#[doc(inline)] +pub use foo::*; + +// or + +#[doc(inline)] +pub use foo::Foo; +``` + +![TEXT](https://microsoft.github.io/rust-guidelines/guidelines/docs/M-DOC-INLINE_GOOD.png) + +This does not apply to `std` or 3rd party types; these should always be re-exported without inlining to make it clear they are external. + +> ### Still avoid glob exports +> +> The `#[doc(inline)]` trick above does not change [M-NO-GLOB-REEXPORTS]; you generally should not re-export items via wildcards. + +[M-NO-GLOB-REEXPORTS]: M-NO-GLOB-REEXPORTS.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-DOCUMENTED-MAGIC.md b/ai-skill/skills/rust-guidelines/rules/M-DOCUMENTED-MAGIC.md new file mode 100644 index 0000000..f4a102f --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-DOCUMENTED-MAGIC.md @@ -0,0 +1,32 @@ +## Magic values are documented (M-DOCUMENTED-MAGIC) + +Why: maintainability and safe refactoring. + +Hardcoded _magic_ values in production code must be accompanied by a comment. The comment should outline: + +- why this value was chosen, +- non-obvious side effects if that value is changed, +- external systems that interact with this constant. + +You should prefer named constants over inline values. + +``` +// Bad: it's relatively obvious that this waits for a day, but not why +wait_timeout(60 * 60 * 24).await // Wait at most a day + +// Better +wait_timeout(60 * 60 * 24).await // Large enough value to ensure the server + // can finish. Setting this too low might + // make us abort a valid request. Based on + // `api.foo.com` timeout policies. + +// Best + +/// How long we wait for the server. +/// +/// Large enough value to ensure the server +/// can finish. Setting this too low might +/// make us abort a valid request. Based on +/// `api.foo.com` timeout policies. +const UPSTREAM_SERVER_TIMEOUT: Duration = Duration::from_secs(60 * 60 * 24); +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-DONT-LEAK-TYPES.md b/ai-skill/skills/rust-guidelines/rules/M-DONT-LEAK-TYPES.md new file mode 100644 index 0000000..4f0ef1b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-DONT-LEAK-TYPES.md @@ -0,0 +1,28 @@ +## Don't leak external types (M-DONT-LEAK-TYPES) + +Why: stable APIs and low long-term maintenance cost. + +Where possible, you should prefer `std`1 types in public APIs over types coming from external crates. Exceptions should be carefully considered. + +Any type in any public API will become part of that API's contract. Since `std` and constituents are the only crates +shipped by default, and since they come with a permanent stability guarantee, their types are the only ones that come without an interoperability risk. + +A crate that exposes another crate's type is said to _leak_ that type. + +For maximal long term stability your crate should, theoretically, not leak any types. Practically, some leakage +is unavoidable, sometimes even beneficial. We recommend you follow this heuristic: + +- [ ] if you can avoid it, do not leak third-party types +- [ ] if you are part of an umbrella crate,2 you may freely leak types from sibling crates. +- [ ] behind a relevant feature flag, types may be leaked (e.g., `serde`) +- [ ] without a feature _only_ if they give a _substantial benefit_. Most commonly that is interoperability with significant + other parts of the Rust ecosystem based around these types. + + + +1 In rare instances, e.g., high performance libraries used from embedded, you might even want to limit yourself to `core` only. + +2 For example, a `runtime` crate might be the umbrella of `runtime_rt`, `runtime_app` and `runtime_clock` As users are +expected to only interact with the umbrella, siblings may leak each others types. + + diff --git a/ai-skill/skills/rust-guidelines/rules/M-ERRORS-CANONICAL-STRUCTS.md b/ai-skill/skills/rust-guidelines/rules/M-ERRORS-CANONICAL-STRUCTS.md new file mode 100644 index 0000000..b9c3bd2 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ERRORS-CANONICAL-STRUCTS.md @@ -0,0 +1,119 @@ +## Errors are canonical structs (M-ERRORS-CANONICAL-STRUCTS) + +Why: harmonized error types and consistent error handling. + +Errors should be a situation-specific `struct` that contain a [`Backtrace`](https://doc.rust-lang.org/stable/std/backtrace/struct.Backtrace.html), +a possible upstream error cause, and helper methods. + +Simple crates usually expose a single error type `Error`, complex crates may expose multiple types, for example +`AccessError` and `ConfigurationError`. Error types should provide helper methods for additional information that allows callers to handle the error. + +A simple error might look like so: + +``` +# use std::backtrace::Backtrace; +# use std::fmt::Display; +# use std::fmt::Formatter; +pub struct ConfigurationError { + backtrace: Backtrace, +} + +impl ConfigurationError { + pub(crate) fn new() -> Self { + Self { backtrace: Backtrace::capture() } + } +} + +// Impl Debug + Display +``` + +Where appropriate, error types should provide contextual error information, for example: + +``` +# use std::backtrace::Backtrace; +# #[derive(Debug)] +# pub struct ConfigurationError { +# backtrace: Backtrace, +# } +impl ConfigurationError { + pub fn config_file(&self) -> &Path { } +} +``` + +If your API does mixed operations, or depends on various upstream libraries, store an `ErrorKind`. +Error kinds, and more generally enum-based errors, should not be used to avoid creating separate public error types when there is otherwise no error overlap: + +``` +// Prefer this +fn download_iso() -> Result<(), DownloadError> {} +fn start_vm() -> Result<(), VmError> {} + +// Over that +fn download_iso() -> Result<(), GlobalEverythingErrorEnum> {} +fn start_vm() -> Result<(), GlobalEverythingErrorEnum> {} + +// However, not every function warrants a new error type. Errors +// should be general enough to be reused. +fn parse_json() -> Result<(), ParseError> {} +fn parse_toml() -> Result<(), ParseError> {} +``` + +If you do use an inner `ErrorKind`, that enum should not be exposed directly for future-proofing reasons, +as otherwise you would expose your callers to _all_ possible failure modes, even the ones you consider internal +and unhandleable. Instead, expose various `is_xxx()` methods as shown below: + +``` +# use std::backtrace::Backtrace; +# use std::fmt::Display; +# use std::fmt::Formatter; +#[derive(Debug)] +pub(crate) enum ErrorKind { + Io(std::io::Error), + Protocol +} + +#[derive(Debug)] +pub struct HttpError { + kind: ErrorKind, + backtrace: Backtrace, +} + +impl HttpError { + pub fn is_io(&self) -> bool { matches!(self.kind, ErrorKind::Io(_)) } + pub fn is_protocol(&self) -> bool { matches!(self.kind, ErrorKind::Protocol) } +} +``` + +Most upstream errors don't provide a backtrace. You should capture one when creating an `Error` instance, either via one of +your `Error::new()` flavors, or when implementing `From for Error {}`. + +Error structs must properly implement `Display` that renders as follows: + +``` +impl Display for MyError { + // Print a summary sentence what happened. + // Print `self.backtrace`. + // Print any additional upstream 'cause' information you might have. +# fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +# todo!() +# } +} +``` + +Errors must also implement `std::error::Error`: + +``` +impl std::error::Error for MyError { } +``` + +Lastly, if you happen to emit lots of errors from your crate, consider creating a private `bail!()` helper macro to simplify error instantiation. + +> ### When You Get Backtraces +> +> Backtraces are an invaluable debug tool in complex or async code, since errors might _travel_ far through a callstack before being surfaced. +> +> That said, they are a _development_ tool, not a _runtime_ diagnostic, and by default `Backtrace::capture()` will **not** capture +> backtraces, as they have a large overhead, e.g., 4ÎĽs per capture on the author's PC. +> +> Instead, Rust evaluates a [set of environment variables](https://doc.rust-lang.org/stable/std/backtrace/index.html#environment-variables), such as +> `RUST_BACKTRACE`, and only walks the call frame when explicitly asked. Otherwise it captures an empty trace, at the cost of only a few CPU instructions. diff --git a/ai-skill/skills/rust-guidelines/rules/M-ESCAPE-HATCHES.md b/ai-skill/skills/rust-guidelines/rules/M-ESCAPE-HATCHES.md new file mode 100644 index 0000000..81a13f5 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ESCAPE-HATCHES.md @@ -0,0 +1,30 @@ +## Native escape hatches (M-ESCAPE-HATCHES) + +Why: workarounds for unsupported use cases until alternatives exist. + +Types wrapping native handles should provide `unsafe` escape hatches. In interop scenarios your users might have gotten a native handle from somewhere +else, or they might have to pass your wrapped handle over FFI. To enable these use cases you should provide `unsafe` conversion methods. + +``` +# type HNATIVE = *const u8; +pub struct Handle(HNATIVE); + +impl Handle { + pub fn new() -> Self { + // Safely creates handle via API calls + # todo!() + } + + // Constructs a new Handle from a native handle the user got elsewhere. + // This method should then also document all safety requirements that + // must be fulfilled. + pub unsafe fn from_native(native: HNATIVE) -> Self { + Self(native) + } + + // Various extra methods to permanently or temporarily obtain + // a native handle. + pub fn into_native(self) -> HNATIVE { self.0 } + pub fn to_native(&self) -> HNATIVE { self.0 } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-ESSENTIAL-FN-INHERENT.md b/ai-skill/skills/rust-guidelines/rules/M-ESSENTIAL-FN-INHERENT.md new file mode 100644 index 0000000..437fca6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ESSENTIAL-FN-INHERENT.md @@ -0,0 +1,43 @@ +## Essential functionality should be inherent (M-ESSENTIAL-FN-INHERENT) + +Why: easily discoverable essential functionality. + +Types should implement core functionality inherently. Trait implementations should forward to inherent functions, and not replace them. Instead of this + +``` +# trait Download { +# fn download_file(&self, url: impl AsRef); +# } +struct HttpClient {} + +// Offloading essential functionality into traits means users +// will have to figure out what other traits to `use` to +// actually use this type. +impl Download for HttpClient { + fn download_file(&self, url: impl AsRef) { + // ... logic to download a file + } +} +``` + +do this: + +``` +# trait Download { +# fn download_file(&self, url: impl AsRef); +# } +struct HttpClient {} + +impl HttpClient { + fn download_file(&self, url: impl AsRef) { + // ... logic to download a file + } +} + +// Forward calls to inherent impls. `HttpClient` can be used +impl Download for HttpClient { + fn download_file(&self, url: impl AsRef) { + Self::download_file(self, url) + } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-EXAMPLE-OVER-PROC.md b/ai-skill/skills/rust-guidelines/rules/M-EXAMPLE-OVER-PROC.md new file mode 100644 index 0000000..34bb6fb --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-EXAMPLE-OVER-PROC.md @@ -0,0 +1,17 @@ +## Prefer 'macros by example' over proc macros (M-EXAMPLE-OVER-PROC) + +Why: easy macro inspection and fast compilation. + +When a 'macro by example' can do the job, it should be preferred over proc macros. + +Proc macros are more powerful, but their expansion can't easily be inspected. Where this versatility isn't needed, a simple 'macro by example' is the better option. + +``` +// Bad, attribute macro requires proc macro machinery, can be hard to +// inspect in some IDEs, and isn't needed here. +#[make_new_id] +struct MyId; + +// Good, easier to write, maintain and inspect, faster compilation speed. +make_new_id!(MyId); +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-FAST-HASHER.md b/ai-skill/skills/rust-guidelines/rules/M-FAST-HASHER.md new file mode 100644 index 0000000..7590018 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FAST-HASHER.md @@ -0,0 +1,15 @@ +## Use a fast hasher where possible (M-FAST-HASHER) + +Why: hashing performance. + +When hashing trusted, internal keys, prefer a fast non-cryptographic hasher (e.g., `foldhash`, `FxHash`) over the standard library default. + +Rust's default hasher is reasonably DoS safe on untrusted user input, but this comes at a performance penalty. If you can trust that keys are not maliciously crafted to overflow individual buckets, a custom fast hasher can yield significant performance gains. + +``` +// Bad, uses default hasher for keys we control. +let lookup = HashMap::::with_capacity(1024); + +// Good, uses faster foldhash for internal keys. +let lookup = foldhash::HashMap::with_capacity(1024); +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-FEATURES-ADDITIVE.md b/ai-skill/skills/rust-guidelines/rules/M-FEATURES-ADDITIVE.md new file mode 100644 index 0000000..53000f1 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FEATURES-ADDITIVE.md @@ -0,0 +1,16 @@ +## Features are additive (M-FEATURES-ADDITIVE) + +Why: reliable compilation in large, complex projects. + +All library features must be additive, and any combination must work, as long as the feature itself would work on the current platform. This implies: + +- [ ] You must not introduce a `no-std` feature, use a `std` feature instead +- [ ] Adding any feature `foo` must not disable or modify any public item + - Adding enum variants is fine if these enums are `#[non_exhaustive]` +- [ ] Features must not rely on other features to be manually enabled +- [ ] Features must not rely on their parent to skip-enable a feature in one of their children + +Further Reading + +- [Feature Unification](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification) +- [Mutually Exclusive Features](https://doc.rust-lang.org/cargo/reference/features.html#mutually-exclusive-features) diff --git a/ai-skill/skills/rust-guidelines/rules/M-FFI-NAMING.md b/ai-skill/skills/rust-guidelines/rules/M-FFI-NAMING.md new file mode 100644 index 0000000..e599543 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FFI-NAMING.md @@ -0,0 +1,10 @@ +## FFI crates follow established naming conventions (M-FFI-NAMING) + +Why: immediately recognizable crate roles across projects. + +Crates used for FFI should follow established naming practices: + +- `-sys` for crates defining items to call into existing (C-style) libraries +- `-ffi` for crates defining (C-style) items when called from existing applications + +There are slight variations of this scheme (e.g., `-sys2` when a previous `-sys` crate was abandoned and using `-` vs `_`), but overall `-ffi` clearly defines 'export' libraries, and `-sys` 'import' ones. diff --git a/ai-skill/skills/rust-guidelines/rules/M-FFI-TRANSLATES.md b/ai-skill/skills/rust-guidelines/rules/M-FFI-TRANSLATES.md new file mode 100644 index 0000000..2605879 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FFI-TRANSLATES.md @@ -0,0 +1,48 @@ +## Business logic belongs in core crates, FFI only translates (M-FFI-TRANSLATES) + +Why: maximal safe code and a clean separation of concerns. + +When Rust is used to create FFI libraries, there should be a clear separation of concerns between the core _business logic_ crate `foo` and the glue crate `foo-ffi`. + +Any operational functionality belongs in the core crate and should be expressed as idiomatic, safe, testable Rust. The FFI crate exists only to translate between native Rust and C constructs, and the core crate must not be infected with interop concerns, even if this means repeating, and slightly adjusting, type and function signatures. For example, given the following type in the core crate `foo`: + +``` +pub struct Message { + destination: [u8; 8], + data: Vec, +} + +impl Message { + pub fn new(destination: [u8; 8], data: Vec) -> Self { /* ... */ } + pub fn transmit(&self) -> Result<(), TransmitError> { /* ... */ } +} +``` + +A proper separation of concerns might collapse construction and transmission into a single FFI entry point in `foo-ffi`: + +``` +#[no_mangle] +pub unsafe extern "C" fn transmit_message( + destination: *const [u8; 8], + data: *const u8, + data_len: usize, +) -> u8 { + let data = std::slice::from_raw_parts(data, data_len).to_vec(); + match Message::new(*destination, data).transmit() { + Ok(()) => 0, + Err(_) => 1, + } +} +``` + +However, it would be improper to leak FFI requirements into `foo` itself: ownership, data models and signatures do not translate seamlessly between the two worlds. Any time _saved_ by skipping a clean split will have to be paid back many times over during refactorings down the line. + +``` +#[repr(C)] +pub struct Message { + pub destination: [u8; 8], + pub data_ptr: *mut u8, + pub data_len: usize, + pub data_cap: usize, +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-FIRST-DOC-SENTENCE.md b/ai-skill/skills/rust-guidelines/rules/M-FIRST-DOC-SENTENCE.md new file mode 100644 index 0000000..0bdb333 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FIRST-DOC-SENTENCE.md @@ -0,0 +1,26 @@ +## First sentence is one line; approx. 15 words (M-FIRST-DOC-SENTENCE) + +Why: easily skimmable API docs. + +When you document your item, the first sentence becomes the "summary sentence" that is extracted and shown in the module summary: + +``` +/// This is the summary sentence, shown in the module summary. +/// +/// This is other documentation. It is only shown in that item's detail view. +/// Sentences here can be as long as you like and it won't cause any issues. +fn some_item() { } +``` + +Since Rust API documentation is rendered with a fixed max width, there is a naturally preferred sentence length you should not +exceed to keep things tidy on most screens. + +If you keep things in a line, your docs will become easily skimmable. Compare, for example, the standard library: + +![TEXT](https://microsoft.github.io/rust-guidelines/guidelines/docs/M-FIRST-DOC-SENTENCE_GOOD.png) + +Otherwise, you might end up with _widows_ and a generally unpleasant reading flow: + +![TEXT](https://microsoft.github.io/rust-guidelines/guidelines/docs/M-FIRST-DOC-SENTENCE_BAD.png) + +As a rule of thumb, the first sentence should not exceed **15 words**. diff --git a/ai-skill/skills/rust-guidelines/rules/M-FOREIGN-REEXPORTS.md b/ai-skill/skills/rust-guidelines/rules/M-FOREIGN-REEXPORTS.md new file mode 100644 index 0000000..cb9b85c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FOREIGN-REEXPORTS.md @@ -0,0 +1,11 @@ +## Items come from their original crate (M-FOREIGN-REEXPORTS) + +Why: unambiguous type identity. + +Crates should generally not re-export items from other crates. For example, if your crate contains a method `foo::download(url: bar::Url)`, you should not do `pub use bar::Url` from inside `foo`. This avoids having possibly dozens of aliases in context, which can get confusing for both users and agents, in particular if these are mixed with genuinely different types of the same name from other crates. + +When a crate accepts or returns a type defined in some third-party crate, users are expected to depend on that third-party crate directly and import the type from there. That said, there are a few valid exceptions to this rule: + +- Umbrella crates (compare [M-DONT-LEAK-TYPES](M-DONT-LEAK-TYPES.md)) by definition re-export other types +- Crates split for technical reasons (e.g., exporting `foo_core::Url` from `foo`) +- Macro use to provide stable paths, e.g., via some hidden `foo::__private::Url` diff --git a/ai-skill/skills/rust-guidelines/rules/M-FROM-ERROR.md b/ai-skill/skills/rust-guidelines/rules/M-FROM-ERROR.md new file mode 100644 index 0000000..87950a6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-FROM-ERROR.md @@ -0,0 +1,27 @@ +## Canonical error conversion uses `From`, not `map_err` (M-FROM-ERROR) + +Why: idiomatic error handling. + +Where an `Error` type is owned, it should `impl From for Error {}` instead of handling the conversion throughout the code via `.map_error()`. Calling `.map_error()` is only appropriate when dealing with foreign error types, or if contextual information needs to be preserved. + +``` +// Bad, repeats the same conversion at every call site and obscures the happy path. +fn load() -> Result { + let bytes = read("config.toml").map_err(|e| MyError::Io(e))?; + let text = str::from_utf8(&bytes).map_err(|e| MyError::Utf8(e))?; + let cfg = toml::from_str(text).map_err(|e| MyError::Parse(e))?; + Ok(cfg) +} + +// Good, define the conversion once and let `?` apply it. +impl From for MyError { ... } +impl From for MyError { ... } +impl From for MyError { ... } + +fn load() -> Result { + let bytes = read("config.toml")?; + let text = str::from_utf8(&bytes)?; + let cfg = toml::from_str(text)?; + Ok(cfg) +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-HOTPATH.md b/ai-skill/skills/rust-guidelines/rules/M-HOTPATH.md new file mode 100644 index 0000000..b1ec040 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-HOTPATH.md @@ -0,0 +1,41 @@ +## Identify, profile, optimize the hot path early (M-HOTPATH) + +Why: high-performance code. + +You should, early in the development process, identify if your crate is performance or COGS relevant. If it is: + +- identify hot paths and create benchmarks around them, +- regularly run a profiler collecting CPU and allocation insights, +- document or communicate the most performance sensitive areas. + +For benchmarks we recommend [criterion](https://crates.io/crates/criterion) or [divan](https://crates.io/crates/divan). +If possible, benchmarks should not only measure elapsed wall time, but also used CPU time over all threads (this unfortunately +requires manual work and is not supported out of the box by the common benchmark utils). + +Profiling Rust on Windows works out of the box with [Intel VTune](https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler.html) +and [Superluminal](https://superluminal.eu/). However, to gain meaningful CPU insights you should enable debug symbols for benchmarks in your `Cargo.toml`: + +```toml +[profile.bench] +debug = 1 +``` + +Documenting the most performance sensitive areas helps other contributors take better decision. This can be as simple as +sharing screenshots of your latest profiling hot spots. + +### Further Reading + +- [Performance Tips](https://cheats.rs/#performance-tips) + +> ### How much faster? +> +> Some of the most common 'language related' issues we have seen include: +> +> - frequent re-allocations, esp. cloned, growing or `format!` assembled strings, +> - short lived allocations over bump allocations or similar, +> - memory copy overhead that comes from cloning Strings and collections, +> - repeated re-hashing of equal data structures +> - the use of Rust's default hasher where collision resistance wasn't an issue +> +> Anecdotally, we have seen ~15% benchmark gains on hot paths where only some of these `String` problems were +> addressed, and it appears that up to 50% could be achieved in highly optimized versions. diff --git a/ai-skill/skills/rust-guidelines/rules/M-IMPL-ASREF.md b/ai-skill/skills/rust-guidelines/rules/M-IMPL-ASREF.md new file mode 100644 index 0000000..abd9583 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-IMPL-ASREF.md @@ -0,0 +1,44 @@ +## Accept `impl AsRef<>` where feasible (M-IMPL-ASREF) + +Why: flexibility for callers to use their own types. + +In **function** signatures, accept `impl AsRef` for types that have a +[clear reference hierarchy](https://doc.rust-lang.org/stable/std/convert/trait.AsRef.html#implementors), where you +do not need to take ownership, or where object creation is relatively cheap. + +| Instead of ... | accept ... | +| --- | --- | +| `&str`, `String` | `impl AsRef` | +| `&Path`, `PathBuf` | `impl AsRef` | +| `&[u8]`, `Vec` | `impl AsRef<[u8]>` | + +``` +# use std::path::Path; +// Definitely use `AsRef`, the function does not need ownership. +fn print(x: impl AsRef) {} +fn read_file(x: impl AsRef) {} +fn send_network(x: impl AsRef<[u8]>) {} + +// Further analysis needed. In these cases the function wants +// ownership of some `String` or `Vec`. If those are +// "low frequency, low volume" functions `AsRef` has better ergonomics, +// otherwise accepting a `String` or `Vec` will have better +// performance. +fn new_instance(x: impl AsRef) -> HoldsString {} +fn send_to_other_thread(x: impl AsRef<[u8]>) {} +``` + +In contrast, **types** should generally not be infected by these bounds: + +``` +// Generally not ok. There might be exceptions for performance +// reasons, but those should not be user visible. +struct User> { + name: T +} + +// Better +struct User { + name: String +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-IMPL-IO.md b/ai-skill/skills/rust-guidelines/rules/M-IMPL-IO.md new file mode 100644 index 0000000..a01f3ae --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-IMPL-IO.md @@ -0,0 +1,30 @@ +## Accept `impl 'IO'` where feasible ('sans IO') (M-IMPL-IO) + +Why: business logic untangled from I/O, with N*M composability. + +Functions and types that only need to perform one-shot I/O during initialization should be written "[sans-io](https://www.firezone.dev/blog/sans-io)", +and accept some `impl T`, where `T` is the appropriate I/O trait, effectively outsourcing I/O work to another type: + +``` +// Bad, caller must provide a File to parse the given data. If this +// data comes from the network, it'd have to be written to disk first. +fn parse_data(file: File) {} +``` + +``` +// Much better, accepts +// - Files, +// - TcpStreams, +// - Stdin, +// - &[u8], +// - UnixStreams, +// ... and many more. +fn parse_data(data: impl std::io::Read) {} +``` + +Synchronous functions should use [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and +[`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html). Asynchronous _functions_ targeting more than one runtime should use +[`futures::io::AsyncRead`](https://docs.rs/futures/latest/futures/io/trait.AsyncRead.html) and similar. +_Types_ that need to perform runtime-specific, continuous I/O should follow [M-RUNTIME-ABSTRACTED] instead. + +[M-RUNTIME-ABSTRACTED]: https://microsoft.github.io/rust-guidelines/guidelines/libs/interop/#M-RUNTIME-ABSTRACTED diff --git a/ai-skill/skills/rust-guidelines/rules/M-IMPL-RANGEBOUNDS.md b/ai-skill/skills/rust-guidelines/rules/M-IMPL-RANGEBOUNDS.md new file mode 100644 index 0000000..c3b4dbc --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-IMPL-RANGEBOUNDS.md @@ -0,0 +1,25 @@ +## Accept `impl RangeBounds<>` where feasible (M-IMPL-RANGEBOUNDS) + +Why: flexibility and clarity when specifying ranges. + +Functions that accept a range of numbers must use a `Range` type or trait over hand-rolled parameters: + +``` +// Bad +fn select_range(low: usize, high: usize) {} +fn select_range(range: (usize, usize)) {} +``` + +In addition, functions that can work on arbitrary ranges, should accept `impl RangeBounds` rather than `Range`. + +``` +# use std::ops::{RangeBounds, Range}; +// Callers must call with `select_range(1..3)` +fn select_range(r: Range) {} + +// Callers may call as +// select_any(1..3) +// select_any(1..) +// select_any(..) +fn select_any(r: impl RangeBounds) {} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-INIT-BUILDER.md b/ai-skill/skills/rust-guidelines/rules/M-INIT-BUILDER.md new file mode 100644 index 0000000..7c6451f --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-INIT-BUILDER.md @@ -0,0 +1,124 @@ +## Complex type construction has builders (M-INIT-BUILDER) + +Why: future-proof type construction in complex scenarios. + +Types that could support 4 or more arbitrary initialization permutations should provide builders. In other words, types with up to +2 optional initialization parameters can be constructed via inherent methods: + +``` +# struct A; +# struct B; +struct Foo; + +// Supports 2 optional construction parameters, inherent methods ok. +impl Foo { + pub fn new() -> Self { Self } + pub fn with_a(a: A) -> Self { Self } + pub fn with_b(b: B) -> Self { Self } + pub fn with_a_b(a: A, b: B) -> Self { Self } +} +``` + +Beyond that, types should provide a builder: + +``` +# struct A; +# struct B; +# struct C; +# struct Foo; +# struct FooBuilder; +impl Foo { + pub fn new() -> Self { ... } + pub fn builder() -> FooBuilder { ... } +} + +impl FooBuilder { + pub fn a(mut self, a: A) -> Self { ... } + pub fn b(mut self, b: B) -> Self { ... } + pub fn c(mut self, c: C) -> Self { ... } + pub fn build(self) -> Foo { ... } +} + +``` + +The proper name for a builder that builds `Foo` is `FooBuilder`. Its methods must be chainable, with the final method called +`.build()`. The buildable struct must have a shortcut `Foo::builder()`, while the builder itself should _not_ have a public +`FooBuilder::new()`. Builder methods that set a value `x` are called `x()`, not `set_x()` or similar. + +### Builders and Required Parameters + +Required parameters should be passed when creating the builder, not as setter methods. For builders with multiple required +parameters, encapsulate them into a parameters struct and use the `deps: impl Into` pattern to provide flexibility: + +> **Note:** A dedicated deps struct is not required if the builder has no required parameters or only a single simple parameter. However, +> for backward compatibility and API evolution, it's preferable to use a dedicated struct for deps even in simple cases, as it makes it +> easier to add new required parameters in the future without breaking existing code. + +``` +#[derive(Debug, Clone)] +pub struct FooDeps { + pub logger: Logger, + pub config: Config, +} + +impl From<(Logger, Config)> for FooDeps { ... } +impl From for FooDeps { ... } // In case we could use default Config instance + +impl Foo { + pub fn builder(deps: impl Into) -> FooBuilder { ... } +} +``` + +This pattern allows for convenient usage: + +- `Foo::builder(logger)` - when only the logger is needed +- `Foo::builder((logger, config))` - when both parameters are needed +- `Foo::builder(FooDeps { logger, config })` - explicit struct construction + +Alternatively, you can use [`fundle`](https://docs.rs/fundle) to simplify the creation of `FooDeps`: + +``` +#[derive(Debug, Clone)] +#[fundle::deps] +pub struct FooDeps { + pub logger: Logger, + pub config: Config, +} +``` + +This pattern enables "dependency injection", see [these docs](https://docs.rs/fundle/latest/fundle/attr.deps.html) for more details. + +### Runtime-Specific Builders + +For types that are runtime-specific or require runtime-specific configuration, provide dedicated builder creation methods that accept the appropriate runtime parameters: + +``` +#[cfg(feature="smol")] +#[derive(Debug, Clone)] +pub struct SmolDeps { + pub clock: Clock, + pub io_context: Context, +} + +#[cfg(feature="tokio")] +#[derive(Debug, Clone)] +pub struct TokioDeps { + pub clock: Clock, +} + +impl Foo { + #[cfg(feature="smol")] + pub fn builder_smol(deps: impl Into) -> FooBuilder { ... } + + #[cfg(feature="tokio")] + pub fn builder_tokio(deps: impl Into) -> FooBuilder { ... } +} +``` + +This approach ensures type safety at compile time and makes the runtime dependency explicit in the API surface. The resulting +builder methods follow the pattern `builder_{runtime}(deps)` where `{runtime}` indicates the specific runtime or execution environment. + +### Further Reading + +- [Builder pattern in Rust: self vs. &mut self, and method vs. associated function](https://users.rust-lang.org/t/builder-pattern-in-rust-self-vs-mut-self-and-method-vs-associated-function/72892) +- [fundle](https://docs.rs/fundle) diff --git a/ai-skill/skills/rust-guidelines/rules/M-INIT-CASCADED.md b/ai-skill/skills/rust-guidelines/rules/M-INIT-CASCADED.md new file mode 100644 index 0000000..0216144 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-INIT-CASCADED.md @@ -0,0 +1,33 @@ +## Complex type initialization hierarchies are cascaded (M-INIT-CASCADED) + +Why: construction free of parameter mix-ups. + +Types that require 4+ parameters should cascade their initialization via helper types. + +``` +# struct Deposit; +impl Deposit { + // Easy to confuse parameters and signature generally unwieldy. + pub fn new(bank_name: &str, customer_name: &str, currency_name: &str, currency_amount: u64) -> Self { } +} +``` + +Instead of providing a long parameter list, parameters should be grouped semantically. When applying this guideline, +also check if [C-NEWTYPE] is applicable: + +``` +# struct Deposit; +# struct Account; +# struct Currency +impl Deposit { + // Better, signature cleaner + pub fn new(account: Account, amount: Currency) -> Self { } +} + +impl Account { + pub fn new_ok(bank: &str, customer: &str) -> Self { } + pub fn new_even_better(bank: Bank, customer: Customer) -> Self { } +} +``` + +[C-NEWTYPE]: https://rust-lang.github.io/api-guidelines/type-safety.html#c-newtype diff --git a/ai-skill/skills/rust-guidelines/rules/M-INITIAL-CAPACITY.md b/ai-skill/skills/rust-guidelines/rules/M-INITIAL-CAPACITY.md new file mode 100644 index 0000000..fbab56a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-INITIAL-CAPACITY.md @@ -0,0 +1,28 @@ +## Collections are created with sufficient initial capacity (M-INITIAL-CAPACITY) + +Why: efficient collection creation. + +Where the final or approximate size of a collection (`Vec`, `String`, `HashMap`, `HashSet`, etc.) is known at construction time, it should be created via `with_capacity` rather than `new` or `default`. + +Collections created without capacity may be re-allocated multiple times during their initialization, which also includes copying their content. Creating them with sufficient capacity can entirely avoid this needless overhead. + +``` +// Bad, probably re-allocates and copies content over multiple times. +let mut rval = Vec::new(); +for x in &other { + rval.push(convert(x)); +} + +// Better, creates collection with sufficient capacity upfront. +let mut rval = Vec::with_capacity(other.len()); +for x in &other { + rval.push(convert(x)); +} +``` + +Iterator-driven construction (`collect`) inherits this behavior via `size_hint` and should be preferred over manual `push` loops when possible: + +``` +// Ideal, looks nicer and is performant +let rval: Vec<_> = other.iter().map(convert).collect(); +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-INTEGRATION-TESTS.md b/ai-skill/skills/rust-guidelines/rules/M-INTEGRATION-TESTS.md new file mode 100644 index 0000000..2bd2fee --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-INTEGRATION-TESTS.md @@ -0,0 +1,7 @@ +## Integration tests live under `tests/` (M-INTEGRATION-TESTS) + +Why: clean code files. + +Tests that only touch public API surface are _integration tests_ and belong under `tests/`, not `mod tests {}`. + +In projects with coverage targets, it is not uncommon for `src/` files to contain more testing code than actual business logic. This can make browsing and understanding the code harder both in IDEs and PRs. Likewise, if a testing goal can be achieved through either an integration test or a unit test, the former is always preferred. diff --git a/ai-skill/skills/rust-guidelines/rules/M-ISOLATE-DLL-STATE.md b/ai-skill/skills/rust-guidelines/rules/M-ISOLATE-DLL-STATE.md new file mode 100644 index 0000000..3d95cc4 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-ISOLATE-DLL-STATE.md @@ -0,0 +1,50 @@ +## Isolate DLL state between FFI libraries (M-ISOLATE-DLL-STATE) + +Why: data integrity and defined behavior across DLL boundaries. + +When loading multiple Rust-based dynamic libraries (DLLs) within one application, you may only share 'portable' state between these libraries. +Likewise, when authoring such libraries, you must only accept or provide 'portable' data from foreign DLLs. + +Portable here means data that is safe and consistent to process regardless of its origin. By definition, this is a subset of FFI-safe types. +A type is portable if it is `#[repr(C)]` (or similarly well-defined), and _all_ of the following: + +- It must not have any interaction with any `static` or thread local. +- It must not have any interaction with any `TypeId`. +- It must not contain any value, pointer or reference to any non-portable data (it is valid to point into portable data within non-portable data, such as + sharing a reference to an ASCII string held in a `Box`). + +_Interaction_ means any computational relationship, and therefore also relates to how the type is used. Sending a `u128` between DLLs is OK, using it to +exchange a transmuted `TypeId` isn't. + +The underlying issue stems from the Rust compiler treating each DLL as an entirely new compilation artifact, akin to a standalone application. This means each DLL: + +- has its own set of `static` and thread-local variables, +- the type layout of any `#[repr(Rust)]` type (the default) can differ between compilations, +- has its own set of unique type IDs, differing from any other DLL. + +Notably, this affects: + +- ⚠️ any allocated instance, e.g., `String`, `Vec`, `Box`, ... +- ⚠️ any library relying on other statics, e.g., `tokio`, `log`, +- ⚠️ any struct not `#[repr(C)]`, +- ⚠️ any data structure relying on consistent `TypeId`. + +In practice, transferring any of the above between libraries leads to data loss, state corruption, and usually undefined behavior. + +Take particular note that this may also apply to types and methods that are invisible at the FFI boundary: + +``` +/// A method in DLL1 that wants to use a common service from DLL2 +#[ffi_function] +fn use_common_service(common: &CommonService) { + // This has at least two issues: + // - `CommonService`, or ANY type nested deep within might have + // a different type layout in DLL2, leading to immediate + // undefined behavior (UB) ⚠️ + // - `do_work()` here looks like it will be invoked in DLL2, but + // the code executed will actually come from DLL1. This means that + // `do_work()` invoked here will see a data structure coming from + // DLL2, but will use statics from DLL1 ⚠️ + common.do_work(); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-LATEST-EDITION.md b/ai-skill/skills/rust-guidelines/rules/M-LATEST-EDITION.md new file mode 100644 index 0000000..78bc2af --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-LATEST-EDITION.md @@ -0,0 +1,7 @@ +## New crates target latest edition (M-LATEST-EDITION) + +Why: access to the latest Rust features. + +When creating a new crate or workspace, set `edition` to the latest stable edition (at least `2024` at the time of writing); the `resolver` field is generally not needed. + +Using an older edition generally has no upsides for new projects, but forces you to write 'old Rust' that is less idiomatic and has worse UX edge cases. Notably, using an older edition does _not_ grant any compatibility benefits with the rest of the ecosystem. An application based on `2015` can use libraries written for `2024` just fine. diff --git a/ai-skill/skills/rust-guidelines/rules/M-LINT-OVERRIDE-EXPECT.md b/ai-skill/skills/rust-guidelines/rules/M-LINT-OVERRIDE-EXPECT.md new file mode 100644 index 0000000..cc76304 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-LINT-OVERRIDE-EXPECT.md @@ -0,0 +1,17 @@ +## Lint overrides should use `#[expect]` (M-LINT-OVERRIDE-EXPECT) + +Why: a current, tidy lint set. + +When overriding project-global lints inside a submodule or item, you should do so via `#[expect]`, not `#[allow]`. + +Expected lints emit a warning if the marked warning was not encountered, thus preventing the accumulation of stale lints. +That said, `#[allow]` lints are still useful when applied to generated code, and can appear in macros. + +Overrides should be accompanied by a `reason`: + +``` +#[expect(clippy::unused_async, reason = "API fixed, will use I/O later")] +pub async fn ping_server() { + // Stubbed out for now +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-LOG-NOT-PRINT.md b/ai-skill/skills/rust-guidelines/rules/M-LOG-NOT-PRINT.md new file mode 100644 index 0000000..66a9509 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-LOG-NOT-PRINT.md @@ -0,0 +1,5 @@ +## Production code uses telemetry, not println (M-LOG-NOT-PRINT) + +Why: diagnostics available where they are needed. + +Production code paths should emit diagnostics through the project's telemetry framework rather than via `println!` or `dbg!`. Console output is reserved for CLIs that intentionally write to stdout as their user interface. diff --git a/ai-skill/skills/rust-guidelines/rules/M-LOG-OVERHEAD.md b/ai-skill/skills/rust-guidelines/rules/M-LOG-OVERHEAD.md new file mode 100644 index 0000000..a8cf1fb --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-LOG-OVERHEAD.md @@ -0,0 +1,25 @@ +## Library telemetry does not tank performance (M-LOG-OVERHEAD) + +Why: low-overhead telemetry during diagnosis. + +Library code that emits telemetry should ensure that doing so does not meaningfully impact throughput or latency on the hot path. + +Crates offered to 3rd parties emitting logs or metrics should assume telemetry will be permanently enabled, or under load. Care should therefore be taken that the volume and overhead of emitted events is reasonable, and will not cause excessive performance degradation. + +Hot, inner loops should preferably stay free of telemetry emission entirely. If it can't be avoided, the events emitted should be lightweight and avoid allocations (e.g., `format!` string concatenation). + +``` +// Bad, logs each message and invokes allocation-based formatting. +for m in messages { + log(format!("Emitting message {}", m.id())) +} + +// Better, avoids per-message allocations. +for m in messages { + log(("Emitting message", m.id())) +} + +// Best: If possible, let telemetry users reconstruct what happened offline +log(("Processing message batch", messages.batch_id())) +for m in messages { ... } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-LOG-STRUCTURED.md b/ai-skill/skills/rust-guidelines/rules/M-LOG-STRUCTURED.md new file mode 100644 index 0000000..b35effb --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-LOG-STRUCTURED.md @@ -0,0 +1,113 @@ +## Use structured logging with message templates (M-LOG-STRUCTURED) + +Why: low-cost logging with strong filtering. + +Logging should use structured events with named properties and message templates following +the [message templates](https://messagetemplates.org/) specification. + +> **Note:** Examples use the [`tracing`](https://docs.rs/tracing/) crate's `event!` macro, +but these principles apply to any logging API that supports structured logging (e.g., `log`, +`slog`, custom telemetry systems). + +### Avoid String Formatting + +String formatting allocates memory at runtime. Message templates defer formatting until viewing time. +We recommend that message template includes all named properties for easier inspection at viewing time. + +``` +// Bad: String formatting causes allocations +tracing::info!("file opened: {}", path); +tracing::info!(format!("file opened: {}", path)); + +// Good: Message templates with named properties +event!( + name: "file.open.success", + Level::INFO, + file.path = path.display(), + "file opened: {{file.path}}", +); +``` + +> **Note**: Use the `{{property}}` syntax in message templates which preserves the literal text +> while escaping Rust's format syntax. String formatting is deferred until logs are viewed. + +### Name Your Events + +Use hierarchical dot-notation: `..` + +``` +// Bad: Unnamed events +event!( + Level::INFO, + file.path = file_path, + "file {{file.path}} processed successfully", +); + +// Good: Named events +event!( + name: "file.processing.success", // event identifier + Level::INFO, + file.path = file_path, + "file {{file.path}} processed successfully", +); +``` + +Named events enable grouping and filtering across log entries. + +### Follow OpenTelemetry Semantic Conventions + +Use [OTel semantic conventions](https://opentelemetry.io/docs/specs/semconv/) for common attributes if needed. +This enables standardization and interoperability. + +``` +event!( + name: "file.write.success", + Level::INFO, + file.path = path.display(), // Standard OTel name + file.size = bytes_written, // Standard OTel name + file.directory = dir_path, // Standard OTel name + file.extension = extension, // Standard OTel name + file.operation = "write", // Custom name + "{{file.operation}} {{file.size}} bytes to {{file.path}} in {{file.directory}} extension={{file.extension}}", +); +``` + +Common conventions: + +- HTTP: `http.request.method`, `http.response.status_code`, `url.scheme`, `url.path`, `server.address` +- File: `file.path`, `file.directory`, `file.name`, `file.extension`, `file.size` +- Database: `db.system.name`, `db.namespace`, `db.operation.name`, `db.query.text` +- Errors: `error.type`, `error.message`, `exception.type`, `exception.stacktrace` + +### Redact Sensitive Data + +Do not log plain sensitive data as this might lead to privacy and security incidents. + +``` +// Bad: Logs potentially sensitive data +event!( + name: "file.operation.started", + Level::INFO, + user.email = user.email, // Sensitive data + file.name = "license.txt", + "reading file {{file.name}} for user {{user.email}}", +); + +// Good: Redact sensitive parts +event!( + name: "file.operation.started", + Level::INFO, + user.email.redacted = redact_email(user.email), + file.name = "license.txt", + "reading file {{file.name}} for user {{user.email.redacted}}", +); +``` + +Sensitive data includes email addresses, file paths revealing user identity, filenames containing secrets or tokens, +file contents with PII, temporary file paths with session IDs and more. Consider using the [`data_privacy`](https://crates.io/crates/data_privacy) crate for consistent redaction. + +### Further Reading + +- [Message Templates Specification](https://messagetemplates.org/) +- [OpenTelemetry Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/) +- [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) diff --git a/ai-skill/skills/rust-guidelines/rules/M-MACRO-HELPERS.md b/ai-skill/skills/rust-guidelines/rules/M-MACRO-HELPERS.md new file mode 100644 index 0000000..291e35f --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MACRO-HELPERS.md @@ -0,0 +1,22 @@ +## Third party items come from hidden `_private` module (M-MACRO-HELPERS) + +Why: predictable compilation. + +When a macro expansion needs to refer to third-party items, the host crate should re-export those from a hidden module, and the macro should emit fully-qualified paths through that module rather than expecting the user's crate to depend on the third-party crate directly. + +For example, a crate `foo` requiring `bar` traits would do: + +``` +#[doc(hidden)] +pub mod _private { + pub use ::bar::Bar; +} + +pub use foo_proc::my_macro; +``` + +The `my_macro!` implementation would then rely on its presence in its emitted code: + +``` +impl ::foo::_private::Bar for MyType { ... } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-MACRO-LAST-RESORT.md b/ai-skill/skills/rust-guidelines/rules/M-MACRO-LAST-RESORT.md new file mode 100644 index 0000000..50fc23c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MACRO-LAST-RESORT.md @@ -0,0 +1,17 @@ +## Macros are a last resort (M-MACRO-LAST-RESORT) + +Why: minimal complexity. + +Macros should only be used if no other viable solution exists, compare this adage: + +> As @littlecalculist always told me, “macros are for when you run out of language”. If you still have language left — and Rust gives you a lot of language — use the language first. +> +> @pcwalton + +Macros are powerful, but come with several downsides. They + +- are magic, and it can be impossible to predict what they do, or how they do it, +- disproportionally increase compilation time in projects that otherwise don't rely on them, +- can cause subtle breakage at edition boundaries where Rust syntax and semantics can change. + +Counterintuitively, the more structurally complex the result of a macro expansion is, the worse an idea it is to use macros for that in the first place. The ideal macro makes your users go "_I know exactly what this will generate, but I don't want to write all of that by hand_". diff --git a/ai-skill/skills/rust-guidelines/rules/M-MACRO-MAIN-CRATE.md b/ai-skill/skills/rust-guidelines/rules/M-MACRO-MAIN-CRATE.md new file mode 100644 index 0000000..c2e812c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MACRO-MAIN-CRATE.md @@ -0,0 +1,15 @@ +## Macros assume main crate (M-MACRO-MAIN-CRATE) + +Why: simple macro logic. + +Procedural macros can (and should) assume they are used through their main crate and emit paths for that. + +For crates including proc macros it is common to ship them split in 3 for technical reasons: + +- `foo` - the main crate that re-exports macros from `foo_proc`, along with extra traits or types, +- `foo_proc` - facade re-exporting macros from `foo_proc_impl` with `proc-macro = true`, +- `foo_proc_impl` - the actual macro implementation and unit tests. + +In some cases there can be additional crates involved. Authors might be tempted to make `foo`, `foo_proc`, and siblings all work, resulting in complex re-export hierarchies or the use of 3rd party helpers. In reality, the minimal UX gain is usually not worth the added complexity (or compile time overhead), given the ecosystem precedent of mostly not supporting these usage modes in the first place. + +This also implies you should not attempt to support use cases where your crate is imported under a different name. diff --git a/ai-skill/skills/rust-guidelines/rules/M-MACRO-VERSION-PIN.md b/ai-skill/skills/rust-guidelines/rules/M-MACRO-VERSION-PIN.md new file mode 100644 index 0000000..75dd9df --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MACRO-VERSION-PIN.md @@ -0,0 +1,21 @@ +## Pin supporting proc macro crates (M-MACRO-VERSION-PIN) + +Why: keep generated code compatible with its library + +A crate that re-exports macros from companion proc macro crates must pin them to its own exact +version via `=x.y.z`, and each macro crate must pin its own companion crates the same way. When +publishing, those crates are counted as one crate and must be published together with the same +exact version. + +Without exact pins, a newer macro may generate code incompatible with an older version of the +crate, causing unexpected and hard-to-diagnose compilation failures in the generated code. + +M-MACRO-VERSION-PIN does not apply to independently consumed macro libraries. + +Example: + +```toml +# foo/Cargo.toml +[dependencies] +foo_macros = "=1.2.3" +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-MACROS-DONT-LIE.md b/ai-skill/skills/rust-guidelines/rules/M-MACROS-DONT-LIE.md new file mode 100644 index 0000000..6f09c9a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MACROS-DONT-LIE.md @@ -0,0 +1,23 @@ +## Macros don't lie about signatures (M-MACROS-DONT-LIE) + +Why: clarity for users and LLMs. + +Macros must not (make users) misrepresent signatures or the shape of items. + +Macros have the ability to arbitrarily rewrite token streams. They could convert structs to enums, traits to functions, or perform any other transformation imaginable. They should, however, do none of that, as the resulting code will be highly confusing and virtually impossible to predict or reason about. + +Among others, macros must not + +- visibly convert the nature of data types (e.g., structs to enums, ...), +- alter function signatures, +- convert the `async`-ness of items, +- do anything else that materially detaches _what's written_ from _what's happening_. + +``` +// Bad: Adds extra parameter and marks function `async`. Impossible to +// predict from reading code. +#[magic_transform] +fn foo() { } + +foo(token).await +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-MEM-REUSE.md b/ai-skill/skills/rust-guidelines/rules/M-MEM-REUSE.md new file mode 100644 index 0000000..9626d75 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MEM-REUSE.md @@ -0,0 +1,47 @@ +## Reuse allocations where possible (M-MEM-REUSE) + +Why: low allocation overhead and fast hot paths. + +When designing APIs you should allow users to hold onto reusable resources. Inside your code you should make use of them where available. + +The cost of repeated allocations inside hot loops can be significant, and from a user's perspective they can be invisible unless profiled: + +``` +// Bad, API design forces new allocation per element. +for id in ids { + let value = db.get(id); +} +``` + +While this style of API may exist for convenience, it should be auxiliary. Instead, the core APIs should allow users to own the underlying object and re-use it: + +``` +// Good, allows users to decide whether a new allocation is needed. +let mut value = Value::new(); +for id in ids { + db.get_in(id, &mut value); +} +``` + +The canonical method on reusable types to reuse them is `.clear()`, as can be found on many `std` items. Multiple flavors of this pattern exist. In simple cases user-owned types can hold a preexisting, reusable collection directly: + +``` +struct Value { + data: Vec +} +``` + +In heavyweight, deeply nested libraries it can be worthwhile to either pass a bump-style `Arena`, or to encapsulate one inside the user types, so it can be used throughout the call stack: + +``` +struct Query { + arena: Arena, + request: Request, + data: Vec +} + +fn client_do_work(query: &mut Query) { + let request = rewrite_request(&query.request, &query.arena); + get_in(request, &mut query.data); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-MIMALLOC-APPS.md b/ai-skill/skills/rust-guidelines/rules/M-MIMALLOC-APPS.md new file mode 100644 index 0000000..8f104a9 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MIMALLOC-APPS.md @@ -0,0 +1,22 @@ +## Use mimalloc for apps (M-MIMALLOC-APPS) + +Why: significant performance at no cost. + +Applications should set [mimalloc](https://crates.io/crates/mimalloc) as their global allocator. This usually results in notable performance +increases along allocating hot paths; we have seen up to 25% benchmark improvements. + +Changing the allocator only takes a few lines of code. Add mimalloc to your `Cargo.toml` like so: + +```toml +[dependencies] +mimalloc = { version = "0.1" } # Or later version if available +``` + +Then use it from your `main.rs`: + +``` +use mimalloc::MiMalloc; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-MOCKABLE-SYSCALLS.md b/ai-skill/skills/rust-guidelines/rules/M-MOCKABLE-SYSCALLS.md new file mode 100644 index 0000000..4d8db4b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MOCKABLE-SYSCALLS.md @@ -0,0 +1,123 @@ +## I/O and system calls are mockable (M-MOCKABLE-SYSCALLS) + +Why: testable edge cases that are otherwise hard to evoke. + +Any user-facing type doing I/O, or sys calls with side effects, should be mockable to these effects. This includes file and +network access, clocks, entropy sources and seeds, and similar. More generally, any operation that is + +- non-deterministic, +- reliant on external state, +- depending on the hardware or the environment, +- is otherwise fragile or not universally reproducible + +should be mockable. + +> ### Mocking Allocations? +> +> Unless you write kernel code or similar, you can consider allocations to be deterministic, hardware independent and practically +> infallible, thus not covered by this guideline. +> +> However, this does _not_ mean you should expect there to be unlimited memory available. While it is ok to +> accept caller provided input as-is if your library has a _reasonable_ memory complexity, memory-hungry libraries +> and code handling external input should provide bounded and / or chunking operations. + +This guideline has several implications for libraries, they + +- should not perform ad-hoc I/O, i.e., call `read("foo.txt")` +- should not rely on non-mockable I/O and sys calls +- should not create their own I/O or sys call _core_ themselves +- should not offer `MyIoLibrary::default()` constructors + +Instead, libraries performing I/O and sys calls should either accept some I/O _core_ that is mockable already, or provide mocking functionality themselves: + +``` +let lib = Library::new_runtime(runtime_io); // mockable I/O functionality passed in +let (lib, mock) = Library::new_mocked(); // supports inherent mocking +``` + +Libraries supporting inherent mocking should implement it as follows: + +``` +pub struct Library { + some_core: LibraryCore // Encapsulates syscalls, I/O, ... compare below. +} + +impl Library { + pub fn new() -> Self { ... } + pub fn new_mocked() -> (Self, MockCtrl) { ... } +} +``` + +Behind the scenes, `LibraryCore` is a non-public enum, similar to [M-RUNTIME-ABSTRACTED], that either dispatches +calls to the respective sys call, or to an mocking controller. + +``` +// Dispatches calls either to the operating system, or to a +// mocking controller. +enum LibraryCore { + Native, + + #[cfg(feature = "test-util")] + Mocked(mock::MockCtrl) +} + +impl LibraryCore { + // Some function you'd forward to the operating system. + fn random_u32(&self) { + match self { + Self::Native => unsafe { os_random_u32() } + Self::Mocked(m) => m.random_u32() + } + } +} + + +#[cfg(feature = "test-util")] +mod mock { + // This follows the M-SERVICES-CLONE pattern, so both `LibraryCore` and + // the user can hold on to the same `MockCtrl` instance. + pub struct MockCtrl { + inner: Arc + } + + // Implement required logic accordingly, usually forwarding to + // `MockCtrlInner` below. + impl MockCtrl { + pub fn set_next_u32(&self, x: u32) { ... } + pub fn random_u32(&self) { ... } + } + + // Contains actual logic, e.g., the next random number we should return. + struct MockCtrlInner { + next_call: u32 + } +} +``` + +Runtime-aware libraries already build on top of the [M-RUNTIME-ABSTRACTED] pattern should extend their runtime enum instead: + +``` +enum Runtime { + #[cfg(feature="tokio")] + Tokio(tokio::Tokio), + + #[cfg(feature="smol")] + Smol(smol::Smol) + + #[cfg(feature="test-util")] + Mock(mock::MockCtrl) +} +``` + +As indicated above, most libraries supporting mocking should not accept mock controllers, but return them via parameter tuples, +with the first parameter being the library instance, the second the mock controller. This is to prevent state ambiguity if multiple +instances shared a single controller: + +``` +impl Library { + pub fn new_mocked() -> (Self, MockCtrl) { ... } // good + pub fn new_mocked_bad(&mut MockCtrl) -> Self { ... } // prone to misuse +} +``` + +[M-RUNTIME-ABSTRACTED]: https://microsoft.github.io/rust-guidelines/guidelines/libs/ux/#M-RUNTIME-ABSTRACTED diff --git a/ai-skill/skills/rust-guidelines/rules/M-MODULE-DOCS.md b/ai-skill/skills/rust-guidelines/rules/M-MODULE-DOCS.md new file mode 100644 index 0000000..425e260 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MODULE-DOCS.md @@ -0,0 +1,33 @@ +## Has comprehensive module documentation (M-MODULE-DOCS) + +Why: easy API docs navigation. + +Any public library module must have `//!` module documentation, and the first sentence must follow [M-DOC-FIRST-SENTENCE]. + +``` +pub mod ffi { + //! Contains FFI abstractions. + + pub struct String {}; +} +``` + +The rest of the module documentation should be comprehensive, i.e., cover the most relevant technical aspects of the contained items, including + +- what the module contains +- when it should be used, possibly when not +- examples +- subsystem specifications (e.g., `std::fmt` [also describes its formatting language](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-parameters)) +- observable side effects, including what guarantees are made about these, if any +- relevant implementation details, e.g., the used system APIs + + Great examples include: + +- [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html) +- [`std::pin`](https://doc.rust-lang.org/stable/std/pin/index.html) +- [`std::option`](https://doc.rust-lang.org/stable/std/option/index.html) + +This does not mean every module should contain all of these items. But if there is something to say about the interaction of the contained types, +their module documentation is the right place. + +[M-DOC-FIRST-SENTENCE]: https://microsoft.github.io/rust-guidelines/guidelines/docs/#M-DOC-FIRST-SENTENCE diff --git a/ai-skill/skills/rust-guidelines/rules/M-MSRV.md b/ai-skill/skills/rust-guidelines/rules/M-MSRV.md new file mode 100644 index 0000000..00266f5 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-MSRV.md @@ -0,0 +1,9 @@ +## MSRV is conservatively updated (M-MSRV) + +Why: modern features with stability for users. + +A Minimum Supported Rust Version (MSRV) should be set when libraries are first created. It can be updated as new Rust features are needed, but should be kept a few versions behind the most recent compiler release. + +The ecosystem expectation is that projects are compiled with a _reasonably modern_ Rust compiler. + +Bumping MSRV therefore does not require a major release, but can be handled through a minor update (e.g., `1.3` to `1.4`). In fact, any project depending on 3rd party crates is already inherently bound to this contract; forcing a major version bump will not confer any benefits, but could possibly bifurcate downstream dependencies. diff --git a/ai-skill/skills/rust-guidelines/rules/M-NO-GLOB-REEXPORTS.md b/ai-skill/skills/rust-guidelines/rules/M-NO-GLOB-REEXPORTS.md new file mode 100644 index 0000000..bf149fb --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-NO-GLOB-REEXPORTS.md @@ -0,0 +1,30 @@ +## Don't glob re-export items (M-NO-GLOB-REEXPORTS) + +Why: a deliberate public surface. + +Don't `pub use foo::*` from other modules, especially not from other crates. You might accidentally export more than you want, +and globs are hard to review in PRs. Re-export items individually instead: + +``` +pub use foo::{A, B, C}; +``` + +Glob exports are permissible for technical reasons, like doing platform specific re-exports from a set of HAL (hardware abstraction layer) modules: + +``` +#[cfg(target_os = "windows")] +mod windows { /* ... */ } + +#[cfg(target_os = "linux")] +mod linux { /* ... */ } + +// Acceptable use of glob re-exports, this is a common pattern +// and it is clear everything is just forwarded from a single +// platform. + +#[cfg(target_os = "windows")] +pub use windows::*; + +#[cfg(target_os = "linux")] +pub use linux::*; +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-NO-META-DESIGN-DOCUMENTATION.md b/ai-skill/skills/rust-guidelines/rules/M-NO-META-DESIGN-DOCUMENTATION.md new file mode 100644 index 0000000..9da733e --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-NO-META-DESIGN-DOCUMENTATION.md @@ -0,0 +1,20 @@ +## Avoid meta design documentation (M-NO-META-DESIGN-DOCUMENTATION) + +Why: docs focused on what is relevant to users. + +Crate and module documentation must be free of meta design narratives that were only relevant during the creation of a crate. In other words, it is the end-state that is to be documented, not the design journey. + +Agents frequently produce sections that describe how a change was designed, "why we picked X over Y" essays, and design journals inside user-facing documentation. These artifacts might be interesting diagnostics while working on the project, but they are mostly meaningless to end users. + +For example, an agent might append a self-report like this, summarizing which guidelines it claims to have followed: + +```text +| Rule | Applied | Where | +| --- | :---: | --- | +| M-SHORT-NAMES | âś… | Shortened method names across the data-access and HTTP handler layers. | +| M-WEASEL-WORDS | âś… | Removed weasel words from type and field names throughout the public API. | +| M-PUBLIC-DISPLAY | âś… | Added `Display` impls for all user-facing identifier and error types. | +| M-ASYNC-FN | âś… | Migrated I/O-facing APIs from `impl Future` returns to `async fn`. | +``` + +This kind of content describes process, not behaviour, and goes stale over time. That said, it is of course perfectly reasonable to have a _Design Principles_ or similar section in the project's README, that on a high level describes the enduring architectural goals that are relevant to end users (e.g., a crate being allocation free, having an OSI architecture, or being designed with `#[no_std]` in mind). diff --git a/ai-skill/skills/rust-guidelines/rules/M-NO-PRELUDE.md b/ai-skill/skills/rust-guidelines/rules/M-NO-PRELUDE.md new file mode 100644 index 0000000..051934c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-NO-PRELUDE.md @@ -0,0 +1,25 @@ +## Don't define preludes (M-NO-PRELUDE) + +Why: a clean namespace and reliable downstream builds. + +Crates must not define a `prelude` or any namespace intended to be imported as `use foo::*`. + +While the Rust Standard Library successfully uses [preludes](https://doc.rust-lang.org/std/prelude/index.html) to define edition items, preludes in crates cause more harm than good. Given today's IDE support they are not needed, and once multiple preludes are used from different crates there is potential for conflicts: + +``` +use foo::prelude::*; +use bar::prelude::*; +use baz::prelude::*; + +_ = Client::new(); + +// error[E0659]: `Client` is ambiguous +// --> src/lib.rs:17:13 +// | +// 17 | _ = Client; +// | ^^^^^^ ambiguous name +// | +// = note: ambiguous because of multiple glob imports of a name in the same module +``` + +Preludes in particular do not resolve bad module design. If it looks like a prelude would make the crate easier to use or understand, this is almost always an indication that the existing module system needs restructuring, see [M-BALANCED-MODULES](M-BALANCED-MODULES.md). diff --git a/ai-skill/skills/rust-guidelines/rules/M-OOBE.md b/ai-skill/skills/rust-guidelines/rules/M-OOBE.md new file mode 100644 index 0000000..e3c5caf --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-OOBE.md @@ -0,0 +1,63 @@ +## Libraries work out of the box (M-OOBE) + +Why: easy adoption across the Rust ecosystem. + +Libraries must _just work_ on all supported platforms, with the exception of libraries that are expressly platform or target specific. + +Rust crates often come with dozens of dependencies, applications with 100's. Users expect `cargo build` and `cargo install` +to _just work_. Consider this installation of `bat` that pulls in ~250 dependencies: + +```text +Compiling writeable v0.5.5 +Compiling strsim v0.11.1 +Compiling litemap v0.7.5 +Compiling crossbeam-utils v0.8.21 +Compiling icu_properties_data v1.5.1 +Compiling ident_case v1.0.1 +Compiling once_cell v1.21.3 +Compiling icu_normalizer_data v1.5.1 +Compiling fnv v1.0.7 +Compiling regex-syntax v0.8.5 +Compiling anstyle v1.0.10 +Compiling vcpkg v0.2.15 +Compiling utf8parse v0.2.2 +Compiling aho-corasick v1.1.3 +Compiling utf16_iter v1.0.5 +Compiling hashbrown v0.15.2 +Building [==> ] 29/251: icu_locid_transform_data, serde, winnow, indexma... +``` + +This compilation, like practically all other applications and libraries, will _just work_. + +While there are tools targeting specific functionality (e.g., a Wayland compositor) or platform crates like +`windows`; unless a crate is _obviously_ platform specific, the expectation is that it will otherwise _just work_. + +This means crates must build, ultimately + +- [ ] on all [Tier 1 platforms](https://doc.rust-lang.org/rustc/platform-support.html),1 and +- [ ] without any additional prerequisites beyond `cargo` and `rust`.2 + + + +1 It is ok to not support Tier 1 platforms "for now", but abstractions must be present so support can easily be extended. This is usually +done by introducing an internal `HAL` ([Hardware Abstraction Layer](https://en.wikipedia.org/wiki/HAL_(software))) module with a `dummy` fallback target.; +2 A default Rust installation will also have `cc` and a linker present. + + + +In particular, non-platform crates must not, by default, require the user to install additional tools, or expect environment variables +to compile. If tools were somehow needed (like the generation of Rust from `.proto` files) these tools should be run as part of the +publishing workflow or earlier, and the resulting artifacts (e.g., `.rs` files) be contained inside the published crate. + +If a dependency is known to be platform specific, the parent must use conditional (platform) compilation or opt-in feature gates. + +> ** Libraries are Responsible for Their Dependencies.** +> +> Imagine you author a `Copilot` crate, which in turn uses an `HttpClient`, which in turn depends on a `perl` script to compile. +> +> Then every one of your users, and your user's users, and everyone above, would need to install Perl to compile _their_ crate. In large projects you would +> have 100's of people who don't know or don't care about your library or Perl, encounter a cryptic compilation error, and now have to figure out how to +> install it on their system. +> +> In practical terms, such behavior is largely a self-inflicted death sentence in the open source space, since the moment alternatives +> are available, people will switch to those that _just work_. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PANIC-CONTINUATION.md b/ai-skill/skills/rust-guidelines/rules/M-PANIC-CONTINUATION.md new file mode 100644 index 0000000..a6ad32d --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PANIC-CONTINUATION.md @@ -0,0 +1,31 @@ +## Panic continuation is last resort (M-PANIC-CONTINUATION) + +Why: state integrity and freedom from subtle bugs. + +Panic recovery via `catch_unwind()` is a matter of last resort and must generally be followed by a controlled application restart. + +Panics indicate the program has reached an unrecoverable state (compare [M-PANIC-IS-STOP](M-PANIC-IS-STOP.md) and [M-PANIC-ON-BUG](M-PANIC-ON-BUG.md)). Library code in particular should not attempt to catch a panic and continue execution, as there is a risk of observing otherwise impossible state: + +``` +thread_local! { + static ALWAYS_EQUAL: RefCell<(i32, i32)> = RefCell::new((0, 0)); +} + +fn main() { + let _ = panic::catch_unwind(|| { + ALWAYS_EQUAL.with_borrow_mut(|p| { + p.0 += 1; + panic!("Assume some user-provided closure failed here"); + p.1 += 1; + }); + }); + + ALWAYS_EQUAL.with_borrow(|p| { + assert_eq!(p.0, p.1); // Broken! + }); +} +``` + +Although the example above is slightly contrived, the side effects and interactions of a caught panic can be harder to identify, can have wide blast radius, and be subtle. + +Systems where many unrelated tasks are in flight (e.g., server request handlers) can use `catch_unwind` on a per-request basis, but should still promote an application restart after a request handler caused a panic. The purpose of `catch_unwind` here is not to continue execution indefinitely, but to allow all other requests to gracefully finish. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PANIC-IS-STOP.md b/ai-skill/skills/rust-guidelines/rules/M-PANIC-IS-STOP.md new file mode 100644 index 0000000..ea787ff --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PANIC-IS-STOP.md @@ -0,0 +1,28 @@ +## Panic means 'stop the program' (M-PANIC-IS-STOP) + +Why: soundness and predictability. + +Panics are not exceptions. Instead, they suggest immediate program termination. + +Although your code must be [_minimally_ panic-safe](https://doc.rust-lang.org/nomicon/exception-safety.html) (i.e., a survived panic may not lead to +undefined state), invoking a panic means _this program should stop now_. It is not valid to: + +- use panics to communicate (errors) upstream, +- use panics to handle self-inflicted error conditions, +- assume panics will be caught, even by your own code. + +For example, if the application calling you is compiled with a `Cargo.toml` containing + +```toml +[profile.release] +panic = "abort" +``` + +then any invocation of panic will cause an otherwise functioning program to needlessly abort. Valid reasons to panic are: + +- when encountering a programming error, e.g., `x.expect("must never happen")`, +- anything invoked from const contexts, e.g., `const { foo.unwrap() }`, +- when user requested, e.g., providing an `unwrap()` method yourself, +- when encountering a poison, e.g., by calling `unwrap()` on a lock result (a poisoned lock signals another thread has panicked already). + +Any of those are directly or indirectly linked to programming errors. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PANIC-MESSAGE.md b/ai-skill/skills/rust-guidelines/rules/M-PANIC-MESSAGE.md new file mode 100644 index 0000000..2d457ee --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PANIC-MESSAGE.md @@ -0,0 +1,17 @@ +## Custom panics have a helpful message (M-PANIC-MESSAGE) + +Why: faster bug diagnosis. + +When code panics intentionally (via `panic!`, `assert!`, `unreachable!`, `todo!`, or similar), a message must be present to clearly state what went wrong and, where applicable, include relevant values. + +``` +// Bad, the panic gives the developer little to act on. +assert!(buffer.len() >= HEADER_SIZE); + +// Good, message contains reason and actual values. +assert!(buffer.len() >= HEADER_SIZE, "buffer too small for header: got {} bytes, need {HEADER_SIZE}", buffer.len()); +``` + +Messages related to API misuse should be useful to the end user. Messages indicating bugs should be helpful to you-as-the-author, or whoever maintains the project after you, to quickly identify the underlying cause. + +Panic messages in tests are not generally needed. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PANIC-ON-BUG.md b/ai-skill/skills/rust-guidelines/rules/M-PANIC-ON-BUG.md new file mode 100644 index 0000000..0ef6fda --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PANIC-ON-BUG.md @@ -0,0 +1,41 @@ +## Detected programming bugs are panics, not errors (M-PANIC-ON-BUG) + +Why: tractable error handling and runtime consistency. + +As an extension of [M-PANIC-IS-STOP] above, when an unrecoverable programming error has been +detected, libraries and applications must panic, i.e., request program termination. + +In these cases, no `Error` type should be introduced or returned, as any such error could not be acted upon at runtime. + +Contract violations, i.e., the breaking of invariants either within a library or by a caller, are programming errors and must therefore panic. + +However, what constitutes a violation is situational. APIs are not expected to go out of their way to detect them, as such +checks can be impossible or expensive. Encountering `must_be_even == 3` during an already existing check clearly warrants +a panic, while a function `parse(&str)` clearly must return a `Result`. If in doubt, we recommend you take inspiration from the standard library. + +``` +// Generally, a function with bad parameters must either +// - Ignore a parameter and/or return the wrong result +// - Signal an issue via Result or similar +// - Panic +// If in this `divide_by` we see that y == 0, panicking is +// the correct approach. +fn divide_by(x: u32, y: u32) -> u32 { ... } + +// However, it can also be permissible to omit such checks +// and return an unspecified (but not an undefined) result. +fn divide_by_fast(x: u32, y: u32) -> u32 { ... } + +// Here, passing an invalid URI is not a contract violation. +// Since parsing is inherently fallible, a Result must be returned. +fn parse_uri(s: &str) -> Result { }; + +``` + +> ### Make it 'Correct by Construction' +> +> While panicking on a detected programming error is the 'least bad option', your panic might still ruin someone's day. +> For any user input or calling sequence that would otherwise panic, you should also explore if you can use the type +> system to avoid panicking code paths altogether. + +[M-PANIC-IS-STOP]: M-PANIC-IS-STOP.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-PARAMETER-CONSISTENCY.md b/ai-skill/skills/rust-guidelines/rules/M-PARAMETER-CONSISTENCY.md new file mode 100644 index 0000000..f5b50c9 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PARAMETER-CONSISTENCY.md @@ -0,0 +1,23 @@ +## Parameter ordering is consistent (M-PARAMETER-CONSISTENCY) + +Why: low development friction. + +When the same conceptual parameters appear in multiple functions (within a crate or across crates in the same ecosystem), they should appear in the same order everywhere: + +- important or call-specific parameters should generally go first, +- ubiquitous parameters rather go last (e.g., `&logger`), +- closures always go last (functions should not accept more than one closure). + +``` +// Bad, the order of `user_id` and `tenant_id` flips between functions, and +// the logger sometimes appears first, sometimes last. +fn create_user(logger: &Logger, user_id: UserId, tenant_id: TenantId) -> Result<()> { ... } +fn delete_user(tenant_id: TenantId, user_id: UserId, logger: &Logger) -> Result<()> { ... } +fn rename_user(user_id: UserId, new_name: &str, tenant_id: TenantId, logger: &Logger) -> Result<()> { ... } + +// Good, call-specific parameters first in a consistent order, ubiquitous +// `logger` always last. +fn create_user(tenant_id: TenantId, user_id: UserId, logger: &Logger) -> Result<()> { ... } +fn delete_user(tenant_id: TenantId, user_id: UserId, logger: &Logger) -> Result<()> { ... } +fn rename_user(tenant_id: TenantId, user_id: UserId, new_name: &str, logger: &Logger) -> Result<()> { ... } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPL.md b/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPL.md new file mode 100644 index 0000000..559fbb2 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPL.md @@ -0,0 +1,30 @@ +## Proc macros should have separate impl crate incl. tests (M-PROC-IMPL) + +Why: thoroughly testable proc macros. + +Proc macros should be thin shims inside some `foo_proc` crate that delegate to a separate, regular library crate, usually called `foo_proc_impl`, which contains the actual token-stream transformation logic and its tests. + +As proc macro crates are special, testing them from `foo_proc` usually requires workarounds for unit and snapshot tests. Instead, consider having a `foo_proc_impl` crate: + +``` +use proc_macro2::TokenStream; + +pub fn my_macro(attr: TokenStream, item: TokenStream) -> TokenStream { ... } +``` + +These can come with regular [insta](https://insta.rs/) or similar snapshot tests, and are then exported as genuine proc macros via a `foo_proc` crate like so: + +``` +#[proc_macro_attribute] +pub fn my_macro(attr: TokenStream, item: TokenStream) -> TokenStream { + foo_proc_impl::my_macro(attr.into(), item.into()).into() +} +``` + +The macros are then re-exported from the core crate: + +``` +pub use foo_proc::my_macro; +``` + +Inside the core crate, we also recommend adding [trybuild](https://docs.rs/trybuild/latest/trybuild/) UI tests with negative examples to ensure consistent error messages. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPLIED-ITEMS.md b/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPLIED-ITEMS.md new file mode 100644 index 0000000..c3184ac --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PROC-IMPLIED-ITEMS.md @@ -0,0 +1,50 @@ +## Proc macros don't produce implied or hidden items (M-PROC-IMPLIED-ITEMS) + +Why: clear errors and correct hygiene and visibility. + +Macros should not define magic types on their own, in particular not public ones, or ones that don't rely on namespace tricks. + +Some macros want to define types, for example + +``` +#[my_macro] +struct UserType; + +// would expand to + +struct UserType; +struct ExtraType; +impl UserType { + fn foo() -> ExtraType { ... }; +} +``` + +This is almost always a bad idea for several reasons: + +- they can conflict with existing user-defined types inside the same module, +- if done naively, they can conflict with other expansions of the same macro, +- they can clash with the user's naming conventions, +- they are invisible at source code level and easily forgotten to be re-exported where needed. + +While it is possible for users to work around these limitations somewhat, these are paper cuts your users will have to deal with, possibly months after the fact when refactoring otherwise unrelated code. + +Note that there is one exception to this rule that has generally acceptable UX, the overloaded use of [namespaces](https://doc.rust-lang.org/reference/names/namespaces.html) made prominent by crates like Rocket: + +``` +#[my_macro] +fn foo() { ... } + +// would expand to + +fn foo() { ... } + +struct foo; +impl SomeTrait for foo { ... } +``` + +Here a new type `foo` is introduced with the same name as the function `foo`. Due to Rust's namespace rules they can co-exist and are automatically re-exported with their parent, and due to [Rust's casing rules (C-CASE)](https://rust-lang.github.io/api-guidelines/naming.html#casing-conforms-to-rfc-430-c-case) these are highly unlikely to clash with user-defined types. However, they would still not make for a pretty _public_ type, and are therefore mainly used inside root crates to define request handlers or FFI functions. + +> ### Namespaces != Modules +> +> Namespaces in Rust have nothing to do with namespaces in other languages. A namespace in C# is approximately a module in Rust. A namespace in Rust +is an esoteric property of names (e.g., `fn foo`, `struct Bar {}`, `moo!`) that decides which 'naming bucket' it lives in inside a module. diff --git a/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DEBUG.md b/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DEBUG.md new file mode 100644 index 0000000..3288bba --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DEBUG.md @@ -0,0 +1,35 @@ +## Public types are Debug (M-PUBLIC-DEBUG) + +Why: easy debugging without leaking sensitive data. + +All public types exposed by a crate should implement `Debug`. Most types can do so via `#[derive(Debug)]`: + +``` +#[derive(Debug)] +struct Endpoint(String); +``` + +Types designed to hold sensitive data should also implement `Debug`, but do so via a custom implementation. +This implementation must employ unit tests to ensure sensitive data isn't actually leaked, and will not be in the future. + +``` +use std::fmt::{Debug, Formatter}; + +struct UserSecret(String); + +impl Debug for UserSecret { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "UserSecret(...)") + } +} + +#[test] +fn test() { + let key = "552d3454-d0d5-445d-ab9f-ef2ae3a8896a"; + let secret = UserSecret(key.to_string()); + let rendered = format!("{:?}", secret); + + assert!(rendered.contains("UserSecret")); + assert!(!rendered.contains(key)); +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DISPLAY.md b/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DISPLAY.md new file mode 100644 index 0000000..072b590 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-PUBLIC-DISPLAY.md @@ -0,0 +1,13 @@ +## Public types meant to be read are Display (M-PUBLIC-DISPLAY) + +Why: usability. + +If your type is expected to be read by upstream consumers, be it developers or end users, it should implement `Display`. This in particular includes: + +- Error types, which are mandated by `std::error::Error` to implement `Display` +- Wrappers around string-like data + +Implementations of `Display` should follow Rust customs; this includes rendering newlines and escape sequences. +The handling of sensitive data outlined in [M-PUBLIC-DEBUG] applies analogously. + +[M-PUBLIC-DEBUG]: M-PUBLIC-DEBUG.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-REGULAR-FN.md b/ai-skill/skills/rust-guidelines/rules/M-REGULAR-FN.md new file mode 100644 index 0000000..1efbc42 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-REGULAR-FN.md @@ -0,0 +1,42 @@ +## Prefer regular over associated functions (M-REGULAR-FN) + +Why: readability. + +Associated functions should primarily be used for instance creation, not general purpose computation. + +In contrast to some OO languages, regular functions are first-class citizens in Rust and need no module or _class_ to host them. Functionality that +does not clearly belong to a receiver should therefore not reside in a type's `impl` block: + +``` +struct Database {} + +impl Database { + // Ok, associated function creates an instance + fn new() -> Self {} + + // Ok, regular method with `&self` as receiver + fn query(&self) {} + + // Not ok, this function is not directly related to `Database`, + // it should therefore not live under `Database` as an associated + // function. + fn check_parameters(p: &str) {} +} + +// As a regular function this is fine +fn check_parameters(p: &str) {} +``` + +Regular functions are more idiomatic, and reduce unnecessary noise on the caller side. Associated trait functions are perfectly idiomatic though: + +``` +pub trait Default { + fn default() -> Self; +} + +struct Foo; + +impl Default for Foo { + fn default() -> Self { Self } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-RUST-SHAPED.md b/ai-skill/skills/rust-guidelines/rules/M-RUST-SHAPED.md new file mode 100644 index 0000000..6f0ba19 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-RUST-SHAPED.md @@ -0,0 +1,21 @@ +## Rust code solves Rust problems (M-RUST-SHAPED) + +Why: idiomatic code. + +When (automatically) porting C#, Java, C++, or similar code to Rust, technical constructs must not be copied 1-on-1. + +It is prudent to separate domain aspects from language aspects. Domain aspects address business problems. An algorithm to compute prime numbers or logic for processing a customer table can (and should) work the same when translating between languages. + +However, many patterns exist to solve problems particular to the ecosystem they stem from. The Rust ecosystem has its own problems, and these need to be addressed by idioms that work for Rust. These include + +- error handling, +- management of tasks and threads, +- component abstractions and their lifetimes, +- ownership of parameters, +- the absence of 'object-oriented' programming, +- structural differences between interfaces and traits, +- and many others. + +While some language constructs simply don't translate at all (e.g., compared to C#, Rust does not have any meaningful reflection), others are deceptively similar and might only bite months down the line (e.g., statics, compare [M-AVOID-STATICS](M-AVOID-STATICS.md)). + +As a rule of thumb, structs and their methods can have vaguely similar names, flows, inputs and outputs, as far as their business functionality is concerned. However, any striking technical similarity between Rust and { C#, Java, Python, ... } implementations is indicative of deeper architectural problems; a `throw_if_null()` never makes sense. diff --git a/ai-skill/skills/rust-guidelines/rules/M-SERVICES-CLONE.md b/ai-skill/skills/rust-guidelines/rules/M-SERVICES-CLONE.md new file mode 100644 index 0000000..7b0d6e6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SERVICES-CLONE.md @@ -0,0 +1,57 @@ +## Services are Clone (M-SERVICES-CLONE) + +Why: composable sharing of common services. + +Heavyweight _service_ types and 'thread singletons' should implement shared-ownership `Clone` semantics, including any type you expect to be used from your `Application::init`. + +Per thread, users should essentially be able to create a single resource handler instance, and have it reused by other handlers on the same thread: + +``` +impl ThreadLocal for MyThreadState { + fn init(...) -> Self { + + // Create common service instance possibly used by many. + let common = ServiceCommon::new(); + + // Users can freely pass `common` here multiple times + let service_1 = ServiceA::new(&common); + let service_2 = ServiceA::new(&common); + + Self { ... } + } +} +``` + +Services then simply clone their dependency and store a new _handle_, as if `ServiceCommon` were a shared-ownership smart pointer: + +``` +impl ServiceA { + pub fn new(common: &ServiceCommon) -> Self { + // If we only need to access `common` from `new` we don't have + // to store it. Otherwise, make a clone we store in `Self`. + let common = common.clone(); + } +} +``` + +Under the hood this `Clone` should **not** create a fat copy of the entire service. Instead, it should follow the `Arc` pattern: + +``` +// Actual service containing core logic and data. +struct ServiceCommonInner {} + +#[derive(Clone)] +pub ServiceCommon { + inner: Arc +} + +impl ServiceCommon { + pub fn new() { + Self { inner: Arc::new(ServiceCommonInner::new()) } + } + + // Method forwards ... + pub fn foo(&self) { self.inner.foo() } + pub fn bar(&self) { self.inner.bar() } +} +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-SHORT-NAMES.md b/ai-skill/skills/rust-guidelines/rules/M-SHORT-NAMES.md new file mode 100644 index 0000000..b1d1991 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SHORT-NAMES.md @@ -0,0 +1,11 @@ +## Names of items are short (M-SHORT-NAMES) + +Why: idiomatic code. + +The Rust convention that item identifiers are short should be followed: + +- identifiers should not compound more than 2 short words (`AppConfig` over `GlobalApplicationConfig`), +- module or crate information shouldn't be baked into prefixes (`foo::Id` over `foo::FooId`), in particular when the direct 'super' item is sufficiently descriptive - in these cases users are expected to disambiguate items locally via qualifiers where needed (`fn convert(foo::Id) -> bar::Id`). +- abbreviations are preferred (`CallbackFn` over `CallbackFunction`), + +Any of these rules can be broken where it makes local sense, but on a per-crate bases these exceptions should be _exceptional_ and well motivated. diff --git a/ai-skill/skills/rust-guidelines/rules/M-SHRINK-TO-FIT.md b/ai-skill/skills/rust-guidelines/rules/M-SHRINK-TO-FIT.md new file mode 100644 index 0000000..84257fe --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SHRINK-TO-FIT.md @@ -0,0 +1,20 @@ +## Shrink collections to fit after building (M-SHRINK-TO-FIT) + +Why: a minimal memory footprint. + +Where large, long-lived, growable collections such as `Vec` or `String` were built without an exact size reservation (compare [M-INITIAL-CAPACITY](M-INITIAL-CAPACITY.md)), the resulting collection should be shrunk via `shrink_to_fit` before storing it. + +Many Rust collections grow by powers of two when iteratively adding elements. In the worst case a collection might therefore use ~2x of its needed memory. + +``` +// Bad, long lived object might end up using 2x needed memory. +let mut long_lived = Vec::new(); +for x in large_iter { + long_lived.push(x); +} + +// Good, frees up extra memory. +long_lived.shrink_to_fit(); +``` + +Note that this does not apply to conversions done via `into_boxed_*` and friends (compare [M-BOX-DST](M-BOX-DST.md)), as these generally shrink before converting already. diff --git a/ai-skill/skills/rust-guidelines/rules/M-SIMPLE-ABSTRACTIONS.md b/ai-skill/skills/rust-guidelines/rules/M-SIMPLE-ABSTRACTIONS.md new file mode 100644 index 0000000..5b6dccc --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SIMPLE-ABSTRACTIONS.md @@ -0,0 +1,60 @@ +## Abstractions don't visibly nest (M-SIMPLE-ABSTRACTIONS) + +Why: low cognitive load and a good out-of-the-box UX. + +When designing your public types and primary API surface, avoid exposing nested or complex parametrized types to your users. + +While powerful, type parameters introduce a cognitive load, even more so if the involved traits are crate-specific. Type parameters +become infectious to user code holding on to these types in their fields, often come with complex trait hierarchies on their own, and +might cause confusing error messages. + +From the perspective of a user authoring `Foo`, where the other structs come from your crate: + +``` +struct Foo { + service: Service // Great + service: Service // Acceptable + service: Service> // Bad + + list: List> // Great, `List` is simple container, + // other types user provided. + + matrix: Matrix4x4 // Great + matrix: Matrix4x4 // Still ok + matrix: Matrix, Const<4>, ArrayStorage> // ?!? +} +``` + +_Visible_ type parameters should be avoided in _service-like_ types (i.e., types mainly instantiated once per thread / application that are often passed +as dependencies), in particular if the nestee originates from the same crate as the service. + +Containers, smart-pointers and similar data structures obviously must expose a type parameter, e.g., `List` above. Even then, care should +be taken to limit the number and nesting of parameters. + +To decide whether type parameter nesting should be avoided, consider these factors: + +- Will the type be **named** by your users? + - Service-level types are always expected to be named (e.g., `Library`), + - Utility types, such as the many [`std::iter`](https://doc.rust-lang.org/stable/std/iter/index.html) types like `Chain`, `Cloned`, `Cycle`, are not + expected to be named. +- Does the type primarily compose with non-user types? +- Do the used type parameters have complex bounds? +- Do the used type parameters affect inference in other types or functions? + +The more of these factors apply, the bigger the cognitive burden. + +As a rule of thumb, primary service API types should not nest _on their own volition_, and if they do, only 1 level deep. In other words, these +APIs should not require users having to deal with an `Foo>`. However, if `Foo` users want to bring their own `A>` as `T` they +should be free to do so. + +> ### Type Magic for Better UX? +> +> The guideline above is written with 'bread-and-butter' types in mind you might create during _normal_ development activity. Its intention is to +> reduce friction users encounter when working with your code. +> +> However, when designing API patterns and ecosystems at large, there might be valid reasons to introduce intricate type magic to overall _lower_ +> the cognitive friction involved, [Bevy's ECS](https://docs.rs/bevy_ecs/latest/bevy_ecs/) or +> [Axum's request handlers](https://docs.rs/axum/latest/axum/handler/trait.Handler.html) come to mind. +> +> The threshold where this pays off is high though. If there is any doubt about the utility of your creative use of generics, your users might be +> better off without them. diff --git a/ai-skill/skills/rust-guidelines/rules/M-SINGLE-ITEM-PATH.md b/ai-skill/skills/rust-guidelines/rules/M-SINGLE-ITEM-PATH.md new file mode 100644 index 0000000..d4484a6 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SINGLE-ITEM-PATH.md @@ -0,0 +1,31 @@ +## Items are only visible through one path (M-SINGLE-ITEM-PATH) + +Why: a single, clutter-free path to each type. + +Public items within a crate should be reachable only through one path. For example some `crate::db::Connection` should not also be visible as `crate::Connection`: + +``` +// Not OK +pub mod db { + pub struct Connection; +} + +pub use db::Connection; +``` + +This rule is often violated by agents creating or refactoring large code bases over several iterations. In an attempt to _simplify_ their task, they re-export items under multiple paths, often previous ones from before some change, instead of cleanly redesigning structures where it makes sense. + +Note this only targets the duplication of user-facing items. Within a crate it is acceptable (and often unavoidable) to see the same item multiple times as export trees are constructed: + +``` +// OK +pub(crate) mod db { + pub struct Connection; +} + +pub use db::Connection; +``` + +Similarly, re-exports of foreign items are not covered by this rule, although they should follow [M-FOREIGN-REEXPORTS](M-FOREIGN-REEXPORTS.md). + +Likewise, this rule also does not apply to public-but-hidden `_private` modules needed by macros, compare [M-MACRO-HELPERS](M-MACRO-HELPERS.md). diff --git a/ai-skill/skills/rust-guidelines/rules/M-SMALLER-CRATES.md b/ai-skill/skills/rust-guidelines/rules/M-SMALLER-CRATES.md new file mode 100644 index 0000000..c7ab126 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SMALLER-CRATES.md @@ -0,0 +1,36 @@ +## If in doubt, split the crate (M-SMALLER-CRATES) + +Why: fast compile times and good modularity. + +You should err on the side of having too many crates rather than too few, as this leads to dramatic compile time improvements—especially +during the development of these crates—and prevents cyclic component dependencies. + +Essentially, if a submodule can be used independently, its contents should be moved into a separate crate. + +Performing this crate split may cause you to lose access to some `pub(crate)` fields or methods. In many situations, this is a desirable +side-effect and should prompt you to design more flexible abstractions that would give your users similar affordances. + +In some cases, it is desirable to re-join individual crates back into a single _umbrella crate_, such as when dealing with proc macros, or runtimes. +Functionality split for technical reasons (e.g., a `foo_proc` proc macro crate) should always be re-exported. Otherwise, re-exports should be used sparingly. + +> ### Features vs. Crates +> +> As a rule of thumb, crates are for items that can reasonably be used on their own. Features should unlock extra functionality that +> can't live on its own. In the case of umbrella crates, see below, features may also be used to enable constituents (but then that functionality +> was extracted into crates already). +> +> For example, if you defined a `web` crate with the following modules, users only needing client calls would also have to pay for the compilation of server code: +> +> ```text +> web::server +> web::client +> web::protocols +> ``` +> +> Instead, you should introduce individual crates that give users the ability to pick and choose: +> +> ```text +> web_server +> web_client +> web_protocols +> ``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-STATIC-VERIFICATION.md b/ai-skill/skills/rust-guidelines/rules/M-STATIC-VERIFICATION.md new file mode 100644 index 0000000..4dcc7f7 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-STATIC-VERIFICATION.md @@ -0,0 +1,78 @@ +## Use static verification (M-STATIC-VERIFICATION) + +Why: consistency and freedom from common issues. + +Projects should use the following static verification tools to help maintain the quality of the code. These tools can be +configured to run on a developer's machine during normal work, and should be used as part of check-in gates. + +* [compiler lints](https://doc.rust-lang.org/rustc/lints/index.html) offer many lints to avoid bugs and improve code quality. +* [clippy lints](https://doc.rust-lang.org/clippy/) contain hundreds of lints to avoid bugs and improve code quality. +* [rustfmt](https://github.com/rust-lang/rustfmt) ensures consistent source formatting. +* [cargo-audit](https://crates.io/crates/cargo-audit) verifies crate dependencies for security vulnerabilities. +* [cargo-hack](https://crates.io/crates/cargo-hack) validates that all combinations of crate features work correctly. +* [cargo-udeps](https://crates.io/crates/cargo-udeps) detects unused dependencies in Cargo.toml files. +* [miri](https://github.com/rust-lang/miri) validates the correctness of unsafe code. + +### Compiler Lints + +The Rust compiler generally produces exceptionally good diagnostics. In addition to the default set of diagnostics, projects +should explicitly enable the following set of compiler lints: + +```toml +[lints.rust] +ambiguous_negative_literals = "warn" +missing_debug_implementations = "warn" +redundant_imports = "warn" +redundant_lifetimes = "warn" +trivial_numeric_casts = "warn" +unsafe_op_in_unsafe_fn = "warn" +unused_lifetimes = "warn" +``` + +### Clippy Lints + +For clippy, projects should enable all major lint categories, and additionally enable some lints from the `restriction` lint group. +Undesired lints (e.g., numeric casts) can be opted back out of on a case-by-case basis: + +```toml +[lints.clippy] +cargo = { level = "warn", priority = -1 } +complexity = { level = "warn", priority = -1 } +correctness = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +perf = { level = "warn", priority = -1 } +style = { level = "warn", priority = -1 } +suspicious = { level = "warn", priority = -1 } +# nursery = { level = "warn", priority = -1 } # optional, might cause more false positives + +# Additional lints are from the `restriction` and `nursery` group that prevent specific +# constructs being used in source code in order to drive up consistency, +# quality, and brevity +allow_attributes_without_reason = "warn" +as_pointer_underscore = "warn" +assertions_on_result_states = "warn" +clone_on_ref_ptr = "warn" +deref_by_slicing = "warn" +disallowed_script_idents = "warn" +empty_drop = "warn" +empty_enum_variants_with_brackets = "warn" +empty_structs_with_brackets = "warn" +fn_to_numeric_cast_any = "warn" +if_then_some_else_none = "warn" +map_err_ignore = "warn" +redundant_type_annotations = "warn" +renamed_function_params = "warn" +semicolon_outside_block = "warn" +undocumented_unsafe_blocks = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unneeded_field_pattern = "warn" +unused_result_ok = "warn" +too_long_first_doc_paragraph = "warn" + +# May cause issues with structured logging otherwise. +literal_string_with_formatting_args = "allow" + +# Define custom opt outs here +# ... +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES-GUARD.md b/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES-GUARD.md new file mode 100644 index 0000000..385ef21 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES-GUARD.md @@ -0,0 +1,39 @@ +## Newtypes guard their invariants (M-STRONG-TYPES-GUARD) + +Why: centralized correctness invariants. + +When introducing a strong type or newtype that exists to encode an invariant (a non-empty string, a percentage, a port number, a sanitized path, ...), the type itself must enforce that invariant where applicable. + +Construction should be fallible, returning a proper error when the invariant cannot be upheld, rather than handing the responsibility off to every user: + +``` +// Bad, creates a new type but enforces nothing. Every caller now has to +// re-check that the value is actually a valid month, defeating the point of +// having a dedicated type. +pub struct Month(pub u8); + +impl Month { + pub fn new(value: u8) -> Self { ... } +} + + +// Good, the invariant (1..=12) is checked once, at the boundary, and +// every later use of `Month` can rely on it. +pub struct Month(u8); + +impl Month { + pub fn from_u8(value: u8) -> Result { ... } +} +``` + +This means for any newtype that is non-total: + +- It must have at least one fallible constructor (e.g., `fn from_foo(...) -> Result`). +- Additional panicking constructors are allowed (e.g., `new`), and should preferably be `const`. +- Conversions from weaker types into the newtype must be fallible (`TryFrom`/`FromStr`). +- Infallible `From` implementations may not be offered. + +> ### Why `const`? +> +> Const constructors allows them to be used inside `const {}` blocks, which surfaces these violations as errors. This enables +> users to do `let month_due = const { Month::new(14) }` and avoids hitting these paths during runtime. diff --git a/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES.md b/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES.md new file mode 100644 index 0000000..4d53d6c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-STRONG-TYPES.md @@ -0,0 +1,18 @@ +## Use the proper type family (M-STRONG-TYPES) + +Why: the right data and safety invariants, at the right time. + +Use the appropriate `std` type for your task. In general you should use the strongest type available, as early as possible in your API flow. Common offenders are + +| Do not use ... | use instead ... | Explanation | +| --- | --- | --- | +| `String`* | `PathBuf`* | Anything dealing with the OS should be `Path`-like | + +That said, you should also follow common Rust `std` conventions. Purely numeric types at public API boundaries (e.g., `window_size()`) are expected to +be regular numbers, not `Saturating`, `NonZero`, or similar. + + + +* Including their siblings, e.g., `&str`, `Path`, ... + + diff --git a/ai-skill/skills/rust-guidelines/rules/M-SYS-CRATES.md b/ai-skill/skills/rust-guidelines/rules/M-SYS-CRATES.md new file mode 100644 index 0000000..2f9399d --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-SYS-CRATES.md @@ -0,0 +1,27 @@ +## Native `-sys` crates compile without dependencies (M-SYS-CRATES) + +Why: libraries that just work on all platforms. + +If you author a pair of `foo` and `foo-sys` crates wrapping a native `foo.lib`, you are likely to run into the issues described +in [M-OOBE]. + +Follow these steps to produce a crate that _just works_ across platforms: + +- [ ] fully govern the build of `foo.lib` from `build.rs` inside `foo-sys`. Only use hand-crafted compilation via the + [cc](https://crates.io/crates/cc) crate, do _not_ run Makefiles or external build scripts, as that will require the installation of external dependencies, +- [ ] make all external tools optional, such as `nasm`, +- [ ] embed the upstream source code in your crate, +- [ ] make the embedded sources verifiable (e.g., include Git URL + hash), +- [ ] pre-generate `bindgen` glue if possible, +- [ ] support both static linking, and dynamic linking via [libloading](https://crates.io/crates/libloading). + +Deviations from these points can work, and can be considered on a case-by-case basis: + +If the native build system is available as an _OOBE_ crate, that can be used instead of `cc` invocations. The same applies to external tools. + +Source code might have to be downloaded if it does not fit crates.io size limitations. In any case, only servers with an availability +comparable to crates.io should be used. In addition, the specific hashes of acceptable downloads should be stored in the crate and verified. + +Downloading sources can fail on hermetic build environments, therefore alternative source roots should also be specifiable (e.g., via environment variables). + +[M-OOBE]: M-OOBE.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-TARGET-CPU.md b/ai-skill/skills/rust-guidelines/rules/M-TARGET-CPU.md new file mode 100644 index 0000000..216277c --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-TARGET-CPU.md @@ -0,0 +1,19 @@ +## Applications target highest viable target-cpu (M-TARGET-CPU) + +Why: fleet performance. + +Server applications should compile against the highest `target-cpu` that the deployment environment is guaranteed to support, rather than defaulting to the generic baseline. + +This can be achieved, for example, by setting inside `.cargo/config.toml`: + +```toml +[target.x86_64-unknown-linux-gnu] +rustflags = ["-C", "target-cpu=x86-64-v3"] + +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-cpu=x86-64-v3"] + +# Add other platforms here based on needs ... +``` + +Note this guideline applies only to applications, as target settings are ignored for libraries. diff --git a/ai-skill/skills/rust-guidelines/rules/M-TAUTOLOGICAL-TESTS.md b/ai-skill/skills/rust-guidelines/rules/M-TAUTOLOGICAL-TESTS.md new file mode 100644 index 0000000..2a53a28 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-TAUTOLOGICAL-TESTS.md @@ -0,0 +1,20 @@ +## Tests do not assert ground truth (M-TAUTOLOGICAL-TESTS) + +Why: tests that add value, not noise. + +Unit tests should verify meaningful behavior instead of repeating foundational definitions. + +Agents frequently produce tests that re-state the expected value from the same logic the code under test uses, or that simply mirror the implementation's branches. Such tests pass by construction, provide virtually no value, but increase the noise floor of subsequent changes: + +``` +const CHECKPOINTS: [u32; 4] = [0, 90, 180, 270]; + +#[test] +fn checkpoints_are_correct() { + assert_eq!(CHECKPOINTS, [0, 90, 180, 270]); +} +``` + +Where these are used to satisfy mutation tests, the mutation test should be skipped instead. + +Instead, a meaningful test would check a property the constants are supposed to satisfy, for example that they are evenly spaced, monotonically increasing, or impose some direction in related logic. diff --git a/ai-skill/skills/rust-guidelines/rules/M-TEST-UTIL.md b/ai-skill/skills/rust-guidelines/rules/M-TEST-UTIL.md new file mode 100644 index 0000000..1e9fb26 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-TEST-UTIL.md @@ -0,0 +1,23 @@ +## Test utilities are feature gated (M-TEST-UTIL) + +Why: production builds that cannot bypass safety checks. + +Testing functionality must be guarded behind a feature flag. This includes + +- mocking functionality ([M-MOCKABLE-SYSCALLS]), +- the ability to inspect sensitive data, +- safety check overrides, +- fake data generation. + +We recommend you use a single flag only, named `test-util`. In any case, the feature(s) must clearly communicate they are for testing purposes. + +``` +impl HttpClient { + pub fn get() { ... } + + #[cfg(feature = "test-util")] + pub fn bypass_certificate_checks() { ... } +} +``` + +[M-MOCKABLE-SYSCALLS]: M-MOCKABLE-SYSCALLS.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-THROUGHPUT.md b/ai-skill/skills/rust-guidelines/rules/M-THROUGHPUT.md new file mode 100644 index 0000000..785be3a --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-THROUGHPUT.md @@ -0,0 +1,28 @@ +## Optimize for throughput, avoid empty cycles (M-THROUGHPUT) + +Why: COGS savings at scale. + +You should optimize your library for throughput, and one of your key metrics should be _items per CPU cycle_. + +This does not mean to neglect latency—after all you can scale for throughput, but not for latency. However, +in most cases you should not pay for latency with _empty cycles_ that come with single-item processing, contended locks and frequent task switching. + +Ideally, you should + +- partition reasonable chunks of work ahead of time, +- let individual threads and tasks deal with their slice of work independently, +- sleep or yield when no work is present, +- design your own APIs for batched operations, +- perform work via batched APIs where available, +- yield within long individual items, or between chunks of batches (see [M-YIELD-POINTS]), +- exploit CPU caches, temporal and spatial locality. + +You should not: + +- hot spin to receive individual items faster, +- perform work on individual items if batching is possible, +- do work stealing or similar to balance individual items. + +Shared state should only be used if the cost of sharing is less than the cost of re-computation. + +[M-YIELD-POINTS]: M-YIELD-POINTS.md diff --git a/ai-skill/skills/rust-guidelines/rules/M-TYPES-SEND.md b/ai-skill/skills/rust-guidelines/rules/M-TYPES-SEND.md new file mode 100644 index 0000000..70a3162 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-TYPES-SEND.md @@ -0,0 +1,93 @@ +## Types are Send (M-TYPES-SEND) + +Why: use in Tokio and behind runtime abstractions. + +Public types should be `Send` for compatibility reasons: + +- All futures produced (explicitly or implicitly) must be `Send` +- Most other types should be `Send`, but there might be exceptions + +### Futures + +When declaring a future explicitly you should ensure it is, and remains, `Send`. + +``` +# use std::future::Future; +# use std::pin::Pin; +# use std::task::{Context, Poll}; +# +struct Foo {} + +impl Future for Foo { + // Explicit implementation of `Future` for your type + # type Output = (); + # + # fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<::Output> { todo!() } +} + +// You should assert your type is `Send` +const fn assert_send() {} +const _: () = assert_send::(); +``` + +When returning futures implicitly through `async` method calls, you should make sure these are `Send` too. +You do not have to test every single method, but you should at least validate your main entry points. + +``` +async fn foo() { } + +// TODO: We want this as a macro as well +fn assert_send(_: T) {} +_ = assert_send(foo()); +``` + +### Regular Types + +Most regular types should be `Send`, as they otherwise infect futures turning them `!Send` if held across `.await` points. + +``` +# use std::rc::Rc; +# async fn read_file(x: &str) {} +# +async fn foo() { + let rc = Rc::new(123); // <-- Holding this across an .await point prevents + read_file("foo.txt").await; // the future from being `Send`. + dbg!(rc); +} +``` + +That said, if the default use of your type is _instantaneous_, and there is no reason for it to be otherwise held across `.await` boundaries, it may be `!Send`. + +``` +# use std::rc::Rc; +# struct Telemetry; impl Telemetry { fn ping(&self, _: u32) {} } +# fn telemetry() -> Telemetry { Telemetry } +# async fn read_file(x: &str) {} +# +async fn foo() { + // Here a hypothetical instance Telemetry is summoned + // and used ad-hoc. It may be ok for Telemetry to be !Send. + telemetry().ping(0); + read_file("foo.txt").await; + telemetry().ping(1); +} +``` + +> ### The Cost of Send +> +> Ideally, there would be abstractions that are `Send` in work-stealing runtimes, and `!Send` in thread-per-core models based on non-atomic +> types like `Rc` and `RefCell` instead. +> +> Practically these abstractions don't exist, preventing Tokio compatibility in the non-atomic case. That in turn means you would have to +> "reinvent the world" to get anything done in a thread-per-core universe. +> +> The good news is, in most cases atomics and uncontended locks only have a measurable impact if accessed more frequently than every 64 words or so. +> +>
+> +> ![TEXT](https://microsoft.github.io/rust-guidelines/guidelines/libs/interop/M-TYPES-SEND.png) +> +>
+> +> Working with a large `Vec` in a hot loop is a bad idea, but doing the occasional uncontended atomic operation from otherwise thread-per-core +> async code has no performance impact, but gives you widespread ecosystem compatibility. diff --git a/ai-skill/skills/rust-guidelines/rules/M-UNSAFE-IMPLIES-UB.md b/ai-skill/skills/rust-guidelines/rules/M-UNSAFE-IMPLIES-UB.md new file mode 100644 index 0000000..a7052f4 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-UNSAFE-IMPLIES-UB.md @@ -0,0 +1,14 @@ +## Unsafe implies undefined behavior (M-UNSAFE-IMPLIES-UB) + +Why: semantic consistency without warning fatigue. + +The marker `unsafe` may only be applied to functions and traits if misuse implies the risk of undefined behavior (UB). +It must not be used to mark functions that are dangerous to call for other reasons. + +``` +// Valid use of unsafe +unsafe fn print_string(x: *const String) { } + +// Invalid use of unsafe +unsafe fn delete_database() { } +``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-UNSAFE.md b/ai-skill/skills/rust-guidelines/rules/M-UNSAFE.md new file mode 100644 index 0000000..e0dbe75 --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-UNSAFE.md @@ -0,0 +1,55 @@ +## Unsafe needs reason, should be avoided (M-UNSAFE) + +Why: memory safety and a minimal attack surface. + +You must have a valid reason to use `unsafe`. The only valid reasons are + +1) novel abstractions, e.g., a new smart pointer or allocator, +1) performance, e.g., attempting to call `.get_unchecked()`, +1) FFI and platform calls, e.g., calling into C or the kernel, ... + +Unsafe code lowers the guardrails used by the compiler, transferring some of the compiler's responsibilities +to the programmer. Correctness of the resulting code relies primarily on catching all mistakes in code review, +which is error-prone. Mistakes in unsafe code may introduce high-severity security vulnerabilities. + +You must not use ad-hoc `unsafe` to + +- shorten a performant and safe Rust program, e.g., 'simplify' enum casts via `transmute`, +- bypass `Send` and similar bounds, e.g., by doing `unsafe impl Send ...`, +- bypass lifetime requirements via `transmute` and similar. + +Ad-hoc here means `unsafe` embedded in otherwise unrelated code. It is of course permissible to create properly designed, sound abstractions doing these things. + +In any case, `unsafe` must follow the guidelines outlined below. + +### Novel Abstractions + +- [ ] Verify there is no established alternative. If there is, prefer that. +- [ ] Your abstraction must be minimal and testable. +- [ ] It must be hardened and tested against ["adversarial code"](https://cheats.rs/#adversarial-code), esp. + - If they accept closures they must become invalid (e.g., poisoned) if the closure panics + - They must assume any safe trait is misbehaving, esp. `Deref`, `Clone` and `Drop`. +- [ ] Any use of `unsafe` must be accompanied by plain-text reasoning outlining its safety +- [ ] It must pass [Miri](https://github.com/rust-lang/miri), including adversarial test cases +- [ ] It must follow all other [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/) + +### Performance + +- [ ] Using `unsafe` for performance reasons should only be done after benchmarking +- [ ] Any use of `unsafe` must be accompanied by plain-text reasoning outlining its safety. This applies to both + calling `unsafe` methods, as well as providing `_unchecked` ones. +- [ ] The code in question must pass [Miri](https://github.com/rust-lang/miri) +- [ ] You must follow the [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/) + +### FFI + +- [ ] We recommend you use an established interop library to avoid `unsafe` constructs +- [ ] You must follow the [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/) +- [ ] You must document your generated bindings to make it clear which call patterns are permissible + +### Further Reading + +- [Nomicon](https://doc.rust-lang.org/nightly/nomicon/) +- [Unsafe Code Guidelines](https://rust-lang.github.io/unsafe-code-guidelines/) +- [Miri](https://github.com/rust-lang/miri) +- ["Adversarial code"](https://cheats.rs/#adversarial-code) diff --git a/ai-skill/skills/rust-guidelines/rules/M-UNSOUND.md b/ai-skill/skills/rust-guidelines/rules/M-UNSOUND.md new file mode 100644 index 0000000..1b419cb --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-UNSOUND.md @@ -0,0 +1,63 @@ +## All code must be sound (M-UNSOUND) + +Why: predictable runtime behavior free of bugs and incompatibilities. + +Unsound code is seemingly _safe_ code that may produce undefined behavior when called from other safe code, or on its own accord. + +> ### Meaning of 'Safe' +> +> The terms _safe_ and `unsafe` are technical terms in Rust. +> +> A function is _safe_, if its signature does not mark it `unsafe`. That said, _safe_ functions can still be dangerous +> (e.g., `delete_database()`), and `unsafe` ones are, when properly used, usually quite benign (e.g.,`vec.get_unchecked()`). +> +> A function is therefore _unsound_ if it appears _safe_ (i.e., it is not marked `unsafe`), but if _any_ of its calling +> modes would cause undefined behavior. This is to be interpreted in the strictest sense. Even if causing undefined +> behavior is only a 'remote, theoretical possibility' requiring 'weird code', the function is unsound. +> +> Also see [Unsafe, Unsound, Undefined](https://cheats.rs/#unsafe-unsound-undefined). + +``` +// "Safely" converts types +fn unsound_ref(x: &T) -> &u128 { + unsafe { std::mem::transmute(x) } +} + +// "Clever trick" to work around missing `Send` bounds. +struct AlwaysSend(T); +unsafe impl Send for AlwaysSend {} +unsafe impl Sync for AlwaysSend {} +``` + +Unsound abstractions are never permissible. If you cannot safely encapsulate something, you must expose `unsafe` functions instead, and document proper behavior. + +
+ +No Exceptions + +While you may break most guidelines if you have a good enough reason, there are no exceptions in this case: unsound code is never acceptable. + +
+ +> ### It's the Module Boundaries +> +> Note that soundness boundaries equal module boundaries! It is perfectly fine, in an otherwise safe abstraction, +> to have safe functions that rely on behavior guaranteed elsewhere **in the same module**. +> +> ```rust +> struct MyDevice(*const u8); +> +> impl MyDevice { +> fn new() -> Self { +> // Properly initializes instance ... +> # todo!() +> } +> +> fn get(&self) -> u8 { +> // It is perfectly fine to rely on `self.0` being valid, despite this +> // function in-and-by itself being unable to validate that. +> unsafe { *self.0 } +> } +> } +> +> ``` diff --git a/ai-skill/skills/rust-guidelines/rules/M-UPSTREAM-GUIDELINES.md b/ai-skill/skills/rust-guidelines/rules/M-UPSTREAM-GUIDELINES.md new file mode 100644 index 0000000..79aecdf --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-UPSTREAM-GUIDELINES.md @@ -0,0 +1,24 @@ +## Follow the upstream guidelines (M-UPSTREAM-GUIDELINES) + +Why: a codebase that reflects community lessons and does not surprise users or contributors. + +The guidelines in this book complement existing Rust guidelines, in particular: + +- [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/checklist.html) +- [Rust Style Guide](https://doc.rust-lang.org/nightly/style-guide/) +- [Rust Design Patterns](https://rust-unofficial.github.io/patterns//intro.html) +- [Rust Reference - Undefined Behavior](https://doc.rust-lang.org/reference/behavior-considered-undefined.html) + +We recommend you read through these as well, and apply them in addition to this book's items. Pay special attention to the ones below, as they are frequently forgotten: + +- [ ] [C-CONV](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv) - Ad-hoc conversions + follow `as_`, `to_`, `into_` conventions +- [ ] [C-GETTER](https://rust-lang.github.io/api-guidelines/naming.html#getter-names-follow-rust-convention-c-getter) - Getter names follow Rust convention +- [ ] [C-COMMON-TRAITS](https://rust-lang.github.io/api-guidelines/interoperability.html#c-common-traits) - Types eagerly implement common traits + - `Copy`, `Clone`, `Eq`, `PartialEq`, `Ord`, `PartialOrd`, `Hash`, `Default`, `Debug` + - `Display` where type wants to be displayed +- [ ] [C-CTOR](https://rust-lang.github.io/api-guidelines/predictability.html?highlight=new#constructors-are-static-inherent-methods-c-ctor) - + Constructors are static, inherent methods + - In particular, have `Foo::new()`, even if you have `Foo::default()` +- [ ] [C-FEATURE](https://rust-lang.github.io/api-guidelines/naming.html#feature-names-are-free-of-placeholder-words-c-feature) - Feature names + are free of placeholder words diff --git a/ai-skill/skills/rust-guidelines/rules/M-WEASEL-WORDS.md b/ai-skill/skills/rust-guidelines/rules/M-WEASEL-WORDS.md new file mode 100644 index 0000000..6955c1b --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-WEASEL-WORDS.md @@ -0,0 +1,24 @@ +## Names are free of weasel words (M-WEASEL-WORDS) + +Why: readability. + +Symbol names, especially type and trait names, should be free of weasel words that do not meaningfully +add information. Common offenders include `Service`, `Manager`, and `Factory`. + +While your library may very well contain or communicate with a booking service—or even hold an `HttpClient` +instance named `booking_service`—one should rarely encounter a `BookingService` _type_ in code. + +An item handling many bookings can just be called `Bookings`. If it does anything more specific, then that quality +should be appended instead. It submits these items elsewhere? Calling it `BookingDispatcher` would be more helpful. + +The same is true for `Manager`s. All code manages _something_, so that moniker is rarely useful. With rare +exceptions, life cycle issues should likewise not be made the subject of some manager. Items are created in whatever +way they are needed, their disposal is governed by `Drop`, and only `Drop`. + +Regarding factories, at least the term should be avoided. While the concept `FooFactory` has its use, its canonical +Rust name is `Builder` (compare [M-INIT-BUILDER](M-INIT-BUILDER.md)). A builder that can produce items repeatedly is still a builder. + +In addition, accepting factories (builders) as parameters is an unidiomatic import of OO concepts into Rust. If +repeatable instantiation is required, functions should ask for an `impl Fn() -> Foo` over a `FooBuilder` or +similar. In contrast, standalone builders have their use, but primarily to reduce parametric permutation complexity +around optional values (again, [M-INIT-BUILDER](M-INIT-BUILDER.md)). diff --git a/ai-skill/skills/rust-guidelines/rules/M-YIELD-POINTS.md b/ai-skill/skills/rust-guidelines/rules/M-YIELD-POINTS.md new file mode 100644 index 0000000..2b54bae --- /dev/null +++ b/ai-skill/skills/rust-guidelines/rules/M-YIELD-POINTS.md @@ -0,0 +1,41 @@ +## Long-running tasks should have yield points (M-YIELD-POINTS) + +Why: fair CPU time for all tasks. + +If you perform long running computations, they should contain `yield_now().await` points. + +Your future might be executed in a runtime that cannot work around blocking or long-running tasks. Even then, such tasks are +considered bad design and cause runtime overhead. If your complex task performs I/O regularly it will simply utilize these await points to preempt itself: + +``` +async fn process_items(items: &[items]) { + // Keep processing items, the runtime will preempt you automatically. + for i in items { + read_item(i).await; + } +} +``` + +If your task performs long-running CPU operations without intermixed I/O, it should instead cooperatively yield at regular intervals, to not starve concurrent operations: + +``` +async fn process_items(zip_file: File) { + let items = zip_file.read().async; + for i in items { + decompress(i); + yield_now().await; + } +} +``` + +If the number and duration of your individual operations are unpredictable you should use APIs such as `has_budget_remaining()` and +related APIs to query your hosting runtime. + +> ### Yield how often? +> +> In a thread-per-core model the overhead of task switching must be balanced against the systemic effects of starving unrelated tasks. +> +> Under the assumption that runtime task switching takes 100's of ns, in addition to the overhead of lost CPU caches, +> continuous execution in between should be long enough that the switching cost becomes negligible (<1%). +> +> Thus, performing 10 - 100ÎĽs of CPU-bound work between yield points would be a good starting point. From c324190bed56086823942cc4272b5399616515eb Mon Sep 17 00:00:00 2001 From: Vaiz <4908982+Vaiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:43:18 +0000 Subject: [PATCH 3/4] docs: limit Copilot README section to installation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 49 ++----------------------------------------------- 1 file changed, 2 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 94aed5f..8785177 100644 --- a/README.md +++ b/README.md @@ -6,28 +6,7 @@ A collection of pragmatic design guidelines helping developers to produce idioma ## Use with GitHub Copilot -This repository is also a Copilot plugin marketplace with one plugin, -`rust-guidelines`, containing one skill of the same name. The plugin lives in -[`ai-skill`](ai-skill); the discovery catalog is -[`.github/plugin/marketplace.json`](.github/plugin/marketplace.json). -The skill bundles a trigger index and individual `rules/.md` files, loading -only the guidelines applicable to the current task. It works offline after -installation; the rules do not need to be fetched from the web. - -The skill is adapted from rust-dev's -[`rust-core-guidelines`](https://github.com/agency-microsoft/playground/tree/0dca309355d50ee610b1b3c45f283019592b40d1/plugins/rust-dev/skills/rust-core-guidelines): -the index and all 144 rule files are retained, the skill is renamed to -`rust-guidelines`, and the dependency on the separate `rust-task-docs` skill is -removed. The bundled rules cover the Pragmatic Rust Guidelines and the Rust API -Guidelines. Their original -[license notices](ai-skill/skills/rust-guidelines/licenses) are included. -The rule files are a verbatim snapshot; their local Markdown lint configuration -preserves upstream formatting without relaxing linting for the skill entry point. - -### Copilot CLI - -With a current [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli) -installed and signed in, register this fork's marketplace and install the plugin: +In GitHub Copilot CLI, add the marketplace and install the skill: ```shell copilot plugin marketplace add Vaiz/rust-guidelines @@ -35,31 +14,7 @@ copilot plugin install rust-guidelines@pragmatic-rust-guidelines ``` Start a new Copilot session and run `/skills list` to confirm that -`rust-guidelines` is available. Ask Copilot to use the skill, for example: - -```text -Use the rust-guidelines skill to review the Rust code in this project. -``` - -To try a local checkout before publishing, register the repository root as a -local marketplace instead of the GitHub repository: - -```shell -copilot plugin marketplace add . -copilot plugin install rust-guidelines@pragmatic-rust-guidelines -``` - -Run these commands from the repository root. Local marketplace plugins load -directly from the checkout; start a new session after editing the skill. - -### Other Copilot clients - -In a Copilot client that supports plugin marketplaces, add -`https://github.com/Vaiz/rust-guidelines` as a marketplace and install -`rust-guidelines`. See the -[client-specific installation instructions](https://docs.github.com/en/copilot/reference/plugin-and-marketplace-reference#use-plugins). -Marketplace support varies by client; this plugin contains a standard -`skills/rust-guidelines/SKILL.md` skill and does not require MCP servers or hooks. +`rust-guidelines` is available. ## Development From bddd0b193b74fae98a1fe6e418a69a39f67fffa9 Mon Sep 17 00:00:00 2001 From: Vaiz <4908982+Vaiz@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:52:24 +0000 Subject: [PATCH 4/4] docs: target upstream Rust guidelines marketplace Use microsoft/rust-guidelines in installation instructions and plugin metadata, with Microsoft as the marketplace owner. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/plugin/marketplace.json | 2 +- README.md | 2 +- ai-skill/plugin.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json index 2b770e7..05adfe3 100644 --- a/.github/plugin/marketplace.json +++ b/.github/plugin/marketplace.json @@ -1,7 +1,7 @@ { "name": "pragmatic-rust-guidelines", "owner": { - "name": "Vaiz" + "name": "Microsoft" }, "metadata": { "description": "Pragmatic Rust Guidelines for GitHub Copilot." diff --git a/README.md b/README.md index 8785177..58b8e03 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ A collection of pragmatic design guidelines helping developers to produce idioma In GitHub Copilot CLI, add the marketplace and install the skill: ```shell -copilot plugin marketplace add Vaiz/rust-guidelines +copilot plugin marketplace add microsoft/rust-guidelines copilot plugin install rust-guidelines@pragmatic-rust-guidelines ``` diff --git a/ai-skill/plugin.json b/ai-skill/plugin.json index aac55fb..b45fb75 100644 --- a/ai-skill/plugin.json +++ b/ai-skill/plugin.json @@ -4,7 +4,7 @@ "version": "0.1.0", "description": "Apply the Pragmatic Rust Guidelines when writing or reviewing Rust.", "homepage": "https://microsoft.github.io/rust-guidelines", - "repository": "https://github.com/Vaiz/rust-guidelines", + "repository": "https://github.com/microsoft/rust-guidelines", "license": "MIT", "keywords": ["rust", "guidelines", "code-review"] }