rto_exec/adapter/clippy.rs
1//! `clippy` — the Rust toolchain's own linter, normalised for a report that is
2//! **never stored**.
3//!
4//! This adapter has the same shape as every other one in this module: native
5//! analyzer output in, a [`NormalizedReport`] out, with the identity recipe and
6//! the severity mapping written beside the parser that needs them. What it does
7//! **not** have is a place in [`ADAPTERS`], and that omission is the decision
8//! rather than an oversight.
9//!
10//! # Why it is not in the registry
11//!
12//! [`ADAPTERS`] is the table `roteiro security ingest` consults, so anything in
13//! it can be filed as a findings layer. Clippy must not be, and leaving it out
14//! is what makes that structural instead of a rule someone has to remember:
15//! there is no `--analyzer clippy` for `ingest` to accept, no
16//! `security:clippy:<worktree>` layer key to collide, and no path from this file
17//! to [`rto_graph::Store::replace_findings_layer`].
18//!
19//! ADR-0020 v1.1 states the reason, and it is about what a lint *is*. An
20//! advisory id is **assigned**, and assignment is a promise: `RUSTSEC-2020-0071`
21//! will mean the same thing in five years, which is why it earns a row in a
22//! store. A lint name is a **symbol in a compiler** — renamed, removed, or moved
23//! between groups at the compiler's discretion, with the old name surviving only
24//! as a deprecation alias. The first is a durable fact about the repository; the
25//! second is a tool's opinion about the code as it stands today, for the person
26//! who asked.
27//!
28//! Storing the second is what produced every identity problem the investigation
29//! behind ADR-0020 found. A layer key renders `<prefix>:<analyzer>:<worktree-id>`
30//! and nothing else, `analyzer_version` is in neither the finding key nor the
31//! layer key, and the column is `UNIQUE` — so two runs of one commit differing
32//! only in toolchain version or feature set would collide, silently replace each
33//! other, and report the displaced findings as *removed*, which reads as
34//! **fixed**. For every stored analyzer the thing deciding the answer is a
35//! pinned asset with a digest; for a linter the rule set is the toolchain, and
36//! there is no asset to digest. Not storing removes all of it.
37//!
38//! # It carries no `package`/`version` pair, deliberately
39//!
40//! [`crate::crossref`] joins two findings when their identifier sets intersect
41//! **and** they name the same package at the same version, both read out of
42//! `meta`. A clippy finding therefore cannot enter that join, because this
43//! adapter never writes those two keys — the cargo message carries a
44//! `package_id` and it is deliberately dropped. That join's correctness rests on
45//! both upstreams publishing identifiers, and nobody publishes lint names; they
46//! are release notes.
47//!
48//! [`ADAPTERS`]: crate::adapter::ADAPTERS
49//!
50//! @rto:0012
51//! @rto:0020
52
53use std::path::Path;
54
55use serde::Deserialize;
56
57use crate::adapter::{
58 Adapter, AssetPaths, InstallHint, Invocation, NativeContext, RUST_TOOLCHAIN, snippet_hash_at,
59};
60use crate::guidance::{Guidance, Line};
61use crate::ingest::{NormalizedReport, REPORT_SCHEMA, ReportFinding};
62use crate::runner::{ExecError, check_reported_path};
63use rto_graph::{Severity, Span};
64
65/// The analyzer id. It names a **reporting** analyzer, and is never the first
66/// component of a stored key, because nothing this adapter produces is stored.
67pub const ANALYZER: &str = "clippy";
68
69/// The command that adds the linter to an already-installed toolchain.
70///
71/// Named once because two refusals print it: this adapter's install hint, and
72/// [`crate::lint::LintError::AnalyzerNotInstalled`], which is raised by the
73/// probe that finds `cargo clippy --version` failing on a toolchain that has
74/// `cargo`. They are the same instruction reached two ways, and a literal in
75/// each is how they would come to disagree.
76///
77/// Documented at <https://doc.rust-lang.org/clippy/installation.html>, whose
78/// full form is `rustup component add clippy [--toolchain=<name>]`; the optional
79/// part is dropped because a hint has to be pasteable as printed.
80pub const COMPONENT_ADD: &str = "rustup component add clippy";
81
82/// How to obtain each of this linter's two programs.
83///
84/// The clearest case for keying hints by program rather than by analyzer: the
85/// *other* program here wants rustup's front page, and this one wants a
86/// component add. Handing a reader whose toolchain is fine an installer link is
87/// the wrong *kind* of way forward — the failure `docs/REVIEW_CHECKLIST.md`
88/// names — and is why [`RUST_TOOLCHAIN`] is reused for `cargo` and pointedly not
89/// for `cargo-clippy`.
90const INSTALL_HINTS: &[InstallHint] = &[
91 InstallHint {
92 program: "cargo",
93 guidance: RUST_TOOLCHAIN,
94 },
95 InstallHint {
96 program: "cargo-clippy",
97 guidance: Guidance::new(&[
98 Line::Note(&[
99 "Roteiro does not install toolchain components, and has not installed",
100 "this one. Clippy ships with the toolchain and is added to it with:",
101 ]),
102 Line::Command(COMPONENT_ADD),
103 Line::Note(&["Upstream: https://doc.rust-lang.org/clippy/installation.html"]),
104 ]),
105 },
106];
107
108/// The rule recorded for a diagnostic that carries no lint code — a parse error,
109/// say. Such a diagnostic still has a location and still matters, so it is
110/// reported under a name rather than dropped: an empty result is the one thing a
111/// failed build must never look like.
112pub const UNCODED_RULE: &str = "rustc";
113
114/// Which features the build under review is resolved with.
115///
116/// Reported rather than assumed, because it is one of the two axes — the other
117/// being the toolchain — that move a lint count without the code changing. On
118/// this repository the difference is 355 crates and 54 build scripts at the
119/// default set against 672 and 87 at `--all-features` (ADR-0020), so a count
120/// quoted without its feature set is not comparable to any other count.
121#[derive(Debug, Clone, PartialEq, Eq, Default)]
122pub enum FeatureSet {
123 /// Whatever each crate declares as its default features.
124 #[default]
125 Defaults,
126 /// `--all-features`.
127 All,
128 /// `--features a,b,c`, as the caller wrote them.
129 Explicit(Vec<String>),
130}
131
132impl FeatureSet {
133 /// The cargo arguments this feature set contributes, in order.
134 #[must_use]
135 pub fn args(&self) -> Vec<String> {
136 match self {
137 Self::Defaults => Vec::new(),
138 Self::All => vec!["--all-features".to_owned()],
139 Self::Explicit(features) => {
140 vec!["--features".to_owned(), features.join(",")]
141 }
142 }
143 }
144
145 /// A one-line label for the report — never empty, so a reader is never left
146 /// to infer which of the three cases produced a count.
147 #[must_use]
148 pub fn label(&self) -> String {
149 match self {
150 Self::Defaults => "default (each crate's own default features)".to_owned(),
151 Self::All => "all (--all-features)".to_owned(),
152 Self::Explicit(features) => features.join(", "),
153 }
154 }
155}
156
157/// The adapter.
158#[derive(Debug, Clone, Copy)]
159pub struct Clippy;
160
161/// What a stream of cargo messages contained beyond the findings themselves.
162///
163/// Every field is a count of something that did **not** become a finding. They
164/// are reported rather than swallowed: a run that silently dropped half its
165/// diagnostics and printed a small number would be indistinguishable from a
166/// clean tree, which is the shape this project has been bitten by before.
167#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
168pub struct Summary {
169 /// Whether cargo's `build-finished` message reported success. A failed build
170 /// still yields the diagnostics it managed to emit, and they are real — but
171 /// the set is partial, and a caller must say so.
172 pub build_succeeded: bool,
173 /// How many `compiler-message` entries the stream carried.
174 pub compiler_messages: usize,
175 /// Diagnostics with no primary span — rustc's own summaries ("aborting due
176 /// to 3 previous errors"), which are about the run rather than about a line
177 /// of code.
178 pub without_location: usize,
179 /// Diagnostics about a file outside the analyzed worktree — a dependency's
180 /// source under the cargo registry, most often.
181 pub outside_worktree: usize,
182 /// Identical diagnostics emitted more than once. `--all-targets` compiles
183 /// one file into several targets, so a lint in `src/main.rs` arrives once
184 /// per target; they are the same defect and are counted once.
185 pub duplicates_collapsed: usize,
186}
187
188impl Clippy {
189 /// The argv that produces the stream [`Clippy::normalize`] parses, at a
190 /// stated feature set.
191 ///
192 /// `--workspace --all-targets` mirrors the gate this repository already runs
193 /// (`AGENTS.md`), so the count a contributor sees here is the count CI will
194 /// see. `-D warnings` is deliberately **not** passed: this command reports,
195 /// and the levels the repository declares in `[workspace.lints]` are part of
196 /// what is being reported.
197 #[must_use]
198 pub fn invocation(features: &FeatureSet) -> Invocation {
199 let mut args = vec![
200 "clippy".to_owned(),
201 "--workspace".to_owned(),
202 "--all-targets".to_owned(),
203 // Not a reproducibility flourish — a write. Without it cargo creates
204 // or updates `Cargo.lock` when the manifest and the lockfile
205 // disagree, and it does that **in the tree being linted**, which is
206 // the tree `roteiro lint` promises to leave as it found it. Pointing
207 // `CARGO_TARGET_DIR` outside the worktree moves the build artefacts
208 // and does nothing about the lockfile; this is the other half of the
209 // same guarantee.
210 //
211 // The cost is real and is the correct one to pay: a tree whose
212 // lockfile is missing or stale now refuses to lint rather than
213 // silently being modified into a lintable one. `LintError::
214 // LockfileWouldBeWritten` is where that refusal is explained.
215 "--locked".to_owned(),
216 ];
217 args.extend(features.args());
218 args.push("--message-format=json".to_owned());
219 args.push("--quiet".to_owned());
220 Invocation {
221 program: "cargo".to_owned(),
222 args,
223 // 0 = the build completed. 101 = it did not, which for a repository
224 // that denies a lint group is the ordinary outcome of *finding
225 // something* — so treating it as failure would discard exactly the
226 // runs that matter. Every other status is a cargo that could not
227 // start, and falls through to a hard failure.
228 success_statuses: vec![0, 101],
229 }
230 }
231
232 /// The argv for a run whose network is denied **by a boundary** rather than
233 /// by good manners.
234 ///
235 /// [`Clippy::invocation`] plus `--offline`, and the two are separate
236 /// functions rather than a flag on one because they describe different
237 /// situations rather than different preferences. On the host, cargo may
238 /// legitimately reach a registry for a dependency the user has not fetched
239 /// yet; that is their machine and their choice, and `--locked` already stops
240 /// the one write into the tree that would follow. In a guest there is no
241 /// interface to reach it with, so the question is only whether cargo finds
242 /// that out from `--offline` or from a DNS timeout inside a VM.
243 ///
244 /// It is worth the flag for the error message alone. Without it a missing
245 /// crate surfaces as a network failure from inside a machine the user cannot
246 /// see; with it, cargo says *"attempting to make an HTTP request, but
247 /// --offline was specified"*, which [`crate::lint_sandbox`] turns into the
248 /// one thing that would actually help — fetch it on the host first.
249 #[must_use]
250 pub fn offline_invocation(features: &FeatureSet) -> Invocation {
251 let mut invocation = Self::invocation(features);
252 // Ahead of `--message-format`/`--quiet` only because `invocation`
253 // appends those last; cargo does not care about order, and this keeps
254 // the two argvs differing by exactly one token wherever they are printed
255 // side by side.
256 invocation.args.push("--offline".to_owned());
257 invocation
258 }
259
260 /// Parse a cargo `--message-format=json` stream, returning the normalised
261 /// report **and** what the stream contained besides findings.
262 ///
263 /// [`Adapter::normalize`] is this without the second half; the counts exist
264 /// because the ephemeral report prints them, and a trait shared with stored
265 /// analyzers has nowhere to carry them.
266 ///
267 /// # Errors
268 /// Returns [`ExecError::MalformedReport`] when the stream carries no
269 /// `build-finished` message — the marker that distinguishes a completed
270 /// cargo run from empty output, and therefore a clean tree from a run that
271 /// never happened.
272 pub fn parse(
273 native: &[u8],
274 ctx: &NativeContext<'_>,
275 ) -> Result<(NormalizedReport, Summary), ExecError> {
276 let text = String::from_utf8_lossy(native);
277 let mut summary = Summary::default();
278 let mut finished = false;
279 let mut findings: Vec<ReportFinding> = Vec::new();
280
281 for line in text.lines().filter(|l| !l.trim().is_empty()) {
282 // A line this build cannot read is not a reason to lose the run:
283 // cargo adds message kinds between releases, and every one of them
284 // carries its own `reason`. Unknown shapes are skipped, and the
285 // `build-finished` requirement below is what stops that leniency
286 // from turning junk into a clean report.
287 let Ok(message) = serde_json::from_str::<CargoMessage>(line) else {
288 continue;
289 };
290 match message.reason.as_str() {
291 "build-finished" => {
292 finished = true;
293 summary.build_succeeded = message.success.unwrap_or(false);
294 }
295 "compiler-message" => {
296 summary.compiler_messages += 1;
297 if let Some(diagnostic) = message.message {
298 convert(&diagnostic, ctx, &mut summary, &mut findings);
299 }
300 }
301 _ => {}
302 }
303 }
304
305 if !finished {
306 return Err(ExecError::MalformedReport(
307 "not a cargo --message-format=json stream: no `build-finished` message, so this \
308 is not a completed run and its emptiness means nothing"
309 .to_owned(),
310 ));
311 }
312
313 findings.sort_by(|a, b| a.identity.cmp(&b.identity));
314 let before = findings.len();
315 findings.dedup_by(|a, b| a.identity == b.identity);
316 summary.duplicates_collapsed = before - findings.len();
317
318 Ok((
319 NormalizedReport {
320 schema: REPORT_SCHEMA.to_owned(),
321 analyzer: ANALYZER.to_owned(),
322 analyzer_version: ctx.version_or(None),
323 started_at: ctx.started_at.clone(),
324 ended_at: ctx.ended_at.clone(),
325 exit_status: ctx.exit_status,
326 // There is no rule set to digest. The rules **are** the
327 // toolchain plus the repository's own `[workspace.lints]`, and
328 // neither is a pinned asset — which is precisely why this
329 // analyzer's output is reported rather than stored.
330 rules_digest: None,
331 image_digest: None,
332 // A linter consults no advisory database. Claiming one would put
333 // a staleness label on a result that has no such axis.
334 advisory_db: None,
335 source: ctx.source.clone(),
336 findings,
337 },
338 summary,
339 ))
340 }
341}
342
343impl Adapter for Clippy {
344 fn analyzer(&self) -> &'static str {
345 ANALYZER
346 }
347
348 fn summary(&self) -> &'static str {
349 "Rust lints from the toolchain's own linter, reported and never stored"
350 }
351
352 fn languages(&self) -> &'static [&'static str] {
353 &["rust"]
354 }
355
356 fn asset_ids(&self) -> &'static [&'static str] {
357 // None, and not because it happens to need nothing: a linter's rule set
358 // is the toolchain it ships with, so there is no asset to pin and no
359 // digest to record. That is the difference this whole adapter turns on.
360 &[]
361 }
362
363 fn host_programs(&self) -> &'static [&'static str] {
364 // The same two-part shape as `cargo-audit`, for the same reason: `cargo
365 // clippy` dispatches to a `cargo-clippy` binary on `PATH`. Unlike the
366 // others this is a toolchain component rather than a separate install —
367 // `rustup component add clippy` — but the *check* is identical, and this
368 // adapter is not in `ADAPTERS`, so `roteiro security status` never reports
369 // it. Declared because the trait requires an answer and a wrong one here
370 // would be waiting for whoever wires a lint status later.
371 &["cargo", "cargo-clippy"]
372 }
373
374 fn install_hints(&self) -> &'static [InstallHint] {
375 INSTALL_HINTS
376 }
377
378 fn command(&self, _assets: &AssetPaths<'_>) -> Invocation {
379 Self::invocation(&FeatureSet::Defaults)
380 }
381
382 fn normalize(
383 &self,
384 native: &[u8],
385 ctx: &NativeContext<'_>,
386 ) -> Result<NormalizedReport, ExecError> {
387 Self::parse(native, ctx).map(|(report, _)| report)
388 }
389}
390
391/// Convert one rustc diagnostic, or account for why it produced no finding.
392fn convert(
393 diagnostic: &Diagnostic,
394 ctx: &NativeContext<'_>,
395 summary: &mut Summary,
396 findings: &mut Vec<ReportFinding>,
397) {
398 let Some(span) = primary_span(diagnostic) else {
399 summary.without_location += 1;
400 return;
401 };
402 let Some(path) = worktree_relative(&span.file_name, ctx.worktree) else {
403 summary.outside_worktree += 1;
404 return;
405 };
406 let start = u32::try_from(span.byte_start).unwrap_or(u32::MAX);
407 let end = u32::try_from(span.byte_end).unwrap_or(u32::MAX).max(start);
408 let message = diagnostic.message.trim();
409 let rule = diagnostic
410 .code
411 .as_ref()
412 .map(|c| c.code.trim())
413 .filter(|c| !c.is_empty())
414 .unwrap_or(UNCODED_RULE)
415 .to_owned();
416
417 findings.push(ReportFinding {
418 // The recipe semgrep uses — rule, path, start byte, snippet hash — for
419 // the same reason it uses it, minus the durability claim: here it orders
420 // the report and collapses the same lint reported once per target. It is
421 // never a stored key, because there is no store to put it in.
422 identity: vec![
423 rule.clone(),
424 path.clone(),
425 start.to_string(),
426 snippet_hash_at(ctx.snippets, &path, start, end),
427 ],
428 rule,
429 severity: severity(&diagnostic.level),
430 title: title_from(message, &span.file_name),
431 message: message.to_owned(),
432 path: Some(path),
433 span: Some(Span::new(start, end)),
434 meta: serde_json::json!({
435 "line": span.line_start,
436 "column": span.column_start,
437 "end_line": span.line_end,
438 "rustc_level": diagnostic.level,
439 }),
440 });
441}
442
443/// The span a diagnostic is *about*: its primary one, else its first.
444fn primary_span(diagnostic: &Diagnostic) -> Option<&DiagnosticSpan> {
445 diagnostic
446 .spans
447 .iter()
448 .find(|s| s.is_primary)
449 .or_else(|| diagnostic.spans.first())
450}
451
452/// Place a reported file inside the analyzed worktree, or refuse it.
453///
454/// Cargo reports workspace-relative paths for the crates it is building and
455/// absolute ones for anything else, so both shapes arrive. An absolute path
456/// under the worktree is relativised; one outside it — a dependency's source in
457/// the cargo registry — is not a claim about this repository and is dropped.
458/// A relative path that climbs out is refused by the same check the stored path
459/// uses, so the two agree on what "inside the tree" means.
460fn worktree_relative(file: &str, worktree: Option<&Path>) -> Option<String> {
461 let path = Path::new(file);
462 let relative = if path.is_absolute() {
463 path.strip_prefix(worktree?).ok()?
464 } else {
465 path.strip_prefix("./").unwrap_or(path)
466 };
467 let text = relative.to_string_lossy().into_owned();
468 check_reported_path(&text).ok()?;
469 Some(text)
470}
471
472/// The first line of `message`, falling back to the file name when a diagnostic
473/// somehow carries no text at all — a titleless finding is refused downstream,
474/// and anything is more use than a blank.
475fn title_from(message: &str, file: &str) -> String {
476 let first = message.lines().next().unwrap_or("").trim();
477 if first.is_empty() {
478 file.to_owned()
479 } else {
480 first.to_owned()
481 }
482}
483
484/// Map rustc's diagnostic levels onto [`Severity`].
485///
486/// A lint's level is the level the *repository* configured — `[workspace.lints]`
487/// is what makes `clippy::all` an error here — so this is a faithful record of
488/// how the toolchain was told to treat it, not a judgement of how bad it is.
489fn severity(level: &str) -> Severity {
490 match level.trim().to_ascii_lowercase().as_str() {
491 "error" | "error: internal compiler error" => Severity::High,
492 "warning" => Severity::Medium,
493 "note" | "help" | "failure-note" => Severity::Info,
494 other => Severity::from_token(other),
495 }
496}
497
498/// One line of `cargo --message-format=json`, narrowed to what is needed.
499///
500/// `package_id` is **not** deserialized, and that is load-bearing rather than
501/// economical: it is the one field that could be turned into the
502/// `meta.package` / `meta.version` pair [`crate::crossref`] joins on, and a lint
503/// must never enter that join.
504#[derive(Debug, Deserialize)]
505struct CargoMessage {
506 reason: String,
507 #[serde(default)]
508 message: Option<Diagnostic>,
509 /// `build-finished` only.
510 #[serde(default)]
511 success: Option<bool>,
512}
513
514/// A rustc diagnostic, as cargo forwards it.
515#[derive(Debug, Deserialize)]
516struct Diagnostic {
517 #[serde(default)]
518 message: String,
519 #[serde(default)]
520 level: String,
521 #[serde(default)]
522 code: Option<DiagnosticCode>,
523 #[serde(default)]
524 spans: Vec<DiagnosticSpan>,
525}
526
527#[derive(Debug, Deserialize)]
528struct DiagnosticCode {
529 #[serde(default)]
530 code: String,
531}
532
533#[derive(Debug, Deserialize)]
534struct DiagnosticSpan {
535 #[serde(default)]
536 file_name: String,
537 #[serde(default)]
538 byte_start: u64,
539 #[serde(default)]
540 byte_end: u64,
541 #[serde(default)]
542 line_start: u64,
543 #[serde(default)]
544 line_end: u64,
545 #[serde(default)]
546 column_start: u64,
547 #[serde(default)]
548 is_primary: bool,
549}
550
551#[cfg(test)]
552mod tests {
553 use super::{ANALYZER, Clippy, FeatureSet, UNCODED_RULE, severity};
554 use crate::adapter::{Adapter, AssetPaths, NativeContext, adapter_for, known_analyzers};
555 use crate::runner::ExecError;
556 use rto_graph::{Severity, SourceIdentity};
557
558 fn ctx() -> NativeContext<'static> {
559 static SOURCE: std::sync::LazyLock<SourceIdentity> =
560 std::sync::LazyLock::new(SourceIdentity::default);
561 NativeContext {
562 started_at: "2026-08-18T09:00:00Z".to_owned(),
563 ended_at: "2026-08-18T09:04:00Z".to_owned(),
564 analyzer_version: Some("0.1.94".to_owned()),
565 exit_status: 101,
566 source: &SOURCE,
567 rules_digest: None,
568 advisory_db: None,
569 worktree: Some(std::path::Path::new("/checkout")),
570 snippets: &crate::snippet::NoSnippets,
571 }
572 }
573
574 /// A stream in the shape cargo emits: one clippy lint, the same lint again
575 /// from a second target, a coded rustc error, a location-less summary, a
576 /// diagnostic about a dependency's source, and the terminator.
577 const STREAM: &str = r#"
578{"reason":"compiler-artifact","target":{"name":"rto-exec"},"fresh":false}
579{"reason":"compiler-message","package_id":"path+file:///checkout#rto-exec@1.23.0","target":{"kind":["lib"],"name":"rto-exec"},"message":{"message":"this expression creates a reference which is immediately dereferenced by the compiler\nchange this to remove the borrow","code":{"code":"clippy::needless_borrow"},"level":"warning","spans":[{"file_name":"crates/rto-exec/src/lib.rs","byte_start":120,"byte_end":132,"line_start":9,"line_end":9,"column_start":13,"is_primary":true}]}}
580{"reason":"compiler-message","package_id":"path+file:///checkout#rto-exec@1.23.0","target":{"kind":["test"],"name":"rto-exec"},"message":{"message":"this expression creates a reference which is immediately dereferenced by the compiler\nchange this to remove the borrow","code":{"code":"clippy::needless_borrow"},"level":"warning","spans":[{"file_name":"crates/rto-exec/src/lib.rs","byte_start":120,"byte_end":132,"line_start":9,"line_end":9,"column_start":13,"is_primary":true}]}}
581{"reason":"compiler-message","message":{"message":"mismatched types","code":{"code":"E0308"},"level":"error","spans":[{"file_name":"/checkout/crates/roteiro/src/main.rs","byte_start":40,"byte_end":48,"line_start":3,"line_end":3,"column_start":5,"is_primary":true}]}}
582{"reason":"compiler-message","message":{"message":"aborting due to 1 previous error","level":"error","spans":[]}}
583{"reason":"compiler-message","message":{"message":"unused variable: `x`","code":{"code":"unused_variables"},"level":"warning","spans":[{"file_name":"/home/dev/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/serde-1.0.0/src/lib.rs","byte_start":1,"byte_end":2,"line_start":1,"line_end":1,"column_start":1,"is_primary":true}]}}
584{"reason":"build-finished","success":false}
585"#;
586
587 #[test]
588 fn normalizes_a_cargo_message_stream() {
589 let (report, summary) = Clippy::parse(STREAM.as_bytes(), &ctx()).expect("parse");
590 assert_eq!(report.analyzer, ANALYZER);
591 assert_eq!(report.analyzer_version, "0.1.94");
592 // A linter pins nothing: its rule set is the toolchain, and there is no
593 // advisory database in the picture at all.
594 assert!(report.rules_digest.is_none());
595 assert!(report.advisory_db.is_none());
596
597 assert_eq!(summary.compiler_messages, 5);
598 assert!(!summary.build_succeeded, "the stream said `success: false`");
599 assert_eq!(summary.without_location, 1, "the `aborting due to` summary");
600 assert_eq!(summary.outside_worktree, 1, "the dependency's own source");
601 assert_eq!(summary.duplicates_collapsed, 1, "lib and test targets");
602
603 let rules: Vec<&str> = report.findings.iter().map(|f| f.rule.as_str()).collect();
604 assert_eq!(rules, vec!["E0308", "clippy::needless_borrow"]);
605
606 let lint = &report.findings[1];
607 assert_eq!(lint.severity, Severity::Medium);
608 assert_eq!(lint.path.as_deref(), Some("crates/rto-exec/src/lib.rs"));
609 assert_eq!(lint.span.map(|s| (s.start, s.end)), Some((120, 132)));
610 // The title is one line; the whole diagnostic survives in `message`.
611 assert_eq!(
612 lint.title,
613 "this expression creates a reference which is immediately dereferenced by the compiler"
614 );
615 assert!(lint.message.contains("change this to remove the borrow"));
616 }
617
618 /// An absolute path inside the checkout is relativised, so the report reads
619 /// the same on two machines and carries nobody's home directory.
620 #[test]
621 fn relativises_an_absolute_path_inside_the_worktree() {
622 let (report, _) = Clippy::parse(STREAM.as_bytes(), &ctx()).expect("parse");
623 let error = &report.findings[0];
624 assert_eq!(error.path.as_deref(), Some("crates/roteiro/src/main.rs"));
625 assert_eq!(error.severity, Severity::High);
626 }
627
628 /// The whole point of requiring `build-finished`: empty output from a cargo
629 /// that never ran must not read as a tree with nothing wrong in it.
630 #[test]
631 fn refuses_a_stream_that_never_finished() {
632 for native in [
633 &b""[..],
634 &b"\n"[..],
635 &br#"{"reason":"compiler-artifact","fresh":true}"#[..],
636 &b"error: no such command: `clippy`"[..],
637 ] {
638 let err = Clippy::parse(native, &ctx()).expect_err("must be refused");
639 assert!(matches!(err, ExecError::MalformedReport(_)));
640 assert!(
641 err.to_string().contains("build-finished"),
642 "the refusal must name what was missing: {err}"
643 );
644 }
645 }
646
647 #[test]
648 fn a_completed_clean_build_is_a_valid_empty_report() {
649 let (report, summary) =
650 Clippy::parse(br#"{"reason":"build-finished","success":true}"#, &ctx()).expect("parse");
651 assert!(report.findings.is_empty());
652 assert!(summary.build_succeeded);
653 assert_eq!(summary.compiler_messages, 0);
654 }
655
656 /// A diagnostic with no lint code still has a location, and losing it would
657 /// hide a build failure behind an empty result.
658 #[test]
659 fn a_diagnostic_with_no_lint_code_is_reported_under_a_name() {
660 // One cargo message per line, as cargo emits them: this parser reads a
661 // stream, not a document, and a message split across lines is not one.
662 let native = concat!(
663 r#"{"reason":"compiler-message","message":{"message":"expected a semicolon","#,
664 r#""level":"error","spans":[{"file_name":"src/a.rs","byte_start":4,"byte_end":5,"#,
665 r#""line_start":1,"line_end":1,"column_start":5,"is_primary":true}]}}"#,
666 "\n",
667 r#"{"reason":"build-finished","success":false}"#
668 );
669 let (report, _) = Clippy::parse(native.as_bytes(), &ctx()).expect("parse");
670 assert_eq!(report.findings.len(), 1);
671 assert_eq!(report.findings[0].rule, UNCODED_RULE);
672 }
673
674 /// The join in [`crate::crossref`] requires a `package` **and** a `version`
675 /// in `meta`. A lint carries neither, so it cannot take part — and the cargo
676 /// message's `package_id` must never be turned into them.
677 #[test]
678 fn carries_no_package_or_version_so_it_cannot_enter_the_dependency_join() {
679 let (report, _) = Clippy::parse(STREAM.as_bytes(), &ctx()).expect("parse");
680 for finding in &report.findings {
681 assert!(finding.meta.get("package").is_none(), "{:?}", finding.meta);
682 assert!(finding.meta.get("version").is_none(), "{:?}", finding.meta);
683 }
684 }
685
686 /// The structural half of "a lint is never stored": `ingest` resolves an
687 /// analyzer through the registry, and clippy is not in it. Adding it there
688 /// would make `roteiro security ingest --analyzer clippy` file a layer.
689 #[test]
690 fn is_absent_from_the_registry_that_ingest_can_store() {
691 assert!(
692 adapter_for(ANALYZER).is_none(),
693 "clippy must not be resolvable as a storable analyzer"
694 );
695 assert!(
696 !known_analyzers().contains(&ANALYZER),
697 "clippy must not be offered by `ingest`"
698 );
699 }
700
701 #[test]
702 fn maps_rustc_levels_and_keeps_an_unknown_one_verbatim() {
703 for (raw, want) in [
704 ("error", Severity::High),
705 ("warning", Severity::Medium),
706 ("note", Severity::Info),
707 ("help", Severity::Info),
708 ("failure-note", Severity::Info),
709 ] {
710 assert_eq!(severity(raw), want, "{raw}");
711 }
712 assert_eq!(severity("lint"), Severity::Other("lint".to_owned()));
713 }
714
715 #[test]
716 fn the_invocation_mirrors_the_repository_gate_and_states_its_features() {
717 let default = Clippy::invocation(&FeatureSet::Defaults);
718 assert_eq!(default.program, "cargo");
719 assert_eq!(default.args[0], "clippy");
720 assert!(default.args.contains(&"--workspace".to_owned()));
721 assert!(default.args.contains(&"--all-targets".to_owned()));
722 assert!(default.args.contains(&"--message-format=json".to_owned()));
723 // Reporting, not gating: the levels the repository declares are part of
724 // what is being reported, so they are not overridden.
725 assert!(!default.args.iter().any(|a| a == "-D" || a == "warnings"));
726 // 101 is what cargo exits with when a denied lint fired, which is the
727 // run that matters most.
728 assert_eq!(default.success_statuses, vec![0, 101]);
729
730 let all = Clippy::invocation(&FeatureSet::All);
731 assert!(all.args.contains(&"--all-features".to_owned()));
732
733 let some = Clippy::invocation(&FeatureSet::Explicit(vec![
734 "serve".to_owned(),
735 "mcp".to_owned(),
736 ]));
737 let at = some
738 .args
739 .iter()
740 .position(|a| a == "--features")
741 .expect("--features");
742 assert_eq!(some.args[at + 1], "serve,mcp");
743 }
744
745 #[test]
746 fn every_feature_set_labels_itself() {
747 assert!(FeatureSet::Defaults.label().contains("default"));
748 assert!(FeatureSet::All.label().contains("--all-features"));
749 assert_eq!(
750 FeatureSet::Explicit(vec!["a".to_owned(), "b".to_owned()]).label(),
751 "a, b"
752 );
753 }
754
755 /// The rule set is the toolchain, so there is nothing to provision and
756 /// nothing to digest — the fact the whole decision turns on.
757 #[test]
758 fn declares_no_pinned_assets() {
759 assert!(Clippy.asset_ids().is_empty());
760 assert_eq!(Clippy.languages(), &["rust"]);
761 assert!(!Clippy.summary().is_empty());
762 assert_eq!(
763 Clippy.command(&AssetPaths::default()),
764 Clippy::invocation(&FeatureSet::Defaults)
765 );
766 }
767}