# Rust 1.100 Guidelines

> Modern Rust 1.100 (Edition 2024) patterns, automated Clippy baseline, #![no_std] rules, and non-lintable safety checklist.

Concise reference for `rust/` (`zwire`). Empirically verified against `rustc 1.100.0` (`rust/rust-toolchain.toml`, Edition 2024, `resolver = "3"`).

---

## 1. Obsolete Pre-1.100 Patterns → Modern Rust 1.100 Replacements

Prefer standard-library Rust 1.100 / Edition 2024 features over legacy crates or pre-2024 workarounds:

| Obsolete / Superseded Pattern | Rust 1.100 Replacement | Stabilized |
| :--- | :--- | :---: |
| `scopeguard` crate or manual rollback structs | `core::mem::DropGuard::new` / `DropGuard::dismiss` | 1.100 |
| `#[cfg(feature = "std")] impl std::error::Error` | Unconditional `impl core::error::Error` (works in `#![no_std]`) | 1.81 |
| `cfg-if` crate or paired `#[cfg]` / `#[cfg(not)]` | `core::cfg_select! { ... }` | 1.95 |
| `itoa` crate or `n.to_string()` for integer formatting | `core::fmt::NumBuffer` + `i*::format_into` (zero-alloc) | 1.98 |
| `#[allow(...)]` lint suppressions | `#[expect(lint, reason = "...")]` + `unfulfilled_lint_expectations` | 1.81 |
| `core::convert::Infallible` / dummy empty enums | Never type `!` (skips `unused_must_use` in `Result<(), !>`) | 1.92–1.100 |
| Nested `if let` / `match` pyramids | Edition 2024 `let`-chains (`if let Some(a) = x && let Some(b) = y`) | 1.88 |
| `cell.set(f(cell.get()))` | `Cell::update(f)` | 1.88 |
| Explicit `v as &dyn Super` / `as_any()` boilerplate | Trait upcasting coercion (`&dyn Any + Send + Sync` → `&dyn Any`) | 1.86 |
| Manual drain-filter / conditional pop loops | `Vec::extract_if`, `BTreeMap::extract_if`, `Vec::pop_if` | 1.87–1.88 |
| Manual chunking / disjoint mutable slice splits | `slice::as_chunks`, `slice::array_windows`, `slice::get_disjoint_mut` | 1.86–1.94 |
| `Box::new([0; N])` (stack-overflow risk on large arrays) | `Box` / `Rc` / `Arc::new_zeroed` | 1.92 |
| Non-`Copy` `core::ops::Range` stored in structs | `core::range::Range` (`Copy`) | 1.96 |
| `resolver = "2"` in workspace `Cargo.toml` | `resolver = "3"` (MSRV-aware dependency resolution) | 1.85 |
| `once_cell` / `lazy_static` | `std::sync::LazyLock` / `core::cell::LazyCell` (with mutation helpers) | 1.80 / 1.94 |
| Boxed `Pin<Box<dyn Future>>` closures / over-capturing RPIT | `async \|\| {}` closures & RPIT `use<...>` precise capturing | 1.85 |
| `#[test]` custom `matches!` panic wrappers | `core::assert_matches!` / `debug_assert_matches!` & `if let` guards | 1.95 |

> [!NOTE]
> **Not yet stable in `rustc 1.100.0`:** `std::sync::nonpoison::Mutex` remains behind unstable `#![feature(nonpoison_mutex)]`. Keep `std::sync::Mutex::lock().unwrap_or_else(PoisonError::into_inner)` in `SyncScope`.

---

## 2. Automated Enforcement (`rust/Cargo.toml` & `rust/clippy.toml`)

Do not duplicate linter rules in reviews or docs. The workspace enforces the following automatically via CI (`-D warnings` on both `--all-features` and `--no-default-features`):

