Scanning 312k LOC of Rust 1.99 without rustc
Right after Laravel released laravel/rust-framework, I ran my syntax-tree scanner cargo-modernize over v0.1.5. The workspace has 312,395 lines of Rust across 23 crates (764 .rs files), declares rust-version = "1.99" and edition = "2024", and ships with agent skills for Claude Code and Cursor.
The scanner finished with zero parse errors and reported 396 older patterns across 29 rules. Here are the verified highlights:
| Pattern in repo | Modern Rust | Since | Sites |
|---|---|---|---|
Duration::from_secs(60) | Duration::from_mins(1) | 1.91 | 111 |
x.map_or("", f) | x.map_or_default(f) | 1.98 | 86 |
assert!(matches!(x, P)) | assert_matches!(x, P) | 1.96 | 81 |
if c { Ok(()) } else { Err(e) } | c.ok_or(e) | 1.98 | 41 |
s.strip_prefix('{')?.strip_suffix('}') | s.strip_circumfix('{', '}') | 1.98 | 7 |
String::from_utf8_lossy(&v).into_owned() | String::from_utf8_lossy_owned(v) | 1.99 | 5 |
path.as_os_str().is_empty() | path.is_empty() | 1.98 | 5 |
format!("{}", ext.to_string_lossy()) | format!("{}", ext.display()) | 1.87 | 2 |
while !s.is_char_boundary(i) { i -= 1; } | s.floor_char_boundary(i) | 1.91 | 1 |
Some of those are taste (Duration::from_secs(60)). Others drop an allocation (String::from_utf8_lossy_owned, OsStr::display) or replace a hand-rolled UTF-8 loop (floor_char_boundary). And one of the 396 hits turned out to be my own false positive, which brings up the main constraint of scanning Rust without rustc.
The type wall
In crates/http/src/session/store.rs:234 of laravel/rust-framework:
if metadata .modified() .map_or(true, |modified| is_expired(modified, lifetime)) { return Ok(None); } My option-is-none-or rule flagged this. That's wrong: std::fs::Metadata::modified() returns io::Result<SystemTime>, not an Option, so is_none_or doesn't even exist on the receiver. On the concrete syntax tree (CST), .map_or(true, |x| ...) looks identical on both types.
Clippy avoids this because it sits on TyCtxt and sees resolved types, traits, and autoderef chains. The price is a full compile. If your workspace builds in two seconds and Clippy already catches the stdlib upgrades you care about, you don't need a CST scanner. Use Clippy.
You reach for a parser-only tool when you want sub-second feedback on a 300k–500k LOC repo, or when you want to check a diff before compilation finishes. Once you accept that TyCtxt isn't there, you have to draw a hard boundary in the rule set. Out of 145 entries in cargo-modernize v0.3.0 (distilled from 1,837 triaged upstream rust-lang/rust stabilizations between 1.64 and 1.100):
- 86 are executable rules (78 Rust CST rules, 6
Cargo.tomlrules, 2 CI/text rules) where syntax shape, local imports,#[rustversion],#![no_std]tier,constcontext, and SemVer position give enough signal. Every rule carries paired positive and negative fixtures thatrustccompiles in CI. - 59 stay out of the detector as
C4type-wall guidelines (RwLockWriteGuard::downgrade,extract_if,as_chunks,Box::new_uninit, strict provenance). They show up only when someone queriesguidelines listorexplain.
Anything that needs type inference belongs in Clippy (cargo xtask export-clippy-candidates tracks those candidates). Trying to fake type resolution with clever AST regexes creates noise people turn off on day one.
Cutting ra_ap_syntax overhead for batch scans
cargo-modernize-core pins ra_ap_syntax = "=0.0.352", ra_ap_parser = "=0.0.352", and rowan = "=0.17.0" behind a single adapter module (syntax_adapter.rs). My first version called ra_ap_syntax::SourceFile::parse on every file, and it used more CPU and RAM than a simple scanner should.
Digging into ra_ap_syntax explained why. SourceFile::parse is tuned for an IDE, not a one-shot CLI:
-
ParseNodeDropperhands green trees to a background thread that holds memory for 100 ms intervals so IDE requests don't stall on drops. -
ra_ap_syntax::validation::validatewalks the entire red tree a second time on every file. -
NodeCachehashes subtrees recursively for incremental reparsing, which a batch scan never does.
Skipping SourceFile::parse and driving ra_ap_parser directly cut out all three:
pub(crate) fn parse_source_file(body: &str, edition: RustEdition) -> ParsedSource { let ra_ed = edition.to_ra(); let lexed = LexedStr::new(ra_ed, body); let parser_input = lexed.to_input(ra_ed); let parser_output = TopEntryPoint::SourceFile.parse(&parser_input); drop(parser_input); let mut error_count = 0usize; let green = with_fast_green_builder(lexed.len(), |builder| { error_count = build_green_from_lexed_output(&lexed, &parser_output, builder); builder.finish() }); error_count += lexed.errors().count(); ParsedSource { root: SyntaxNode::new_root(green), error_count, } } In the workspace scanner, files don't even hit FastGreenBuilder right away. They stop at LazyParsedSource, which holds LexedStr, ra_ap_parser::Output, and a small token summary. If no active rule matches the file's token prefilter, the scanner drops the handle without building or freeing a rowan::GreenNode tree at all.
catalog/build.rs applies the same idea to the rule database. It parses all upstream release inventories (1.56–1.100) and rule TOMLs at build time, fails compilation if a rule sets const = true without a matching #[rustc_const_stable] entry, and emits &'static tables into cargo-modernize-catalog (#![no_std], MSRV 1.85, zero runtime dependencies). Startup does zero TOML parsing.
On an M5 Pro (release binary, idle host, median of warm runs): cargo-modernize scans its own 4-crate repo in 46.6 ms (warm no-op cargo clippy takes 95.5 ms) and an external 477k-LOC workspace in 143.1 ms (about 3,200 .rs files/s, zero panics).
Turning a borrow into a move without a borrow checker
Method renames like path.as_os_str().is_empty() to path.is_empty() are easy. Rust 1.99's String::from_utf8_lossy_owned is not:
// Before: borrows &stdout, copies into a new String String::from_utf8_lossy(&stdout).into_owned() // After (Rust 1.99): moves stdout and reuses its Vec<u8> allocation String::from_utf8_lossy_owned(stdout) That rewrite turns a shared borrow into a move. In v0.2.1, my liveness check only looked at subsequent statements in the immediate block. When I ran v0.2.1 on laravel/rust-framework, it reported 7 sites, including String::from_utf8_lossy(&self.body).into_owned() in src/testing/response.rs:284. You can't move self.body out of &self.
Looking closer turned up four other ways a single-block check breaks real code with E0382 or E0505:
- Same-statement siblings like
(String::from_utf8_lossy(&buf).into_owned(), buf.len()), wherebufis read again inside the same expression. - Enclosing
loop,while, orforblocks, where moving an outerbufbreaks iteration two (unless the loop header bindsbuffresh each time, likefor buf in chunks). - Closures capturing an outer binding, where a move changes
FnorFnMutintoFnOnce. - Self-shadowing in the other direction:
let buf = String::from_utf8_lossy(&buf).into_owned();is safe to move even when later lines referencebuf, because theletshadows the old binding.
For v0.3.0, I replaced that check with is_safe_to_move_after (crates/cargo-modernize-core/src/preds.rs). It walks up parent STMT_LIST, LET_STMT, LOOP_EXPR, WHILE_EXPR, FOR_EXPR, and closure nodes, tracks shadowing and loop-header bindings, and rejects field borrows whose root stays live. Re-running v0.3.0 on laravel/rust-framework dropped &self.body and the other unsafe borrows, leaving the 5 owned Vec<u8> sites like Output::Captured { stdout, stderr } in crates/console/src/console/output.rs:190 where into_output(self) already takes self by value.
Prompting coding agents to "write modern Rust"
Humans miss recent stdlib additions because Rust moves fast; coding agents miss them because their training weights tilt toward older crates. Since cargo-modernize also ships a compact CLI for agents, I tested whether telling Claude or Codex to "write modern Rust 1.98 / Edition 2024" works on its own.
I put together 6 tasks covering greenfield Rust 1.98 / Edition 2024 code, PR --diff cleanup, C4 type-wall idioms, #![no_std] / const limits, strict MSRV 1.75 compliance (checked with cargo +1.75.0 check), and Cargo/CI rules. Each task ran once with zero retries across 3 models and 3 PATH-isolated setups (baseline, prompt-only, and cargo-modernize v0.2.1): 54 runs total, graded with 80% deterministic assertions and 162 cold blind reviews.
| Model | Baseline | "Write modern Rust" prompt | cargo-modernize | Findings left (base / prompt / tool) |
|---|---|---|---|---|
| Claude Opus 5.5 | 91.1% | 88.9% | 100.0% | 10 / 9 / 0 |
| Claude Sonnet 5.5 | 78.9% | 81.1% | 88.9% | 16 / 14 / 6 |
| Codex (GPT-6.2-Astra) | 92.2% | 95.6% | 98.9% | 3 / 0 / 0 |
| Pooled (270 assertions / arm) | 87.4% | 88.5% | 95.9% | 29 / 23 / 6 |
Prompting moved the pooled score from 87.4% to 88.5% (+1.1 points), and Opus 5.5 scored worse with the prompt than with nothing at all (91.1% down to 88.9%). Handing the models the CLI pushed Opus to 90/90 in less wall time than baseline (43.6s vs 53.3s median) and jumped Sonnet 5.5 by 10 points.
Keeping the context small mattered here too. Dumping every rule guide with examples costs about 73.4k tokens. cargo modernize guidelines list --msrv 1.98 --edition 2024 --format compact shrinks step 1 to 4.4k tokens (1.8k with --impact high), so the agent batches explain only for the IDs it needs and verifies its edits with --diff --format compact.
The eval wasn't a clean sweep. All three models already hit 100% on the 1.81–1.96 C4 idioms in Task 03 (RwLockWriteGuard::downgrade, extract_if, as_chunks, #[expect]) on baseline. Sonnet ran slower with the tool (34.3s vs 18.1s) and skipped medium-impact C4 rules whenever it passed --impact high. Task 05 lost a pooled point on a div_ceil overflow edge case. On the upside, an earlier v0.1.0 run caught a real bug in my own int-div-ceil doc entry (it claimed behavior = "none" while mentioning overflow panics), which got four catalog entries fixed before v0.2.1. Also, none of the 18 runs called --fix on their own; every model preferred editing files by hand and using the scanner as a read-only check.
Everything is MIT / Apache-2.0 at github.com/Dankosik/cargo-modernize, and the starter crates, graders, and raw results.json from the 54 runs live in benchmarks/agent-eval-2026-11-v021/.
原文:https://www.a8q9.cn/en/article/scanning-312k-loc-of-rust-1-99-without-rustc-587710.html