rust-code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Code Review

Rust 代码审查

Review the actual diff and its callers, not an isolated snippet or a generic checklist. Prioritize defects that can change behavior, violate invariants, expose data, deadlock, panic unexpectedly, or break public APIs.
审查实际 diff 及其调用方,而不是孤立的代码片段或泛化的检查清单。优先处理可能改变行为、破坏不变量、泄露数据、导致死锁、意外 panic 或破坏公共 API 的缺陷。

Scope and Routing

范围与分流

Use this skill to review:
  • ownership, borrowing, lifetime, and drop behavior;
  • unsafe
    preconditions and safe-wrapper soundness;
  • error propagation, panic paths, partial updates, and rollback;
  • concurrency, cancellation, lock ordering, and task lifecycle;
  • public API, semver, feature, target, and MSRV compatibility;
  • allocation, cloning, blocking, serialization, and hot-path costs;
  • tests, documentation, dependencies, and operational failure paths.
Route format and lint configuration to
rust-style-clippy
, deep unsafe or ABI analysis to
rust-unsafe-ffi
, concurrency design to
rust-concurrency
, dependency resolution to
rust-cargo-build
, test implementation to
rust-testing
, and API shape decisions (trait sealing, newtype design, error taxonomy, builder patterns) to
rust-api-design
.
使用此 skill 审查:
  • 所有权、借用、生命周期和 drop 行为;
  • unsafe
    前置条件及 safe wrapper 的可靠性;
  • 错误传播、panic 路径、部分更新和回滚;
  • 并发、取消、锁顺序和任务生命周期;
  • 公共 API、semver、feature、target 和 MSRV 兼容性;
  • 分配、克隆、阻塞、序列化和热路径成本;
  • 测试、文档、依赖和运行失败路径。
将格式与 lint 配置交由
rust-style-clippy
,将深入的 unsafe 或 ABI 分析交由
rust-unsafe-ffi
,将并发设计交由
rust-concurrency
,将依赖解析交由
rust-cargo-build
,将测试实现交由
rust-testing
,并将 API 形态决策(trait sealing、newtype 设计、错误分类体系、builder pattern)交由
rust-api-design
。

Workflow

工作流

1. Establish the review contract

1. 确定审查契约

Inspect the repository instructions, changed files, surrounding symbols, callers, tests, manifests, lockfile, declared MSRV, enabled features, and supported targets. Determine whether the change affects a private implementation, public library API, persistent data, wire format, database schema, or security boundary.
Use the narrowest relevant commands:
bash
git diff --check
cargo metadata --format-version 1
cargo check --workspace --all-targets --all-features
cargo test --workspace --all-targets --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
Do not claim a command passed unless it ran. Do not treat successful compilation as proof of behavioral correctness.
检查仓库说明、变更文件、周边符号、调用方、测试、manifest、lockfile、声明的 MSRV、启用的 features 和支持的 targets。确定变更是否影响私有实现、公共库 API、持久化数据、传输格式、数据库 schema 或安全边界。
仅运行最窄范围内的相关命令:
bash
git diff --check
cargo metadata --format-version 1
cargo check --workspace --all-targets --all-features
cargo test --workspace --all-targets --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
除非命令已实际运行,否则不要声称其已通过。不要将成功编译视为行为正确性的证明。

2. Trace behavior through boundaries

2. 跨边界追踪行为

For each changed path, follow input, state transitions, side effects, errors, cleanup, and observable output. Check:
  • whether references outlive their owners or guards;
  • whether moves, clones, or allocations change cost or semantics;
  • whether
    Option
    and
    Result
    preserve absence and failure information;
  • whether resources are released on early return, cancellation, panic, and shutdown;
  • whether transactions and multi-step mutations are atomic where required;
  • whether retries are bounded and safe for the operation;
  • whether logs, Debug output, metrics, or errors expose secrets.
对于每条发生变更的路径,跟踪输入、状态转换、副作用、错误、清理过程和可观察输出。检查:
  • 引用是否会在其所有者或 guard 失效后继续使用;
  • move、clone 或 allocation 是否改变了成本或语义;
  • Option
    和
    Result
    是否保留了缺失与失败信息;
  • 资源是否会在提前返回、取消、panic 和关闭时释放;
  • 在需要原子性的场景中,事务和多步骤变更是否保持原子性;
  • 重试是否有界,且对当前操作安全;
  • 日志、
    Debug
    输出、指标或错误是否会泄露机密信息。

3. Review Rust-specific hazards

3. 审查 Rust 特有风险

Unsafe and FFI