- **`[workspace.lints.rust]`:** `unsafe_code = "forbid"`, `missing_docs`, `missing_debug_implementations`, `unreachable_pub`, `let_underscore_drop`, `elided_lifetimes_in_paths`, `trivial_casts`, `unused_qualifications`, `unfulfilled_lint_expectations`, Edition 2024 capture/upcasting lints (`impl_trait_overcaptures`, `deref_into_dyn_supertrait`).
- **`[workspace.lints.rustdoc]`:** `broken_intra_doc_links`, `private_intra_doc_links`, `bare_urls`, `invalid_html_tags`, `unescaped_backticks`.
- **`[workspace.lints.clippy]`:** `all`, `pedantic`, `nursery`, `cargo`, plus restriction guardrails (`allow_attributes`, `allow_attributes_without_reason`, `alloc_instead_of_core`, `std_instead_of_core`, `clone_on_ref_ptr`, `mem_forget`, `rc_buffer`, `rc_mutex`, `str_to_string`, `dbg_macro`, `todo`, `unimplemented`).
- **`rust/clippy.toml`:** `msrv = "1.100"`, `allow-{expect,unwrap}-in-tests = true`, and `disallowed-methods` blocking `std::process::exit` and `std::process::abort`.
- **Deliberate exclusions:** `redundant_pub_crate` is allowed (conflicts with `rustc`'s `unreachable_pub`), and `redundant_imports` is omitted because dual `std`/`no_std` crates require explicit `use alloc::*` imports even when `std::prelude` is active.

---

## 3. Rules Clippy Cannot Enforce (Mandatory Checklist)

Static lints cannot verify runtime re-entrancy, reference-cycle freedom, lock ordering, or cross-language protocol parity. Every PR touching `rust/` must uphold these invariants:

1. **Zero-Borrow & Zero-Lock User Callbacks:** Release every `RefCell` borrow (`Scope`) and `MutexGuard` (`SyncScope`) *before* invoking any user closure (`compute`, `eq`, `updater`, `subscriber`, `on_watched`, `on_unwatched`, cleanup, instrumentation). In `Debug::fmt` on interior-mutable handles (`Scope`, `SyncScope`, `Draft`, `SyncBridge`, `ReactiveCollection`), always use `try_borrow()` / `try_lock()` so debug logging never panics or deadlocks.
2. **Weak Back-References (`WeakScope` / `WeakSyncScope`) + Drop-Counter Tests:** Any closure stored inside a `Scope` or `SyncScope` (hooks, `InspectorHook`, `SyncBridge`, `ReactiveCollection`, `on_watched`) MUST capture a weak handle (`scope.downgrade()`), never a strong handle. Every new scope-attached bridge or hook must be verified in `scope_drops_without_rc_reference_cycles_across_all_layers` (`rust/crates/zwire/tests/integration.rs`).
3. **`DropGuard` Dismissal Ordering:** Guard depth counters (`batch_depth`, `eval_depth`, `in_draft`) and rollback buffers (`try_settle`) with `core::mem::DropGuard::new`. Call `DropGuard::dismiss` *only* after all fallible/panicking operations have succeeded so unwinds and early `?` returns always restore invariants.
4. **`SyncScope` Optimistic Concurrency Retry:** Evaluate `SyncScope::computed` closures completely unlocked; before committing the result under the mutex, verify every recorded `(NodeId, version)` still matches and retry on concurrent writes.
5. **Strict 2-Tier Star Topology & Zero External Runtime Dependencies:** Companion crates (`zwire-tx`, `zwire-protocol`, `zwire-collections`) must never depend on each other and must keep `[dependencies]` free of external crates. Attach per-scope companion state via `zwire_core::internal::get_or_init_scope_ext` (`TypeId` map) and the 5 lazy extension slots.
6. **Dual `no_std + alloc` Prelude Hygiene:** Never rely on `std::prelude` items (`Box`, `String`, `Vec`, `ToOwned`) or inline `alloc::...::` paths in library code. Import them explicitly at module top (`use alloc::borrow::ToOwned;`, `use alloc::boxed::Box;`) and verify both `--no-default-features` and `-p zwire --no-default-features --features "core tx collections protocol"`.
7. **Single-Copy Arena & Zero-`Clone` Reads:** Store each payload once in generational slot arenas (`u32` indices in sorted blocks). Never add unnecessary `T: Clone` bounds to `Scope` storage, `with`/`get_rc` reads, or `Collection` storage.
8. **RAII Guards Require `#[must_use]` + Idempotent Teardown:** Every handle whose `Drop` performs cleanup (`Subscription`, `SyncSubscription`, `HookGuard`, `SyncHookGuard`, `OptimisticGuard`, `SyncBridge`) must declare `#[must_use = "..."]`, provide an idempotent manual teardown method, and delegate `Drop` to it.
9. **Cross-Language Parity (`spec/conformance.json`):** Changes to optimistic rebase semantics, `Collection` Top-K ordering/pruning, or `WireValue`/JSON hydration must update `spec/conformance.json`, run `mise run sync:spec`, and pass both Rust (`rust/crates/zwire/tests/conformance.rs`) and TypeScript (`ts/tests/conformance.test.ts`).
10. **Narrow `#[expect]` Policy:** Never add `#[allow]` in workspace Rust code. Use `#[expect(lint, reason = "...")]` on the narrowest item possible so obsolete suppressions surface automatically via `unfulfilled_lint_expectations`.

## Compiler floor and synchronization policy

The supported compiler floor is the Rust version in the released manifest, currently 1.100. The workspace tests that exact toolchain. A later release can raise the floor through a documented manifest and CI change. The active engine uses `DropGuard` for rollback on unwinding, `AtomicUsize::try_update` for non-wrapping identities and `cfg_select!` for standard-library boundaries. Integer JSON encoding uses `fmt::NumBuffer`; infallible transaction settlement uses `Result<(), !>`. Supporting an older compiler would require maintaining alternative implementations of these paths.

`SyncScope` retains a per-scope mutex. Its read path can promote a computed, update dependency links, and commit a versioned cache entry. A shared read lock would only cover immediate atom and clean-cache hits. Per-node sharding would also need a lock order across disposal, propagation, and multi-atom transaction publication. Values are cloned as `Arc` snapshots while locked, and callbacks run after unlocking. The local `Scope` remains available with `alloc` on embedded targets. A portable multi-core lock implementation would also need equivalents for thread identity, poisoning, and per-thread batching currently provided by `std`, so this release exposes `SyncScope` under `sync` and `std`.
