Skip to content
Back to skills

Rust

ASecurity

Canonical rules for writing and reviewing Rust code in Shift's crates. Use whenever you add or change `.rs` code, especially error handling (`ok_or`, `ok_or_else`, `map_err`, `?`, `CoreError`, `StoreError`, `SlugError`, `BridgeError`), entity lookups by id, checked arithmetic and integer conversions, or helpers that several call sites repeat. Load `rustdoc` as well when the change adds or edits doc comments.

  • 420 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 9, 2026
developmenttypescriptrustgosqlexpressapibackend

Works with

  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned November 26, 2026

npx -y skills add shift-editor/shift --skill rust --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Rust?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Rust
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/shift-editor-rust/badge)](https://www.skillsdirectory.com/skills/shift-editor-rust)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: rust
description: Canonical rules for writing and reviewing Rust code in Shift's crates. Use whenever you add or change `.rs` code, especially error handling (`ok_or`, `ok_or_else`, `map_err`, `?`, `CoreError`, `StoreError`, `SlugError`, `BridgeError`), entity lookups by id, checked arithmetic and integer conversions, or helpers that several call sites repeat. Load `rustdoc` as well when the change adds or edits doc comments.
---

# /rust — How Rust is written in Shift

Shift's crates had the same failure built by hand at hundreds of sites: `.ok_or_else(|| CoreError::GlyphNotFound(glyph_id.clone()))?`, `.map_err(|_| SlugError::LengthOverflow)?`, `StoreError::MissingEntity { kind, id }` struct literals. Every copy drifted a little: different `kind` strings, eager `ok_or` cloning ids on the success path, lookups cloning an id just to pass it by value. The rules below keep a failure defined once and named at the call site.

## The rule

**A failure that recurs for the same reason is constructed in exactly one place.** Call sites say _what_ they need (`require_glyph`, `or_overflow`, `or_missing`), not _how_ to build the error.

`ok_or_else` with a site-specific error is fine. A message that only makes sense at one site, such as `InvalidLibValue("missing value")` in a parser, belongs inline. The second time the same error appears for the same reason, extract it.

## Error helpers that already exist

Use these before writing an error by hand:

| Failure                                        | Helper                                                                                                                           | Crate                                       |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| Entity missing from a `Font`                   | `font.require_glyph(&id)?`, `require_layer`, `require_layer_mut`, `require_layer_owner`, `require_source`, `require_axis`        | `shift-font` (`ir/font.rs`)                 |
| Entity missing from any other lookup           | `lookup.require(&id)?` (`Require` + `EntityRef`; the id's type picks the `*NotFound` variant)                                    | `shift-font` (`error.rs`)                   |
| Contour, point, or anchor missing from a layer | `layer.require_contour_mut(id)?`, `require_point_mut`, `require_point_contour`                                                   | `shift-font` (`layer_edit.rs`)              |
| Length or offset overflow                      | `a.checked_add(b).or_overflow()?`, `u32::try_from(n).or_overflow()?`, `length::to_u32`, `length::ensure_total`, `length::within` | `shift-slug` (`length.rs`)                  |
| Row missing from the store                     | `lookup.or_missing("glyph", &id)?`, `order_index(conn, table, kind, &id)?`                                                       | `shift-store` (`error.rs`, `change_set.rs`) |
| Retained-source index out of range             | `identity.glyph_id(index)?`, `glyph_index`, `axis_id`, `source_id`                                                               | `shift-bridge` (`SourceIdentity`)           |

`?` converts between crate errors through the existing `From` impls (`SlugError` into `AuthoredSlugError`, `BridgeError` and the backends error; `CoreError` into `StoreError`). Do not name another crate's error variant at a call site, as in `shift_slug::SlugError::LengthOverflow`; call that crate's helper and let `?` convert.

## Adding a helper

When an error pattern repeats and no helper fits, add one next to the data it describes:

- **Lookups on an owner** (`Font`, `GlyphLayer`, `SourceIdentity`): add a `require_*` method beside the `Option` lookup. It takes the id by reference and returns `Result<&T, _>`.
- **One error for many value types** (all ids, all checked operations): add an extension trait on `Option<T>` or `Result<T, E>` whose method names the failure (`require`, `or_overflow`, `or_missing`), plus one impl per input type. A macro like `entity_ref!` keeps one line per variant.
- **A repeated query or computation that ends in the error** (the same SQL with `.optional()?`): extract the whole operation as one function, not just its error.
- **Only one crate needs it**: keep it `pub(crate)`. Export it only when another crate would otherwise build the same error.

Every new helper gets Rustdoc with an `# Errors` section (see `rustdoc`) and a unit test of the failure it produces.

## Error types

A failure that callers may handle, test, or wrap is a type, not text.

- A function that can fail for more than one reason returns a `thiserror` enum with one variant per reason. Never return `Result<_, String>` or add a `{ message: String }` variant to carry another error.
- Wrap another module's error with `#[from]` or `#[source]`; never `.map_err(|error| error.to_string())`. Include `{0}` or `{source}` in the wrapping message when callers surface errors through `to_string()`, so the detail survives.
- Convert to text only at a boundary that requires it: a NAPI or MCP message, or a foreign API such as fontir's `Error::InvalidEntry`.
- A public error type cannot hold a private one. Export a wrapped error type alongside the public error that contains it.
- When new code calls an existing function that returns `String` errors, type that function's error first instead of wrapping the string again. Inherited stringly errors spread through every caller that adapts to them.
- **Never turn a failure into an empty answer.** `unwrap_or_default()`, `unwrap_or(0)` or `.ok()` on a `Result` makes "the font is unreadable" look like "there is nothing here", and the caller cannot tell. Return the error; where a boundary must answer anyway (a WASM read), give the answer a variant that says why, as `ShapedParagraph::Unshapable { reason }` does.

```rust
// Before: an unreadable GSUB lists no substitutions; an index past u32 gives an empty range.
let substitutions = shaper.feature_substitutions(tag).unwrap_or_default();
let start = u32::try_from(index).unwrap_or(0);

// After
let substitutions = shaper.feature_substitutions(tag)?;
let start = u32::try_from(index).or_overflow()?;
```

## Lookups and ids

- Font-level ids (`GlyphId`, `LayerId`, `SourceId`, the axis, instance, kerning group and metric ids) are interned and `Copy`: one word each. Pass them by value, `fn glyph(&self, id: GlyphId)`, and copy rather than clone them (clippy's `trivially_copy_pass_by_ref` and `clone_on_copy` enforce it).
- Ids inside a layer (`PointId`, `ContourId`, `ComponentId`, `AnchorId`, `GuidelineId`) own their text, because interned text is never freed. Take them by reference: `fn point(&self, id: &PointId)`; by value only when the function stores or returns it. Never pass `&id.clone()`; borrow the id you have.
- Never clone an id only to build an error that is probably not returned. Use `ok_or_else` or the helpers above, which format the id only on failure. `ok_or(CoreError::X(id.clone()))` clones on every call, including successful ones.
- `Option` lookups (`font.glyph(id)`) are for "absent is a normal answer". Use `require_*` when absence is an error for this caller.

## Arithmetic and conversions

- Lengths, offsets, and counts that reach packed buffers use checked arithmetic with `.or_overflow()?`. Keep the `checked_add`/`checked_mul` visible at the call site.
- Integer narrowing uses `try_from` with `.or_overflow()?` or `length::to_u32`. Never use `as` for a narrowing conversion that can lose data.
- Bit-packed fields with a limit below their integer type go through `length::within(value, MASK)?`.

## Use the language

Let the type system state intent instead of comments, flags and tuples. Clippy enforces some of this (see `[workspace.lints.clippy]`); the rest is for review.

- **An enum, not a `bool`, for any choice with consequences.** `persist(change_set, AfterPersist::KeepUnsaved)` says what happens; `persist(change_set, false)` doesn't, and a `!flag` deep inside can silently discard data. Keep `bool` for genuine yes/no facts (`is_closed`, `smooth`).
- **Collect into domain types.** A collection type that callers build in loops implements `FromIterator` and `Extend`, so `let location: DesignLocation = axes.map(|a| (a.id(), a.default())).collect();` replaces `let mut location = DesignLocation::new(); for … { location.set(…) }`.
- **Name a type instead of a tuple** once it has three fields, is returned from a function, is stored in a collection, or is destructured with `_` placeholders. Points are `kurbo::Point`, not `(f64, f64)`.
- **Name a type instead of nesting generics.** When a signature stacks three or more of `Result`, `Vec`, `Option` and `HashMap`, each layer means something; give it a name. An `Option` inside a `Vec` usually is an enum with a reason.

```rust
// Before: what does a `None` paragraph mean?
fn shape_paragraphs(…) -> Result<Vec<Option<Vec<ShapedRun>>>, ShapingFailure>

// After
pub enum ShapedParagraph {
    Runs { runs: Vec<ShapedRun> },
    Unshapable { reason: String },
}
fn shape_paragraphs(…) -> Vec<ShapedParagraph>
```

- **Phases are an enum, events are an enum.** A struct whose `Option` fields and `bool`s are only valid in some combinations is a state machine written as loose fields; make each phase a variant that holds what that phase has. Several methods that each adjust the same fields for one kind of event (`applied`, `went_back`, `committed`) become one `fn on(&mut self, event: EditEvent)` with a `match`. What changed is one flag set (`FontChangeImpact`), not a `bool` or a revision counter per concern.
- **Each part says what "the same" means.** A derived `PartialEq` over a whole request, used to decide whether to recompile or re-read, compares fields that don't matter and can't express "this part changed only by appending". Give each part its own comparison, as `CompileInput::recompiles` does for `UnitsPerEm`, `FeatureSource` and `ShaperAxes`, and let the owner combine them.

```rust
// Before: one derived equality decides what a change costs.
if attempt.units_per_em != next.units_per_em
    || attempt.feature_source != next.feature_source
    || attempt.axes != next.axes { … }

// After: each input type answers for itself.
let recompiles = self.units_per_em.recompiles(&next.units_per_em)
    || self.feature_source.recompiles(&next.feature_source)
    || self.axes.recompiles(&next.axes);
```

- **A method, not a free function**, when the first argument is the owner: `font.master_layers(glyph)`, not `master_layers(font, glyph)`. Extension traits are fine across crates.
- **Entity kinds are an enum.** `EntityKind::Glyph` with `Display`, never `kind: "glyph"` or a `kind: &str` parameter, so kinds can't drift and callers can match them.
- **Convert elements with `From` impls and collect directly into the field's type** (`Box<[T]>`, `Vec`, a map); destructure the source once instead of repeating `self.x.` per field. Reported by `pnpm scan:rust --kind field-copy-conversion`.
- **Write `.collect()` and let the field, argument or return type pick the collection**; use a turbofish or a typed `let` only when nothing else fixes the type, and never collect just to iterate again (clippy's `needless_collect`). Reported by `pnpm scan:rust --kind collect-turbofish`.
- **Repeated conversion shapes get one helper.** `.into_iter().map(Into::into).collect()` written ten times in a `From` impl becomes `convert_all(v)`; `changed.then(|| read()).transpose()?` becomes `if_changed(changed, read)?`.
- **Let the type do the adapting.** When a call site needs `.to_string()`, `into_inner()`, `from_raw(…)` or a `.map(…)` to pass a value along, implement the trait instead: ids implement `ToSql`/`FromSql` (`params![glyph.id()]`, `row.get("glyph_id")?`), and conversions implement `From`/`Into`.
- **Name the intent with a constructor.** `font.location_at(&coordinates)` and `font.default_location()` say what a value is; a `zip`/`map`/`collect` at the call site says how it's built.
- **Method paths over closures** that only call a method: `.map(Axis::id)`, not `.map(|axis| axis.id())`.
- **Points and vectors are `kurbo::Point`/`Vec2`**, and blending uses their operators (`point += weight * master_point`), not paired `x`/`y` arithmetic.
- **Prefer `let … else`, `if let` chains (edition 2024) and early returns** over nested `match` or `if let`, and name non-trivial intermediate values.
- **A closure does one thing.** A `filter_map` whose body builds a tuple with two `?`s, a dereference and a conversion reads as noise; the missing piece is usually a type that owns the mapping (`ShaperGlyphOrder`) or a named method on it.

```rust
// Before
self.shaper_glyphs = glyph_order
    .iter()
    .enumerate()
    .filter_map(|(index, glyph_id)| Some(((*glyph_id)?, u32::try_from(index).ok()?)))
    .collect();

// After: the order type knows its glyphs' positions.
self.glyphs.set_glyph_order(glyph_order);
```

## Data structures

An edit should cost what the edited thing costs, not what the font costs. A `Font` is copied on the first write of every edit, so whatever it holds is copied or rescanned on every keystroke.

- **Answer a repeated query from an index, not a scan.** A lookup that walks every glyph, layer, group or pair (`iter().find(…)`, `iter().filter(…).collect()`) is a missing index. Keep one beside the data and update it where the data changes: `FontIndex` maps layers to owners and component bases to the layers that use them; `KerningGroups` maps each glyph to its groups.
- **Declare indexes, don't hand-maintain them.** Indexes that must agree are fields of one type, like `FontIndex`: a `UniqueIndex` for each key that may be held once, a multimap for the rest. One entries type (`IndexEntries`) says what an item files under each index, so inserting and removing are written once. Insert into a copy, which is O(1) for persistent collections, and keep it only on success; a rejected edit then leaves the font unchanged without a separate validation pass.
- **Wrap third-party collections.** Font state that grows with the font uses the persistent collections in `ir/persistent.rs` (`PersistentMap`, `PersistentSet`, `UniqueIndex`, `PersistentMultiMap`, `PersistentListMultiMap`, `PersistentOrdMap`, `PersistentVec`), which copy in O(1) and change in O(log n). Only that module names the backing crate; add the operation you need there instead of reaching through to `imbl`.
- **Collect a query's result into a type that states its order and uniqueness**, such as a `BTreeSet`, rather than pushing, sorting and deduplicating a `Vec`.
- **Change only what changed.** Compare persistent copies with `ptr_eq` before walking them, and diff two versions of a collection rather than rebuilding everything derived from it.

## Rules the editor needs

**One owner per rule.** Before writing a numeric or domain rule (normalization, interpolation, metrics, geometry), search shift-font and its libraries for it and call that; never write a second copy with different edge handling. Axis normalization once had five copies across shift-font, shift-backends and shift-slug, each clamping and comparing differently. Reported by `pnpm scan:rust --kind duplicate-body`.

**Wrap the library's rule; don't copy it.** When a font library Shift builds on (fontc, fontir, fontbe, fontdrasil, fea-rs, glyphs-reader, norad, skrifa, read-fonts, write-fonts, HarfRust, kurbo) exposes the rule as a public function, call it, wrapped once in shift-font beside the type it serves, so the editor and export answer alike: axis normalization goes through fontdrasil's `CoordConverter`, open corners through `fontdrasil::open_corners`. A copy drifts on the library's next release without failing anything; fontdrasil 2.0 changed how decreasing axis mappings normalize, and Shift's copy then disagreed with every compiled font.

- Keep only what the library doesn't decide, and say why beside it (Shift snaps a normalized `1e-15` to exactly `0` because its variation model only recognises an exact default).
- Build the library's value once where a hot path would otherwise rebuild it per call, and measure: `DesignNormalization` holds its converter because region evaluation normalizes for every support.
- When the library keeps the rule private, ask upstream to expose it before copying. A copy that must stay meanwhile gets a test that runs the library on the same inputs and compares, as `variation_oracle.rs` does for normalization.

When the editor needs a shift-font rule synchronously, write it as a plain-data function in shift-font that native callers use, and export that function from `crates/shift-wasm`. Don't write a second Rust version for WebAssembly, and don't re-declare its types there: a `FontFeature` or `FeatureGroup` copied into `shift-wasm` beside `shift-text`'s is two enums to keep in sync. Derive the wire format on the original type, or convert with one `From`. The export only converts numbers to and from shift-font types; "Choosing a route" in `crates/shift-wasm/docs/DOCS.md` says what belongs there and what may stay in TypeScript.

## The scan ratchet

`pnpm scan:rust --check` (CI) holds every `shift-scan` kind's count per crate to `crates/shift-scan/baseline.json`: a branch may not add a hit, and a branch that fixes some runs `pnpm scan:rust --update` and commits the lower number. The kinds are listed in `crates/shift-scan/docs/DOCS.md`.

## The lint ratchet

Clippy lints that still have hits are listed in `clippy-ratchet.json` with their hits per crate (`src` for library and binary code, `tests` for the rest), and `pnpm lint:rust-ratchet`, CI's clippy step, fails when a count differs from the file.
To lower one, fix hits and run `pnpm lint:rust-ratchet --update`; a lint at 0 everywhere moves to `[workspace.lints.clippy]` in `Cargo.toml`.

## Review checklist

- [ ] No `CoreError::*NotFound`, `SlugError::LengthOverflow`, or `StoreError::MissingEntity` built inline where a helper above applies.
- [ ] No other crate's error variant named at a call site.
- [ ] No id cloned on a lookup's success path just for its error.
- [ ] No new `Result<_, String>`, `{ message: String }` error variant, or `.to_string()` of an error before a text boundary.
- [ ] Code that calls a function with `String` errors types that error rather than wrapping the string.
- [ ] Any error built at two or more sites for the same reason has one helper, with Rustdoc and a test.
- [ ] No new `bool` parameter for a choice with consequences; no new `kind: "…"` string.
- [ ] Collections built in loops implement `FromIterator`/`Extend` and are collected.
- [ ] No tuple of three or more fields returned, stored or destructured with `_`; no free function whose first parameter is its owner.
- [ ] No `unwrap_or_default()`, `unwrap_or(…)` or `.ok()` that turns an error into an empty answer.
- [ ] No signature nesting three or more generic layers; no `filter_map` closure doing two `?`s into a tuple.
- [ ] No `Option`/`bool` fields standing in for phases; no derived `PartialEq` deciding what a change costs; events and change kinds are enums or flag sets.
- [ ] No rule (normalization, interpolation, geometry) written again beside the one shift-font owns or a font library exposes publicly; a library rule is called through one wrapper; no `duplicate-body` hit the branch added.
- [ ] Conversions collect straight into the field's type; no turbofish where the field, argument or return type fixes it.
- [ ] No type re-declared in `shift-wasm` that `shift-font` or `shift-text` already defines.
- [ ] No scan of the whole font for a query an edit repeats; indexes that must agree are declared on one type and updated through a copy; no `imbl` outside `ir/persistent.rs`.
- [ ] `cargo fmt`, `cargo clippy` for the affected crates, and their tests pass.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.