Unsafe 与 FFI

  • Require a documented safety invariant for every unsafe API and implementation.
  • Keep unsafe blocks minimal and enable
    unsafe_op_in_unsafe_fn
    explicitly.
  • Verify provenance, validity, alignment, initialization, aliasing, layout, unwinding, ownership transfer, and deallocation symmetry.
  • Treat manual
    Send
    or
    Sync
    implementations as unsafe contracts, not marker boilerplate.
  • 每个 unsafe API 和实现都应有文档化的 safety invariant。
  • 保持 unsafe block 最小化,并显式启用
    unsafe_op_in_unsafe_fn
    。
  • 验证 provenance、validity、alignment、initialization、aliasing、layout、unwinding、ownership transfer 和 deallocation symmetry。
  • 手动实现的
    Send
    或
    Sync
    应被视为 unsafe contract,而不是单纯的 marker trait 样板代码。

Concurrency

并发

  • Check lock ordering and whether guards cross
    .await
    , callbacks, blocking I/O, or user code.
  • Require bounded queues, overload behavior, cancellation ownership, supervised tasks, and deterministic shutdown.
  • Distinguish I/O concurrency from CPU parallelism; adding tasks or workers is not automatically a performance fix.
  • 检查锁顺序,以及 guard 是否跨越
    .await
    、回调、阻塞 I/O 或用户代码。
  • 要求使用有界队列,明确过载行为、取消所有权、受监督任务和确定性的关闭流程。
  • 区分 I/O 并发与 CPU 并行;增加 task 或 worker 并不自动构成性能优化。

Error handling

错误处理

  • Flag
    unwrap
    ,
    expect
    , indexing, assertions, integer overflow assumptions, and unreachable branches when user or external input can reach them.
  • Preserve structured library errors; add context at application boundaries without leaking internals.
  • Verify that cleanup or rollback failures are not silently discarded.
  • 当用户或外部输入可能触发时,标记
    unwrap
    、
    expect
    、索引、断言、整数溢出假设和不可达分支。
  • 保留结构化的库错误;在应用边界添加上下文,但不要泄露内部实现。
  • 验证清理或回滚失败不会被静默丢弃。

API and compatibility

API 与兼容性

  • Check visibility, trait bounds, auto traits, object safety,
    #[non_exhaustive]
    , feature combinations, target-specific code, and MSRV.
  • Treat generated methods, serialization shapes, error variants, and public feature names as API surface.
  • Require explicit migration for persisted or transmitted formats.
  • 检查可见性、trait bounds、auto traits、object safety、
    #[non_exhaustive]
    、feature 组合、target 专属代码和 MSRV。
  • 将生成的方法、序列化结构、错误变体和公共 feature 名称视为 API surface。
  • 对持久化或传输格式的变更,要求提供明确的迁移方案。

3a. API Guidelines Review Lens

3a. API Guidelines 审查视角

For every touched public item, scan the diff against the four chapters of the Rust API Guidelines checklist. Confirm each match with a concrete caller before raising it, and route design-level fixes to
rust-api-design
. The full table per chapter, severities, and suggested comments live in API Guidelines Checklist.
  • Dependability — flag
    panic!
    ,
    unwrap
    ,
    expect
    ,
    unreachable!
    , slice indexing, and
    transmute
    inside public methods that accept caller input (C-PANIC, C-UNWRAP, C-TRANSMUTE).
  • Type safety — flag functions taking multiple
    bool
    parameters or interchangeable bare primitives where enums or newtypes would prevent argument-order bugs (C-BOOL, C-NEWTYPE).
  • Interoperability — flag public types missing
    Debug
    /
    Clone
    /
    PartialEq
    , and non-smart-pointer types implementing
    Deref
    to borrow methods (C-COMMON-TRAITS, C-CONVERT).
  • Future-proofing — flag extensible public traits that are not sealed and library error or config enums without
    #[non_exhaustive]
    (C-SEALED, C-NON-EXHAUSTIVE).
Do not flag
unwrap
/
expect
in
#[cfg(test)]
modules, idiomatic infallible
unsafe
in FFI shims with documented invariants, or single-purpose
bool
setters; see the false-positives list in the checklist.
对于每个受影响的公共 item,根据 Rust API Guidelines 检查清单的四个章节扫描 diff。提出问题前,先通过具体调用方确认每项匹配,并将设计层面的修复交由
rust-api-design
。各章节的完整表格、严重程度和建议评论见 API Guidelines 检查清单。
  • Dependability——标记公共方法中接收调用方输入时使用的
    panic!
    、
    unwrap
    、
    expect
    、
    unreachable!
    、slice 索引和
    transmute
    (C-PANIC、C-UNWRAP、C-TRANSMUTE)。
  • Type safety——标记接收多个
    bool
    参数或可互换的裸基本类型的函数,因为 enum 或 newtype 可以防止参数顺序错误(C-BOOL、C-NEWTYPE)。
  • Interoperability——标记缺少
    Debug
    、
    Clone
    、
    PartialEq
    的公共类型,以及为借用方法而实现
    Deref
    的非智能指针类型(C-COMMON-TRAITS、C-CONVERT)。
  • Future-proofing——标记未封装的可扩展公共 trait,以及缺少
    #[non_exhaustive]
    的库错误或配置 enum(C-SEALED、C-NON-EXHAUSTIVE)。
