1use std::fs::{self, OpenOptions};
5use std::io::{self, IsTerminal as _, Read as _, Write as _};
6use std::path::Path;
7use std::sync::Arc;
8
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11
12use crate::report::{self, Finding, Report};
13
14const MAX_EXPLAIN_BYTES: u64 = 16 * 1024 * 1024;
16
17#[derive(Clone, Debug, PartialEq)]
19pub struct ExplainedFinding {
20 pub package: Arc<str>,
21 pub raw: Value,
22}
23
24impl ExplainedFinding {
25 pub fn id(&self) -> &str {
26 self.raw.get("id").and_then(Value::as_str).unwrap_or("")
27 }
28
29 pub fn kind(&self) -> &str {
30 self.raw.get("kind").and_then(Value::as_str).unwrap_or("")
31 }
32
33 pub fn file(&self) -> &str {
34 self.raw.get("file").and_then(Value::as_str).unwrap_or("")
35 }
36
37 pub fn line(&self) -> usize {
38 self.raw.get("line").and_then(Value::as_u64).unwrap_or(0) as usize
39 }
40
41 pub fn column(&self) -> usize {
42 self.raw.get("column").and_then(Value::as_u64).unwrap_or(0) as usize
43 }
44
45 pub fn site(&self) -> String {
46 format!("{}:{}:{}", self.file(), self.line(), self.column())
47 }
48
49 pub fn line_site(&self) -> String {
50 format!("{}:{}", self.file(), self.line())
51 }
52
53 pub fn item(&self) -> &str {
54 self.raw.get("item").and_then(Value::as_str).unwrap_or("")
55 }
56
57 pub fn code(&self) -> &str {
58 self.raw.get("code").and_then(Value::as_str).unwrap_or("")
59 }
60
61 pub fn ignore_comment(&self) -> String {
63 if let Some(comment) = self
64 .raw
65 .get("likely_equivalent")
66 .and_then(|v| v.get("ignore_comment"))
67 .and_then(Value::as_str)
68 && !comment.is_empty()
69 {
70 return comment.to_string();
71 }
72 let kind = match self.kind() {
73 k @ ("input_gap" | "assertion_gap" | "survivor") => k,
74 _ => "survivor",
75 };
76 let col = self.column();
77 if col > 0 {
78 format!("// tmt:ignore[{kind}@{col}] <reason>")
79 } else {
80 format!("// tmt:ignore[{kind}] <reason>")
81 }
82 }
83}
84
85pub fn read_report_input(from: Option<&Path>) -> Result<String> {
88 if let Some(path) = from {
89 let mut options = OpenOptions::new();
90 options.read(true);
91 #[cfg(unix)]
92 {
93 use std::os::unix::fs::OpenOptionsExt as _;
94
95 #[cfg(any(
96 target_os = "macos",
97 target_os = "ios",
98 target_os = "freebsd",
99 target_os = "netbsd",
100 target_os = "openbsd",
101 target_os = "dragonfly"
102 ))]
103 const O_NONBLOCK: i32 = 0x0004;
104 #[cfg(any(
105 target_os = "macos",
106 target_os = "ios",
107 target_os = "freebsd",
108 target_os = "netbsd",
109 target_os = "openbsd",
110 target_os = "dragonfly"
111 ))]
112 const O_NOFOLLOW: i32 = 0x0100;
113
114 #[cfg(all(
115 target_os = "linux",
116 any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
117 ))]
118 const O_NONBLOCK: i32 = 0o4000;
119 #[cfg(all(
120 target_os = "linux",
121 any(target_arch = "x86_64", target_arch = "x86", target_arch = "riscv64")
122 ))]
123 const O_NOFOLLOW: i32 = 0o400000;
124
125 #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
126 const O_NONBLOCK: i32 = 0o4000;
127 #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
128 const O_NOFOLLOW: i32 = 0o100000;
129
130 #[cfg(not(any(
131 target_os = "macos",
132 target_os = "ios",
133 target_os = "freebsd",
134 target_os = "netbsd",
135 target_os = "openbsd",
136 target_os = "dragonfly",
137 all(
138 target_os = "linux",
139 any(
140 target_arch = "x86_64",
141 target_arch = "x86",
142 target_arch = "aarch64",
143 target_arch = "riscv64"
144 )
145 )
146 )))]
147 const O_NONBLOCK: i32 = 0;
148 #[cfg(not(any(
149 target_os = "macos",
150 target_os = "ios",
151 target_os = "freebsd",
152 target_os = "netbsd",
153 target_os = "openbsd",
154 target_os = "dragonfly",
155 all(
156 target_os = "linux",
157 any(
158 target_arch = "x86_64",
159 target_arch = "x86",
160 target_arch = "aarch64",
161 target_arch = "riscv64"
162 )
163 )
164 )))]
165 const O_NOFOLLOW: i32 = 0;
166
167 let flags = O_NONBLOCK | O_NOFOLLOW;
168 if flags != 0 {
169 options.custom_flags(flags);
170 } else {
171 let meta = fs::symlink_metadata(path)
172 .with_context(|| format!("inspecting {}", path.display()))?;
173 if !meta.is_file() {
174 bail!("{} is not a regular file", path.display());
175 }
176 }
177 }
178 #[cfg(not(unix))]
179 {
180 let meta = fs::symlink_metadata(path)
181 .with_context(|| format!("inspecting {}", path.display()))?;
182 if !meta.is_file() {
183 bail!("{} is not a regular file", path.display());
184 }
185 }
186 let file = options
187 .open(path)
188 .with_context(|| format!("reading {}", path.display()))?;
189 let meta = file
190 .metadata()
191 .with_context(|| format!("inspecting {}", path.display()))?;
192 if !meta.is_file() {
193 bail!("{} is not a regular file", path.display());
194 }
195 read_bounded(file, &path.display().to_string())
196 } else {
197 let stdin = io::stdin();
198 if stdin.is_terminal() {
199 bail!(
200 "no input file given and stdin is a terminal; pass --from FILE or pipe `cargo tmt --json`"
201 );
202 }
203 read_bounded(stdin.lock(), "stdin")
204 }
205}
206
207fn read_bounded<R: io::Read>(reader: R, label: &str) -> Result<String> {
208 let mut text = String::new();
209 reader
210 .take(MAX_EXPLAIN_BYTES + 1)
211 .read_to_string(&mut text)
212 .with_context(|| format!("reading {label}"))?;
213 let text_len = text.len() as u64;
214 if text_len > MAX_EXPLAIN_BYTES {
215 bail!("{label} exceeds maximum report size of {MAX_EXPLAIN_BYTES} bytes");
216 }
217 Ok(text)
218}
219
220fn collect_findings_from_report_value(mut val: Value, out: &mut Vec<ExplainedFinding>) {
221 let Some(obj) = val.as_object_mut() else {
222 return;
223 };
224 if let Some(Value::Array(packages)) = obj.remove("packages") {
225 for pkg in packages {
226 collect_findings_from_report_value(pkg, out);
227 }
228 return;
229 }
230 if let Some(mut inner) = obj.remove("report") {
231 let fallback_pkg = obj
232 .get("package")
233 .and_then(Value::as_str)
234 .unwrap_or_default();
235 if let Some(inner_obj) = inner.as_object_mut() {
236 let pkg: Arc<str> = Arc::from(
237 inner_obj
238 .get("package")
239 .and_then(Value::as_str)
240 .unwrap_or(fallback_pkg),
241 );
242 if let Some(Value::Array(findings)) = inner_obj.remove("findings") {
243 for f in findings {
244 out.push(ExplainedFinding {
245 package: Arc::clone(&pkg),
246 raw: f,
247 });
248 }
249 }
250 }
251 return;
252 }
253 let pkg: Arc<str> = Arc::from(
254 obj.get("package")
255 .and_then(Value::as_str)
256 .unwrap_or_default(),
257 );
258 if let Some(Value::Array(findings)) = obj.remove("findings") {
259 for f in findings {
260 out.push(ExplainedFinding {
261 package: Arc::clone(&pkg),
262 raw: f,
263 });
264 }
265 }
266}
267
268pub fn parse_findings(text: &str) -> Result<Vec<ExplainedFinding>> {
270 let trimmed = text.trim();
271 if trimmed.is_empty() {
272 bail!("report input is empty");
273 }
274 if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
275 let mut out = Vec::new();
276 collect_findings_from_report_value(value, &mut out);
277 return Ok(out);
278 }
279 let mut out = Vec::new();
281 for (idx, line) in trimmed.lines().enumerate() {
282 let line = line.trim();
283 if line.is_empty() {
284 continue;
285 }
286 let value: Value = serde_json::from_str(line)
287 .with_context(|| format!("invalid JSON on line {}", idx + 1))?;
288 collect_findings_from_report_value(value, &mut out);
289 }
290 Ok(out)
291}
292
293fn distinct_finding_key(f: &ExplainedFinding) -> (&str, Option<&str>, &str, usize, usize) {
294 let id = f.id();
295 if id.is_empty() {
296 (f.package.as_ref(), None, f.kind(), f.line(), f.column())
297 } else {
298 (f.package.as_ref(), Some(id), "", 0, 0)
299 }
300}
301
302pub fn resolve_findings<'a>(
308 findings: &'a [ExplainedFinding],
309 query: &str,
310) -> Result<Vec<&'a ExplainedFinding>> {
311 let query = query.trim();
312 if query.is_empty() {
313 bail!("finding id or site must not be empty");
314 }
315
316 let exact_id: Vec<&ExplainedFinding> = findings.iter().filter(|f| f.id() == query).collect();
317 if !exact_id.is_empty() {
318 return Ok(exact_id);
319 }
320
321 let exact_site: Vec<&ExplainedFinding> =
322 findings.iter().filter(|f| f.site() == query).collect();
323 if !exact_site.is_empty() {
324 let distinct_keys: std::collections::BTreeSet<_> =
325 exact_site.iter().map(|f| distinct_finding_key(f)).collect();
326 if distinct_keys.len() == 1 {
327 return Ok(exact_site);
328 }
329 return Err(ambiguous_error(query, &exact_site));
330 }
331
332 let exact_line: Vec<&ExplainedFinding> =
333 findings.iter().filter(|f| f.line_site() == query).collect();
334 if !exact_line.is_empty() {
335 let distinct_keys: std::collections::BTreeSet<_> =
336 exact_line.iter().map(|f| distinct_finding_key(f)).collect();
337 if distinct_keys.len() == 1 {
338 return Ok(exact_line);
339 }
340 return Err(ambiguous_error(query, &exact_line));
341 }
342
343 let prefix_id: Vec<&ExplainedFinding> = findings
344 .iter()
345 .filter(|f| !f.id().is_empty() && f.id().starts_with(query))
346 .collect();
347 if !prefix_id.is_empty() {
348 let distinct_keys: std::collections::BTreeSet<_> =
349 prefix_id.iter().map(|f| distinct_finding_key(f)).collect();
350 if distinct_keys.len() == 1 {
351 return Ok(prefix_id);
352 }
353 return Err(ambiguous_error(query, &prefix_id));
354 }
355
356 bail!(
357 "no finding matching `{}` ({} finding(s) in report)",
358 report::sanitize_inline(query),
359 findings.len()
360 )
361}
362
363pub fn resolve_finding<'a>(
366 findings: &'a [ExplainedFinding],
367 query: &str,
368) -> Result<&'a ExplainedFinding> {
369 resolve_findings(findings, query).map(|mut list| list.remove(0))
370}
371
372fn ambiguous_error(query: &str, matches: &[&ExplainedFinding]) -> anyhow::Error {
373 let mut msg = format!(
374 "ambiguous selector `{}` matched {} findings:\n",
375 report::sanitize_inline(query),
376 matches.len()
377 );
378 for item in matches.iter().take(10) {
379 let pkg = if item.package.is_empty() {
380 String::new()
381 } else {
382 format!("[{}] ", report::sanitize_inline(&item.package))
383 };
384 msg.push_str(&format!(
385 " - {pkg}{} [{}] {}\n",
386 report::sanitize_inline(&item.site()),
387 report::sanitize_inline(item.kind()),
388 report::sanitize_inline(item.id())
389 ));
390 }
391 if matches.len() > 10 {
392 msg.push_str(&format!(" ... and {} more\n", matches.len() - 10));
393 }
394 anyhow::anyhow!(msg.trim_end().to_string())
395}
396
397pub fn render_explanation_text(finding: &ExplainedFinding) -> String {
399 let mut out = String::new();
400 let kind_label = match finding.kind() {
401 "input_gap" => "INPUT GAP",
402 "assertion_gap" => "ASSERTION GAP",
403 "survivor" if finding.raw.get("change_since").is_some() => "UNTESTED CHANGE",
404 "survivor" => "SURVIVOR",
405 other => other,
406 };
407 out.push_str(&format!(
408 "{} {}\n",
409 report::sanitize_inline(kind_label),
410 report::sanitize_inline(&finding.site())
411 ));
412 if !finding.package.is_empty() {
413 out.push_str(&format!(
414 " package: {}\n",
415 report::sanitize_inline(&finding.package)
416 ));
417 }
418 if !finding.id().is_empty() {
419 out.push_str(&format!(
420 " id: {}\n",
421 report::sanitize_inline(finding.id())
422 ));
423 }
424 if !finding.item().is_empty() {
425 out.push_str(&format!(
426 " item: {}\n",
427 report::sanitize_inline(finding.item())
428 ));
429 }
430 out.push_str(&format!(
431 " code: {}\n",
432 report::sanitize_inline(finding.code())
433 ));
434
435 if let Some(survivors) = finding.raw.get("survivors").and_then(Value::as_array) {
436 let list: Vec<String> = survivors
437 .iter()
438 .filter_map(Value::as_str)
439 .map(report::sanitize_inline)
440 .collect();
441 let total = finding
442 .raw
443 .get("survivor_count")
444 .and_then(|v| v.as_u64().map(u128::from))
445 .unwrap_or(list.len() as u128)
446 .max(list.len() as u128);
447 if !list.is_empty() {
448 if total > list.len() as u128 {
449 let more = total - list.len() as u128;
450 out.push_str(&format!(
451 " survivors ({total} total, showing {}):\n",
452 list.len()
453 ));
454 for s in list {
455 out.push_str(&format!(" - {s}\n"));
456 }
457 out.push_str(&format!(" - (+{more} more)\n"));
458 } else {
459 out.push_str(&format!(" survivors ({total}):\n"));
460 for s in list {
461 out.push_str(&format!(" - {s}\n"));
462 }
463 }
464 }
465 }
466 if let Some(observed) = finding.raw.get("observed").and_then(Value::as_str) {
467 out.push_str(&format!(
468 " observed: {}\n",
469 report::sanitize_inline(observed)
470 ));
471 }
472 let has_likely_eq = finding
473 .raw
474 .get("likely_equivalent")
475 .and_then(Value::as_object)
476 .is_some();
477 if !has_likely_eq
478 && let Some(add_tests) = finding.raw.get("add_tests").and_then(Value::as_array)
479 {
480 for item in add_tests.iter().filter_map(Value::as_str) {
481 out.push_str(&format!(" add test: {}\n", report::sanitize_inline(item)));
482 }
483 }
484 if let Some(tests) = finding.raw.get("tests").and_then(Value::as_array) {
485 let names: Vec<String> = tests
486 .iter()
487 .filter_map(Value::as_str)
488 .map(report::sanitize_inline)
489 .collect();
490 if !names.is_empty() {
491 out.push_str(&format!(" reaching tests: {}\n", names.join(", ")));
492 }
493 }
494 if let Some(effects) = finding.raw.get("effects").and_then(Value::as_array) {
495 for effect in effects.iter().filter_map(Value::as_str) {
496 out.push_str(&format!(" effect: {}\n", report::sanitize_inline(effect)));
497 }
498 }
499 if let Some(advice) = finding.raw.get("advice").and_then(Value::as_str) {
500 out.push_str(&format!(" advice: {}\n", report::sanitize_inline(advice)));
501 }
502 if let Some(witness) = finding.raw.get("witness").and_then(Value::as_object) {
503 let call = witness.get("call").and_then(Value::as_str).unwrap_or("");
504 let orig = witness
505 .get("original")
506 .and_then(Value::as_str)
507 .unwrap_or("");
508 let mutant = witness.get("mutant").and_then(Value::as_str).unwrap_or("");
509 let assertion = witness
510 .get("assertion")
511 .and_then(Value::as_str)
512 .unwrap_or("");
513 out.push_str(&format!(
514 " witness: `{}` (original: {}, mutant: {})\n",
515 report::sanitize_inline(call),
516 report::sanitize_inline(orig),
517 report::sanitize_inline(mutant)
518 ));
519 if !assertion.is_empty() {
520 out.push_str(&format!(
521 " assert: {}\n",
522 report::sanitize_inline(assertion)
523 ));
524 }
525 }
526 if let Some(eq) = finding
527 .raw
528 .get("likely_equivalent")
529 .and_then(Value::as_object)
530 && let Some(reason) = eq.get("reason").and_then(Value::as_str)
531 {
532 out.push_str(&format!(
533 " likely equivalent: {}\n",
534 report::sanitize_inline(reason)
535 ));
536 }
537 out.push_str(&format!(
538 " suppress: {}\n",
539 report::sanitize_inline(&finding.ignore_comment())
540 ));
541 report::sanitize_terminal(&out)
542}
543
544pub fn render_explanation_json(finding: &ExplainedFinding) -> String {
546 let mut obj = finding.raw.clone();
547 if let Some(map) = obj.as_object_mut() {
548 if !finding.package.is_empty() {
549 map.insert(
550 "package".to_string(),
551 Value::String(finding.package.to_string()),
552 );
553 }
554 map.insert(
555 "ignore_comment".to_string(),
556 Value::String(finding.ignore_comment()),
557 );
558 }
559 serde_json::to_string_pretty(&obj).expect("finding explanation serialises")
560}
561
562pub fn render_todo_stubs(reports: &[Report]) -> Option<String> {
565 let total: usize = reports.iter().map(|r| r.findings.len()).sum();
566 if total == 0 {
567 return None;
568 }
569 let mut out = String::new();
570 out.push_str("// Generated by `cargo tmt --emit-todos`.\n");
571 out.push_str(
572 "// Fill in each test body and remove `#[ignore = ...]` as you close each gap.\n\n",
573 );
574 let mut idx = 0usize;
575 for rep in reports {
576 for finding in &rep.findings {
577 idx += 1;
578 let at = finding.at();
579 let stem = sanitize_ident(&at.file);
580 let fn_name = format!("tmt_todo_{idx:03}_{stem}_l{}_c{}", at.line, at.column);
581 let summary = format!(
582 "tmt: {} at {}:{}:{}",
583 finding.kind(),
584 report::sanitize_inline(&at.file),
585 at.line,
586 at.column
587 );
588 out.push_str(&format!(
589 "// Package: {} | Kind: {} | Location: {}:{}:{}\n",
590 report::sanitize_inline(&rep.package),
591 finding.kind(),
592 report::sanitize_inline(&at.file),
593 at.line,
594 at.column,
595 ));
596 if !at.id.is_empty() {
597 out.push_str(&format!("// ID: {}\n", report::sanitize_inline(&at.id)));
598 }
599 out.push_str(&format!("// Code: {}\n", report::sanitize_inline(&at.code)));
600 if let Some(eq) = finding.likely_equivalent() {
601 out.push_str(&format!(
602 "// Likely equivalent: {}\n// Suppress: {}\n",
603 report::sanitize_inline(&eq.reason),
604 report::sanitize_inline(&eq.ignore_comment),
605 ));
606 } else {
607 match finding {
608 Finding::InputGap { add_tests, .. } => {
609 for hint in add_tests {
610 out.push_str(&format!(
611 "// Add test: {}\n",
612 report::sanitize_inline(hint)
613 ));
614 }
615 }
616 Finding::AssertionGap { tests, witness, .. } => {
617 if !tests.is_empty() {
618 out.push_str(&format!(
619 "// Reaching tests: {}\n",
620 tests
621 .iter()
622 .take(5)
623 .map(|t| report::sanitize_inline(t))
624 .collect::<Vec<_>>()
625 .join(", ")
626 ));
627 }
628 if let Some(w) = witness {
629 out.push_str(&format!(
630 "// Suggested assertion: {}\n",
631 report::sanitize_inline(&w.assertion)
632 ));
633 }
634 }
635 Finding::Survivor {
636 advice, witness, ..
637 } => {
638 if let Some(w) = witness {
639 out.push_str(&format!(
640 "// Suggested assertion: {}\n",
641 report::sanitize_inline(&w.assertion)
642 ));
643 } else if let Some(a) = advice {
644 out.push_str(&format!("// Advice: {}\n", report::sanitize_inline(a)));
645 }
646 }
647 }
648 }
649 out.push_str("#[test]\n");
650 out.push_str(&format!("#[ignore = {:?}]\n", summary));
651 out.push_str(&format!("fn {fn_name}() {{\n"));
652 out.push_str(&format!(" todo!(\"{{}}\", {:?});\n", summary));
653 out.push_str("}\n\n");
654 }
655 }
656 Some(out)
657}
658
659pub fn write_todo_stubs(path: &Path, reports: &[Report]) -> Result<usize> {
664 let count: usize = reports.iter().map(|r| r.findings.len()).sum();
665 let Some(content) = render_todo_stubs(reports) else {
666 return Ok(0);
667 };
668 if fs::symlink_metadata(path).is_ok() {
669 bail!(
670 "refusing to overwrite existing path `{}` (choose a new file path for --emit-todos)",
671 path.display()
672 );
673 }
674 let mut file = OpenOptions::new()
675 .write(true)
676 .create_new(true)
677 .open(path)
678 .with_context(|| format!("creating {}", path.display()))?;
679 file.write_all(content.as_bytes())
680 .with_context(|| format!("writing {}", path.display()))?;
681 file.flush()
682 .with_context(|| format!("flushing {}", path.display()))?;
683 Ok(count)
684}
685
686fn sanitize_ident(path: &str) -> String {
687 let trimmed = path.strip_suffix(".rs").unwrap_or(path);
688 let mut out = String::new();
689 let mut prev_underscore = false;
690 for ch in trimmed.chars() {
691 if ch.is_ascii_alphanumeric() {
692 out.push(ch.to_ascii_lowercase());
693 prev_underscore = false;
694 } else if !prev_underscore && !out.is_empty() {
695 out.push('_');
696 prev_underscore = true;
697 }
698 }
699 let trimmed = out.trim_matches('_');
700 if trimmed.is_empty() {
701 "file".to_string()
702 } else if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) {
703 format!("f_{trimmed}")
704 } else {
705 trimmed.to_string()
706 }
707}