不要标记
#[cfg(test)]
module 中的
unwrap
或
expect
、具有文档化 invariant 的 FFI shim 中符合惯用写法且不会失败的 unsafe 代码,也不要标记单一用途的
bool
setter;请参阅检查清单中的误报列表。

4. Review performance with evidence

4. 基于证据审查性能

Report an allocation, clone, lock, or algorithm as a performance finding only when it is plausibly material on the changed path. Prefer measurements over aesthetic rewrites. Check blocking work on async executors, accidental quadratic behavior, repeated parsing, oversized enum variants, unnecessary buffering, and unbounded growth.
仅当 allocation、clone、lock 或算法在变更路径上可能产生实质影响时,才将其作为性能问题报告。优先使用测量结果,而不是基于审美偏好的重写。检查 async executor 上的阻塞工作、意外产生的二次复杂度、重复解析、尺寸过大的 enum variant、不必要的缓冲和无界增长。

5. Verify tests and documentation

5. 验证测试与文档

Require tests at the boundary where regressions are observable. Cover success, invalid input, failure after partial progress, cancellation, concurrency, feature and platform variants, and public examples. Ensure public safety requirements, errors, panics, and compatibility constraints are documented and doctests remain executable.
Read Review Tools and Checklist when choosing additional analysis tools. Read Review Scenarios for expected finding shape. Read API Guidelines Checklist when applying the C-PANIC / C-UNWRAP / C-TRANSMUTE / C-BOOL / C-NEWTYPE / C-COMMON-TRAITS / C-CONVERT / C-SEALED / C-NON-EXHAUSTIVE rules to a public API surface.
要求在能够观察到回归的边界处提供测试。覆盖成功场景、非法输入、部分进度后失败、取消、并发、feature 和平台变体,以及公共示例。确保公共 safety requirement、错误、panic 和兼容性约束均已文档化,并确保 doctest 保持可执行。
选择额外分析工具时,请阅读 审查工具与检查清单。了解预期发现形式时,请阅读 审查场景。将 C-PANIC、C-UNWRAP、C-TRANSMUTE、C-BOOL、C-NEWTYPE、C-COMMON-TRAITS、C-CONVERT、C-SEALED、C-NON-EXHAUSTIVE 规则应用于公共 API surface 时,请阅读 API Guidelines 检查清单。

Finding Format

发现格式

Return findings before any summary. Each finding must contain:
  1. severity and concise title;
  2. the tightest file and line range;
  3. the concrete failing condition or caller path;
  4. user, security, compatibility, or operational impact;
  5. a minimal correction or test that proves the fix.
Do not report style-only preferences as correctness findings. If no actionable finding remains, say so and state the residual verification gaps.
在给出任何总结之前先返回发现。每项发现必须包含:
  1. 严重程度和简明标题;
  2. 范围最紧凑的文件与行号区间;
  3. 具体失败条件或调用方路径;
  4. 对用户、安全性、兼容性或运行的影响;
  5. 可证明修复有效的最小改动或测试。
不要将纯样式偏好作为正确性问题报告。如果没有剩余的可执行发现,请明确说明,并列出尚未验证的差距。

Completion Criteria

完成标准

  • Review the diff, callers, tests, manifests, and relevant feature or target boundaries.
  • Report reproducible findings in severity order with tight locations.
  • Separate confirmed defects from risks that still require evidence.
  • Run or explicitly account for relevant checks.
  • Avoid silently broadening the change or implementing fixes unless requested.
  • 审查 diff、调用方、测试、manifest 和相关的 feature 或 target 边界。
  • 按严重程度顺序报告可复现的发现,并提供精确位置。
  • 区分已确认的缺陷与仍需证据支持的风险。
  • 运行相关检查,或明确说明未运行检查的原因和影响。
  • 除非用户明确要求,否则不要擅自扩大变更范围或实现修复。

Upstream Sources

上游来源

Data Privacy

数据隐私

This skill does not collect, store, or transmit user data. Confirm authorization before querying private registries or external review systems.
此 skill 不收集、存储或传输用户数据。查询私有 registry 或外部审查系统前,必须确认已获得授权。