1use std::collections::{BTreeSet, HashSet};
11
12use anyhow::{Context, Result};
13use proc_macro2::{Span, TokenStream, TokenTree};
14use quote::ToTokens;
15use serde::Serialize;
16use syn::spanned::Spanned;
17use syn::visit::{self, Visit};
18
19use crate::plan::CmpOp;
20
21pub const RUNTIME_MOD: &str = "__tmt_rt";
23
24#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
25#[serde(rename_all = "snake_case")]
26pub enum LiteralSide {
27 None,
28 Rhs(i128),
29 Lhs(i128),
30}
31
32#[derive(Clone, PartialEq, Eq, Debug)]
33pub enum SiteKind {
34 Cmp {
35 op: CmpOp,
36 lhs: String,
37 rhs: String,
38 literal: LiteralSide,
39 gap: (usize, usize),
41 },
42 Logic {
44 and: bool,
45 lhs: String,
46 rhs: String,
47 gap: (usize, usize),
48 },
49 Arith {
52 op: ArithOp,
53 assign: bool,
55 lhs: String,
56 rhs: String,
57 gap: (usize, usize),
58 },
59 Not {
61 bang: (usize, usize),
63 operand: String,
64 },
65 Return {
68 name: String,
69 option: Option<String>,
72 sole_expr: Option<(usize, usize)>,
75 },
76 MinMax {
78 max: bool,
79 receiver: String,
80 argument: String,
81 call: (usize, usize),
83 close: (usize, usize),
84 },
85 SliceEnd {
88 first: bool,
89 receiver: String,
90 call: (usize, usize),
92 method: (usize, usize),
94 },
95 Range {
97 inclusive: bool,
98 lhs: String,
99 rhs: String,
100 gap: (usize, usize),
101 },
102 Arm {
105 pattern: String,
106 guard: ArmGuard,
108 removal: (usize, usize),
109 },
110 Stmt,
112 Neg {
114 minus: (usize, usize),
116 operand: String,
117 literal: bool,
119 },
120 Guard {
122 can_be_false: bool,
125 },
126 Field {
128 name: String,
129 shorthand: bool,
131 from_base: Option<String>,
133 removal: (usize, usize),
135 },
136 Body {
139 name: String,
140 value: String,
141 sole_expr: Option<(usize, usize)>,
145 },
146}
147
148#[derive(Clone, Copy, PartialEq, Eq, Debug)]
149pub enum ArmGuard {
150 None(usize),
152 Existing(usize, usize),
154}
155
156#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
157#[serde(rename_all = "snake_case")]
158pub enum ArithOp {
159 Add,
160 Sub,
161 Mul,
162 Div,
163 Rem,
164 BitAnd,
165 BitOr,
166 BitXor,
167 Shl,
168 Shr,
169}
170
171impl ArithOp {
172 pub fn binding(self) -> u8 {
174 match self {
175 ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
176 ArithOp::Add | ArithOp::Sub => 4,
177 ArithOp::Shl | ArithOp::Shr => 3,
178 ArithOp::BitAnd => 2,
179 ArithOp::BitXor => 1,
180 ArithOp::BitOr => 0,
181 }
182 }
183
184 pub const ALL: [ArithOp; 10] = [
185 ArithOp::Add,
186 ArithOp::Sub,
187 ArithOp::Mul,
188 ArithOp::Div,
189 ArithOp::Rem,
190 ArithOp::BitAnd,
191 ArithOp::BitOr,
192 ArithOp::BitXor,
193 ArithOp::Shl,
194 ArithOp::Shr,
195 ];
196
197 pub fn symbol(self) -> &'static str {
198 match self {
199 ArithOp::Add => "+",
200 ArithOp::Sub => "-",
201 ArithOp::Mul => "*",
202 ArithOp::Div => "/",
203 ArithOp::Rem => "%",
204 ArithOp::BitAnd => "&",
205 ArithOp::BitOr => "|",
206 ArithOp::BitXor => "^",
207 ArithOp::Shl => "<<",
208 ArithOp::Shr => ">>",
209 }
210 }
211
212 pub fn swapped(self) -> ArithOp {
214 match self {
215 ArithOp::Add => ArithOp::Sub,
216 ArithOp::Sub => ArithOp::Add,
217 ArithOp::Mul => ArithOp::Div,
218 ArithOp::Div => ArithOp::Mul,
219 ArithOp::Rem => ArithOp::Div,
220 ArithOp::BitAnd => ArithOp::BitOr,
221 ArithOp::BitOr => ArithOp::BitAnd,
222 ArithOp::BitXor => ArithOp::BitAnd,
223 ArithOp::Shl => ArithOp::Shr,
224 ArithOp::Shr => ArithOp::Shl,
225 }
226 }
227
228 pub fn swapped2(self) -> Option<ArithOp> {
230 Some(match self {
231 ArithOp::Add => ArithOp::Mul,
232 ArithOp::Sub => ArithOp::Div,
233 ArithOp::Mul => ArithOp::Add,
234 ArithOp::Div => ArithOp::Rem,
235 ArithOp::Rem => ArithOp::Add,
236 ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
237 ArithOp::BitXor => ArithOp::BitOr,
238 ArithOp::Shl | ArithOp::Shr => return None,
239 })
240 }
241
242 pub fn second(self, assign: bool) -> Option<ArithOp> {
246 if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
247 return None;
248 }
249 self.swapped2()
250 }
251
252 pub fn is_bitwise(self) -> bool {
254 matches!(
255 self,
256 ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
257 )
258 }
259
260 fn stem(self) -> (&'static str, &'static str) {
262 match self {
263 ArithOp::Add => ("add", "Add"),
264 ArithOp::Sub => ("sub", "Sub"),
265 ArithOp::Mul => ("mul", "Mul"),
266 ArithOp::Div => ("div", "Div"),
267 ArithOp::Rem => ("rem", "Rem"),
268 ArithOp::BitAnd => ("bitand", "BitAnd"),
269 ArithOp::BitOr => ("bitor", "BitOr"),
270 ArithOp::BitXor => ("bitxor", "BitXor"),
271 ArithOp::Shl => ("shl", "Shl"),
272 ArithOp::Shr => ("shr", "Shr"),
273 }
274 }
275
276 pub(crate) fn method(self, assign: bool) -> String {
278 format!(
279 "tmt_{}{}",
280 self.stem().0,
281 if assign { "_assign" } else { "" }
282 )
283 }
284
285 pub(crate) fn fallback_trait(self, assign: bool) -> String {
287 format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
288 }
289
290 fn prim_trait(self, assign: bool) -> &'static str {
292 match (self.is_bitwise(), assign) {
293 (false, false) => "ArithPrim",
294 (true, false) => "BitPrim",
295 (false, true) => "ArithAssignPrim",
296 (true, true) => "BitAssignPrim",
297 }
298 }
299}
300
301#[derive(Clone, PartialEq, Eq, Debug)]
302pub struct Site {
303 pub id: u32,
304 pub kind: SiteKind,
305 pub line: usize,
307 pub column: usize,
308 pub start: usize,
310 pub end: usize,
311 pub text: String,
312}
313
314#[derive(Debug, PartialEq, Eq)]
315pub struct TestModule {
316 pub name: String,
317 pub path: Option<String>,
319}
320
321#[derive(Debug, Default)]
322pub struct Discovery {
323 pub sites: Vec<Site>,
324 pub rebuild_sites: Vec<Site>,
329 pub single_statement_bodies: Vec<String>,
332 pub test_modules: Vec<TestModule>,
334}
335
336pub fn discover(source: &str, first_id: u32) -> Result<Discovery> {
338 discover_with_errors(source, first_id, &[])
339}
340
341pub(crate) fn discover_with_errors(
342 source: &str,
343 first_id: u32,
344 error_values: &[&str],
345) -> Result<Discovery> {
346 let file = parse_source(source)?;
347 Ok(discover_parsed(source, &file, first_id, error_values))
348}
349
350pub(crate) fn parse_source(source: &str) -> Result<syn::File> {
351 if source.starts_with('\u{feff}') || (source.starts_with("#!") && !source.starts_with("#![")) {
354 anyhow::bail!("starts with a byte order mark or a `#!` line");
355 }
356 syn::parse_file(source).context("not parseable as a Rust source file")
357}
358
359pub(crate) fn discover_parsed(
360 source: &str,
361 file: &syn::File,
362 first_id: u32,
363 error_values: &[&str],
364) -> Discovery {
365 let local_macros = file
368 .items
369 .iter()
370 .filter_map(|item| match item {
371 syn::Item::Macro(m) => m.ident.as_ref().map(|i| i.to_string()),
372 _ => None,
373 })
374 .collect();
375 let mut finder = Finder {
376 source,
377 next_id: first_id,
378 found: Discovery::default(),
379 local_macros,
380 const_depth: 0,
381 error_values,
382 for_ranges: std::collections::HashSet::new(),
383 };
384 finder.visit_file(file);
385 finder.found
386}
387
388struct Finder<'s> {
389 error_values: &'s [&'s str],
390 local_macros: Vec<String>,
392 source: &'s str,
393 next_id: u32,
394 found: Discovery,
395 const_depth: usize,
397 for_ranges: std::collections::HashSet<usize>,
399}
400
401impl Finder<'_> {
402 fn function_sites(&mut self, sig: &syn::Signature, body: &syn::Block) {
405 if body.stmts.is_empty() {
406 return;
407 }
408 let braces = body.brace_token.span;
409 let (Some((_, start)), Some((end, _)), Some((sig_start, sig_end))) = (
410 self.range(braces.open()),
411 self.range(braces.close()),
412 self.range(sig.span()),
413 ) else {
414 return;
415 };
416 if !in_order(start, end) {
417 return;
418 }
419 let at = sig.span().start();
420 let text = self.source[sig_start..sig_end].to_string();
421 let (sole_expr, sole_plain) = match &body.stmts[..] {
422 [syn::Stmt::Expr(expr, None)] => {
423 let range = self.range(expr.span());
424 (range, range.filter(|_| does_nothing_else(expr)))
425 }
426 _ => (None, None),
427 };
428 let push = |finder: &mut Self, kind: SiteKind| {
429 finder.add(Site {
430 id: 0,
431 kind,
432 line: at.line,
433 column: at.column + 1,
434 start,
435 end,
436 text: text.clone(),
437 });
438 };
439 let name = sig.ident.to_string();
440 if let Some(option) = self.result_kind(&sig.output)
441 && !may_bypass_result_probe(body)
442 {
443 let kind = SiteKind::Return {
444 name: name.clone(),
445 option,
446 sole_expr,
447 };
448 push(self, kind);
449 }
450 let one_deletable_statement = matches!(sig.output, syn::ReturnType::Default)
453 && matches!(&body.stmts[..], [syn::Stmt::Expr(expr, Some(_))] if deletable(expr));
454 if sig.unsafety.is_some() {
455 return;
456 }
457 if one_deletable_statement {
458 self.found.single_statement_bodies.push(name);
459 return;
460 }
461 let written = sole_expr.map(|(from, to)| tokens_of(&self.source[from..to]));
462 let is_written = |value: &str| {
463 written
464 .as_deref()
465 .is_some_and(|text| text == tokens_of(value))
466 };
467 let probe_values = body_values_with_errors(&sig.output, self.error_values, false);
468 let probe_index = (probe_values.len() > 32).then(|| {
470 probe_values
471 .iter()
472 .map(String::as_str)
473 .collect::<HashSet<_>>()
474 });
475 for value in body_values_with_errors(&sig.output, self.error_values, true) {
476 let is_probe = probe_index.as_ref().map_or_else(
477 || probe_values.contains(&value),
478 |index| index.contains(value.as_str()),
479 );
480 if !is_probe && !is_written(&value) {
481 self.add_rebuild(Site {
482 id: NO_ID,
483 kind: SiteKind::Body {
484 name: name.clone(),
485 value,
486 sole_expr: sole_plain,
487 },
488 line: at.line,
489 column: at.column + 1,
490 start,
491 end,
492 text: text.clone(),
493 });
494 }
495 }
496 for value in probe_values {
497 if !is_written(&value) {
498 push(
499 self,
500 SiteKind::Body {
501 name: name.clone(),
502 value,
503 sole_expr: sole_plain,
504 },
505 );
506 }
507 }
508 }
509
510 fn result_kind(&self, output: &syn::ReturnType) -> Option<Option<String>> {
513 let syn::ReturnType::Type(_, ty) = output else {
514 return None;
515 };
516 match &**ty {
517 syn::Type::Path(p) if p.path.is_ident("bool") => Some(None),
519 syn::Type::Path(p)
520 if p.qself.is_none()
521 && p.path.segments.last().is_some_and(|s| {
522 s.ident == "Option"
523 && matches!(s.arguments, syn::PathArguments::AngleBracketed(_))
524 }) =>
525 {
526 match self
527 .range(ty.span())
528 .map(|(from, to)| &self.source[from..to])
529 {
530 Some(written) if !written.contains("impl ") => Some(Some(written.to_string())),
532 _ => None,
533 }
534 }
535 _ => None,
536 }
537 }
538 fn range(&self, span: Span) -> Option<(usize, usize)> {
539 let range = span.byte_range();
540 let located = !range.is_empty() && self.source.get(range.clone()).is_some();
543 located.then_some((range.start, range.end))
544 }
545
546 fn push(&mut self, kind: SiteKind, start: usize, end: usize, span: Span) {
547 let at = span.start();
548 self.add(Site {
549 id: 0,
550 kind,
551 line: at.line,
552 column: at.column + 1,
553 start,
554 end,
555 text: self.source[start..end].to_string(),
556 });
557 }
558
559 fn constant(&mut self, attrs: &[syn::Attribute], value: &syn::Expr) {
562 if !is_test_only(attrs) && !is_skipped(attrs) {
563 self.const_depth += 1;
564 self.visit_expr(value);
565 self.const_depth -= 1;
566 }
567 }
568
569 fn typed_constant(
570 &mut self,
571 attrs: &[syn::Attribute],
572 ty: &syn::Type,
573 value: Option<&syn::Expr>,
574 ) {
575 if !is_test_only(attrs) && !is_skipped(attrs) {
576 self.visit_type(ty);
577 if let Some(value) = value {
578 self.constant(&[], value);
579 }
580 }
581 }
582
583 fn add_rebuild(&mut self, mut site: Site) {
585 site.id = NO_ID;
586 self.found.rebuild_sites.push(site);
587 }
588
589 fn add(&mut self, mut site: Site) {
590 if self.const_depth > 0 {
591 self.add_rebuild(site);
592 } else {
593 site.id = self.next_id;
594 self.found.sites.push(site);
595 self.next_id += 1;
596 }
597 }
598}
599
600fn cmp_op(op: &syn::BinOp) -> Option<CmpOp> {
601 Some(match op {
602 syn::BinOp::Lt(_) => CmpOp::Lt,
603 syn::BinOp::Le(_) => CmpOp::Le,
604 syn::BinOp::Gt(_) => CmpOp::Gt,
605 syn::BinOp::Ge(_) => CmpOp::Ge,
606 syn::BinOp::Eq(_) => CmpOp::Eq,
607 syn::BinOp::Ne(_) => CmpOp::Ne,
608 _ => return None,
609 })
610}
611
612fn arith_op(op: &syn::BinOp) -> Option<(ArithOp, bool)> {
614 use syn::BinOp as B;
615 Some(match op {
616 B::Add(_) => (ArithOp::Add, false),
617 B::Sub(_) => (ArithOp::Sub, false),
618 B::Mul(_) => (ArithOp::Mul, false),
619 B::Div(_) => (ArithOp::Div, false),
620 B::Rem(_) => (ArithOp::Rem, false),
621 B::BitAnd(_) => (ArithOp::BitAnd, false),
622 B::BitOr(_) => (ArithOp::BitOr, false),
623 B::BitXor(_) => (ArithOp::BitXor, false),
624 B::Shl(_) => (ArithOp::Shl, false),
625 B::Shr(_) => (ArithOp::Shr, false),
626 B::AddAssign(_) => (ArithOp::Add, true),
627 B::SubAssign(_) => (ArithOp::Sub, true),
628 B::MulAssign(_) => (ArithOp::Mul, true),
629 B::DivAssign(_) => (ArithOp::Div, true),
630 B::RemAssign(_) => (ArithOp::Rem, true),
631 B::BitAndAssign(_) => (ArithOp::BitAnd, true),
632 B::BitOrAssign(_) => (ArithOp::BitOr, true),
633 B::BitXorAssign(_) => (ArithOp::BitXor, true),
634 B::ShlAssign(_) => (ArithOp::Shl, true),
635 B::ShrAssign(_) => (ArithOp::Shr, true),
636 _ => return None,
637 })
638}
639
640fn is_plain_place(expr: &syn::Expr) -> bool {
649 match expr {
650 syn::Expr::Path(e) => e.attrs.is_empty(),
651 syn::Expr::Field(e) => is_plain_place(&e.base),
652 syn::Expr::Unary(syn::ExprUnary {
653 op: syn::UnOp::Deref(_),
654 expr,
655 ..
656 }) => is_plain_place(expr),
657 syn::Expr::Paren(e) => is_plain_place(&e.expr),
658 syn::Expr::Group(e) => is_plain_place(&e.expr),
659 _ => false,
660 }
661}
662
663fn written_bool(expr: &syn::Expr) -> Option<bool> {
665 match expr {
666 syn::Expr::Paren(e) => written_bool(&e.expr),
667 syn::Expr::Group(e) => written_bool(&e.expr),
668 syn::Expr::Lit(syn::ExprLit {
669 lit: syn::Lit::Bool(value),
670 ..
671 }) => Some(value.value),
672 _ => None,
673 }
674}
675
676fn is_literal(expr: &syn::Expr) -> bool {
677 match expr {
678 syn::Expr::Paren(e) => is_literal(&e.expr),
679 syn::Expr::Group(e) => is_literal(&e.expr),
680 syn::Expr::Lit(_) => true,
681 syn::Expr::Unary(syn::ExprUnary {
682 op: syn::UnOp::Neg(_),
683 expr,
684 ..
685 }) => is_literal(expr),
686 _ => false,
687 }
688}
689
690fn in_order(earlier: usize, later: usize) -> bool {
694 earlier <= later }
696
697fn in_let_chain(expr: &syn::Expr) -> bool {
699 match expr {
700 syn::Expr::Let(_) => true,
701 syn::Expr::Binary(syn::ExprBinary {
702 op: syn::BinOp::And(_),
703 left,
704 right,
705 ..
706 }) => in_let_chain(left) || matches!(**right, syn::Expr::Let(_)),
707 _ => false,
708 }
709}
710
711const EXPR_MACROS: [&str; 18] = [
715 "assert_eq",
716 "assert_ne",
717 "debug_assert_eq",
718 "debug_assert_ne",
719 "vec",
720 "format",
721 "print",
722 "println",
723 "eprint",
724 "eprintln",
725 "write",
726 "writeln",
727 "panic",
728 "unreachable",
729 "todo",
730 "unimplemented",
731 "format_args",
732 "matches",
733];
734
735fn is_assign_op(op: &syn::BinOp) -> bool {
736 use syn::BinOp::*;
737 matches!(
738 op,
739 AddAssign(_)
740 | SubAssign(_)
741 | MulAssign(_)
742 | DivAssign(_)
743 | RemAssign(_)
744 | BitXorAssign(_)
745 | BitAndAssign(_)
746 | BitOrAssign(_)
747 | ShlAssign(_)
748 | ShrAssign(_)
749 )
750}
751
752fn int_literal(expr: &syn::Expr) -> Option<i128> {
753 match expr {
754 syn::Expr::Paren(e) => int_literal(&e.expr),
755 syn::Expr::Group(e) => int_literal(&e.expr),
756 syn::Expr::Lit(syn::ExprLit {
757 lit: syn::Lit::Int(lit),
758 ..
759 }) => lit.base10_parse().ok(),
760 syn::Expr::Unary(syn::ExprUnary {
761 op: syn::UnOp::Neg(_),
762 expr,
763 ..
764 }) => int_literal(expr).and_then(i128::checked_neg),
765 _ => None,
766 }
767}
768
769fn deletable(expr: &syn::Expr) -> bool {
771 match expr {
772 syn::Expr::Call(e) => e.attrs.is_empty(),
773 syn::Expr::MethodCall(e) => e.attrs.is_empty(),
774 syn::Expr::Assign(e) => e.attrs.is_empty(),
775 syn::Expr::Binary(e) => is_assign_op(&e.op),
777 syn::Expr::Try(e) => e.attrs.is_empty() && deletable_call(&e.expr),
778 syn::Expr::Await(e) => e.attrs.is_empty() && deletable_call(&e.base),
779 _ => false,
780 }
781}
782
783fn yields_iterator(receiver: &syn::Expr) -> bool {
787 const MAKERS: &[&str] = &[
788 "iter",
789 "iter_mut",
790 "into_iter",
791 "chars",
792 "char_indices",
793 "bytes",
794 "lines",
795 "keys",
796 "values",
797 "values_mut",
798 "into_keys",
799 "into_values",
800 "drain",
801 "windows",
802 "chunks",
803 "chunks_exact",
804 "rchunks",
805 "split",
806 "rsplit",
807 "splitn",
808 "rsplitn",
809 "split_terminator",
810 "split_whitespace",
811 "split_ascii_whitespace",
812 "split_inclusive",
813 "matches",
814 "match_indices",
815 "components",
816 "ancestors",
817 "range",
818 "map",
819 "filter",
820 "filter_map",
821 "flat_map",
822 "flatten",
823 "rev",
824 "skip",
825 "skip_while",
826 "take",
827 "take_while",
828 "step_by",
829 "zip",
830 "chain",
831 "enumerate",
832 "peekable",
833 "cloned",
834 "copied",
835 "inspect",
836 "scan",
837 "fuse",
838 "by_ref",
839 "map_while",
840 "cycle",
841 "args",
842 "encode_utf16",
843 ];
844 match receiver {
845 syn::Expr::Paren(e) => yields_iterator(&e.expr),
846 syn::Expr::Group(e) => yields_iterator(&e.expr),
847 syn::Expr::MethodCall(e) => MAKERS.contains(&e.method.to_string().as_str()),
848 syn::Expr::Range(_) => true,
849 _ => false,
850 }
851}
852
853fn variable_name(receiver: &str) -> Option<String> {
857 let mut expr = &syn::parse_str::<syn::Expr>(receiver).ok()?;
858 while let syn::Expr::Paren(inner) = expr {
859 if !inner.attrs.is_empty() {
860 return None;
861 }
862 expr = &inner.expr;
863 }
864 let syn::Expr::Path(path) = expr else {
865 return None;
866 };
867 if path.qself.is_some() || !path.attrs.is_empty() {
868 return None;
869 }
870 let name = path.path.get_ident()?.to_string();
871 let first = name.trim_start_matches("r#").chars().next()?;
872 (!first.is_uppercase()).then_some(name)
873}
874
875fn deletable_call(expr: &syn::Expr) -> bool {
876 match expr {
877 syn::Expr::Call(_) | syn::Expr::MethodCall(_) => true,
878 syn::Expr::Await(e) => deletable_call(&e.base),
879 _ => false,
880 }
881}
882
883fn has_ident(tokens: TokenStream, name: &str) -> bool {
884 tokens.into_iter().any(|tree| match tree {
885 TokenTree::Ident(ident) => ident == name,
886 TokenTree::Group(group) => has_ident(group.stream(), name),
887 _ => false,
888 })
889}
890
891pub const NO_ID: u32 = u32::MAX;
893
894#[derive(Debug, PartialEq, Eq, Clone)]
897pub struct NamedItem {
898 pub start: usize,
899 pub end: usize,
900 pub name: String,
901}
902
903pub fn named_items(source: &str) -> Vec<NamedItem> {
906 struct Namer {
907 path: Vec<String>,
908 items: Vec<NamedItem>,
909 }
910 impl Namer {
911 fn inside(&mut self, name: String, span: Option<Span>, visit: impl FnOnce(&mut Self)) {
912 self.path.push(name);
913 if let Some(span) = span {
914 let range = span.byte_range();
915 self.items.push(NamedItem {
916 start: range.start,
917 end: range.end,
918 name: self.path.join("::"),
919 });
920 }
921 visit(self);
922 self.path.pop();
923 }
924 }
925 impl<'ast> Visit<'ast> for Namer {
926 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
927 self.inside(node.ident.to_string(), None, |namer| {
928 visit::visit_item_mod(namer, node)
929 });
930 }
931 fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
932 self.inside(node.ident.to_string(), None, |namer| {
933 visit::visit_item_trait(namer, node)
934 });
935 }
936 fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
937 let of = squeezed(&node.self_ty.to_token_stream().to_string());
938 let name = match &node.trait_ {
939 Some((_, path, _)) => {
940 format!(
941 "<{} for {of}>",
942 squeezed(&path.to_token_stream().to_string())
943 )
944 }
945 None => of,
946 };
947 self.inside(name, None, |namer| visit::visit_item_impl(namer, node));
948 }
949 fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
950 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
951 visit::visit_item_fn(namer, node)
952 });
953 }
954 fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
955 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
956 visit::visit_impl_item_fn(namer, node)
957 });
958 }
959 fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
960 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
961 visit::visit_trait_item_fn(namer, node)
962 });
963 }
964 fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
965 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
966 }
967 fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
968 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
969 }
970 fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
971 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
972 }
973 }
974 let Ok(file) = syn::parse_file(source) else {
975 return vec![];
976 };
977 let mut namer = Namer {
978 path: vec![],
979 items: vec![],
980 };
981 namer.visit_file(&file);
982 namer.items
983}
984
985pub fn enclosing_item(items: &[NamedItem], offset: usize) -> &str {
987 items
988 .iter()
989 .filter(|item| item.start <= offset && offset < item.end)
990 .min_by_key(|item| item.end - item.start)
991 .map_or("", |item| item.name.as_str())
992}
993
994pub fn offset_of(source: &str, line: usize, column: usize) -> Option<usize> {
996 let start: usize = source
997 .split_inclusive('\n')
998 .take(line.checked_sub(1)?)
999 .map(str::len)
1000 .sum();
1001 let rest = source.get(start..)?;
1002 let within = rest
1003 .char_indices()
1004 .nth(column.checked_sub(1)?)
1005 .map_or(rest.len(), |(at, _)| at);
1006 Some(start + within)
1007}
1008
1009pub(crate) struct ItemIndex<'a>(Vec<(usize, &'a str)>);
1011
1012impl<'a> ItemIndex<'a> {
1013 pub(crate) fn new(items: &'a [NamedItem]) -> Self {
1014 use std::{cmp::Reverse, collections::BinaryHeap};
1015
1016 let mut starts: Vec<_> = items.iter().enumerate().collect();
1017 starts.sort_unstable_by_key(|&(_, item)| item.start);
1018 let mut boundaries: Vec<_> = items
1019 .iter()
1020 .flat_map(|item| [item.start, item.end])
1021 .collect();
1022 boundaries.sort_unstable();
1023
1024 let mut starts = starts.into_iter().peekable();
1025 let mut active = BinaryHeap::new();
1026 let mut intervals = Vec::new();
1027 for boundary in boundaries {
1028 while let Some(&(index, item)) =
1029 starts.peek().filter(|(_, item)| item.start <= boundary)
1030 {
1031 starts.next();
1032 active.push(Reverse((item.end - item.start, index)));
1034 }
1035 while active
1036 .peek()
1037 .is_some_and(|&Reverse((_, index))| items[index].end <= boundary)
1038 {
1039 active.pop();
1040 }
1041 let name = active
1042 .peek()
1043 .map_or("", |&Reverse((_, index))| items[index].name.as_str());
1044 if intervals
1045 .last()
1046 .is_none_or(|&(_, previous)| previous != name)
1047 {
1048 intervals.push((boundary, name));
1049 }
1050 }
1051 Self(intervals)
1052 }
1053
1054 pub(crate) fn at(&self, offset: usize) -> &'a str {
1055 let end = self.0.partition_point(|&(start, _)| start <= offset);
1056 self.0[..end].last().map_or("", |&(_, name)| name)
1057 }
1058}
1059
1060#[cfg(test)]
1061#[test]
1062fn indexed_item_boundaries_agree_with_the_previous_search() {
1063 let items = [
1064 (6, 10, "first tie"),
1065 (0, 16, "outer"),
1066 (2, 6, "before tie"),
1067 (6, 10, "second tie"),
1068 (4, 13, "overlap"),
1069 (7, 9, "inner"),
1070 (7, 7, "empty"),
1071 (17, 18, "after outer"),
1072 ]
1073 .map(|(start, end, name)| NamedItem {
1074 start,
1075 end,
1076 name: name.to_string(),
1077 });
1078 let indexed = ItemIndex::new(&items);
1079 for offset in 0..=20 {
1080 assert_eq!(
1081 indexed.at(offset),
1082 enclosing_item(&items, offset),
1083 "{offset}"
1084 );
1085 assert_eq!(ItemIndex::new(&[]).at(offset), "");
1086 }
1087}
1088
1089#[derive(Clone, PartialEq, Eq, Debug)]
1091pub struct SourceMutant {
1092 pub start: usize,
1093 pub end: usize,
1094 pub replacement: String,
1095 pub what: String,
1098 pub into: String,
1099}
1100
1101pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
1107 let SiteKind::Cmp { op, gap, .. } = &site.kind else {
1108 return None;
1109 };
1110 let replacement = match op {
1111 CmpOp::Le => "<",
1112 CmpOp::Ge => ">",
1113 _ => return None,
1114 };
1115 Some(SourceMutant {
1116 start: gap.0,
1117 end: gap.1,
1118 replacement: format!(" {replacement} "),
1119 what: op.symbol().to_string(),
1120 into: replacement.to_string(),
1121 })
1122}
1123
1124pub fn keep_line_ends(source: &str, mutants: &mut [SourceMutant]) {
1127 for mutant in mutants {
1128 let Some(replaced) = source.get(mutant.start..mutant.end) else {
1129 continue;
1130 };
1131 let lines = replaced.matches('\n').count();
1132 let kept = mutant.replacement.matches('\n').count();
1133 mutant
1134 .replacement
1135 .push_str(&"\n".repeat(lines.saturating_sub(kept)));
1136 }
1137}
1138
1139pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
1140 let change =
1141 |start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
1142 start,
1143 end,
1144 replacement,
1145 what: what.to_string(),
1146 into: into.to_string(),
1147 };
1148 let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
1151 let operands = gap
1153 .0
1154 .checked_sub(site.start)
1155 .zip(gap.1.checked_sub(site.start))
1156 .and_then(|(left, right)| {
1157 Some((
1158 site.text.get(..left)?.trim_end(),
1159 site.text.get(right..)?.trim_start(),
1160 "\n".repeat(site.text.get(left..right)?.matches('\n').count()),
1163 ))
1164 });
1165 match (binds, operands) {
1166 (std::cmp::Ordering::Less, Some((left, right, lines))) => change(
1167 site.start,
1168 site.end,
1169 format!("({left} {to} {lines}{right})"),
1170 &from,
1171 &to,
1172 ),
1173 (std::cmp::Ordering::Greater, Some((left, right, lines))) => change(
1174 site.start,
1175 site.end,
1176 format!("({left}) {to} {lines}({right})"),
1177 &from,
1178 &to,
1179 ),
1180 _ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
1181 }
1182 };
1183 let same = std::cmp::Ordering::Equal;
1184 match &site.kind {
1185 SiteKind::Cmp { op, gap, .. } => {
1186 let others: &[CmpOp] = match op {
1187 CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
1188 CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
1189 CmpOp::Le => &[CmpOp::Gt],
1190 CmpOp::Ge => &[CmpOp::Lt],
1191 CmpOp::Eq => &[CmpOp::Ne],
1192 CmpOp::Ne => &[CmpOp::Eq],
1193 };
1194 others
1195 .iter()
1196 .map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
1197 .collect()
1198 }
1199 SiteKind::Logic { and, gap, .. } => {
1200 let (from, to, binds) = if *and {
1202 ("&&", "||", std::cmp::Ordering::Less)
1203 } else {
1204 ("||", "&&", std::cmp::Ordering::Greater)
1205 };
1206 vec![operator(gap, from.into(), to.into(), binds)]
1207 }
1208 SiteKind::Arith {
1209 op, assign, gap, ..
1210 } => {
1211 let eq = if *assign { "=" } else { "" };
1212 [Some(op.swapped()), op.second(*assign)]
1213 .into_iter()
1214 .flatten()
1215 .map(|other| {
1216 operator(
1217 gap,
1218 format!("{}{eq}", op.symbol()),
1219 format!("{}{eq}", other.symbol()),
1220 if *assign {
1222 same
1223 } else {
1224 other.binding().cmp(&op.binding())
1225 },
1226 )
1227 })
1228 .collect()
1229 }
1230 SiteKind::Not { bang, .. } => vec![change(bang.0, bang.1, String::new(), "!", "")],
1231 SiteKind::Neg { minus, .. } => vec![change(minus.0, minus.1, String::new(), "-", "")],
1232 SiteKind::Body { value, .. } => {
1233 vec![change(
1234 site.start,
1235 site.end,
1236 format!(" {value} "),
1237 "body",
1238 value,
1239 )]
1240 }
1241 SiteKind::Arm {
1242 pattern,
1243 guard,
1244 removal,
1245 } => vec![match guard {
1246 ArmGuard::None(_) => change(removal.0, removal.1, String::new(), "arm", pattern),
1247 ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
1248 }],
1249 SiteKind::Guard { can_be_false } => [true, false]
1250 .into_iter()
1251 .filter(|value| *value || *can_be_false)
1252 .filter(|value| {
1254 syn::parse_str::<syn::Expr>(&site.text)
1255 .ok()
1256 .and_then(|guard| written_bool(&guard))
1257 != Some(*value)
1258 })
1259 .map(|value| {
1260 change(
1261 site.start,
1262 site.end,
1263 value.to_string(),
1264 "guard",
1265 &value.to_string(),
1266 )
1267 })
1268 .collect(),
1269 SiteKind::Field { name, removal, .. } => {
1270 vec![change(removal.0, removal.1, String::new(), "field", name)]
1271 }
1272 SiteKind::Stmt => vec![change(site.start, site.end, String::new(), "statement", "")],
1273 SiteKind::Range { inclusive, gap, .. } => {
1275 let (from, to) = if *inclusive {
1276 ("..=", "..")
1277 } else {
1278 ("..", "..=")
1279 };
1280 vec![change(gap.0, gap.1, to.to_string(), from, to)]
1281 }
1282 SiteKind::SliceEnd { first, method, .. } => {
1285 let (from, to) = if *first {
1286 ("first", "last")
1287 } else {
1288 ("last", "first")
1289 };
1290 vec![change(method.0, method.1, to.to_string(), from, to)]
1291 }
1292 SiteKind::Return { .. } | SiteKind::MinMax { .. } => vec![],
1293 }
1294}
1295
1296pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
1298 let gap = match &site.kind {
1299 SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
1300 gap
1301 }
1302 _ => return,
1303 };
1304 if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
1305 let span = operator.span().byte_range();
1306 for mutant in mutants {
1307 mutant.start = gap.0 + span.start;
1308 mutant.end = gap.0 + span.end;
1309 mutant.replacement.clone_from(&mutant.into);
1310 }
1311 }
1312}
1313
1314pub fn iterator_values(output: &syn::ReturnType) -> Vec<String> {
1317 let syn::ReturnType::Type(_, ty) = output else {
1318 return vec![];
1319 };
1320 let syn::Type::ImplTrait(opaque) = &**ty else {
1321 return vec![];
1322 };
1323 iterator_type_values(opaque, &[], false)
1324}
1325
1326fn iterator_type_values(
1327 opaque: &syn::TypeImplTrait,
1328 error_values: &[&str],
1329 extended: bool,
1330) -> Vec<String> {
1331 let item = opaque.bounds.iter().find_map(|bound| {
1332 let syn::TypeParamBound::Trait(bound) = bound else {
1333 return None;
1334 };
1335 let last = bound.path.segments.last()?;
1336 let syn::PathArguments::AngleBracketed(list) = &last.arguments else {
1337 return None;
1338 };
1339 (last.ident == "Iterator").then_some(())?;
1340 list.args.iter().find_map(|arg| match arg {
1341 syn::GenericArgument::AssocType(item) if item.ident == "Item" => Some(&item.ty),
1342 _ => None,
1343 })
1344 });
1345 let Some(item) = item else {
1346 return vec![];
1347 };
1348 if !extended && has_ident(item.to_token_stream(), "impl") {
1349 return vec!["::core::iter::empty()".to_string()];
1350 }
1351 let mut values = vec!["::core::iter::empty()".to_string()];
1352 values.extend(
1353 values_of(item, error_values, extended)
1354 .iter()
1355 .map(|value| format!("::core::iter::once({value})")),
1356 );
1357 values
1358}
1359
1360fn squeezed(text: &str) -> String {
1362 text.chars().filter(|c| !c.is_whitespace()).collect()
1363}
1364
1365fn tokens_of(text: &str) -> String {
1368 match text.parse::<TokenStream>() {
1369 Ok(tokens) => tokens.to_string(),
1370 Err(_) => text.to_string(),
1371 }
1372}
1373
1374fn may_bypass_result_probe(body: &syn::Block) -> bool {
1377 struct EarlyExit(bool);
1378
1379 impl<'ast> Visit<'ast> for EarlyExit {
1380 fn visit_expr(&mut self, expr: &'ast syn::Expr) {
1381 if self.0 {
1382 return;
1383 }
1384 match expr {
1385 syn::Expr::Return(_) | syn::Expr::Try(_) | syn::Expr::Verbatim(_) => self.0 = true,
1386 syn::Expr::Async(_) | syn::Expr::Closure(_) | syn::Expr::Const(_) => {}
1387 _ => visit::visit_expr(self, expr),
1388 }
1389 }
1390
1391 fn visit_macro(&mut self, _: &'ast syn::Macro) {
1392 self.0 = true;
1393 }
1394
1395 fn visit_item(&mut self, _: &'ast syn::Item) {}
1396 fn visit_pat(&mut self, _: &'ast syn::Pat) {}
1397 fn visit_type(&mut self, _: &'ast syn::Type) {}
1398 }
1399
1400 let mut exits = EarlyExit(false);
1401 exits.visit_block(body);
1402 exits.0
1403}
1404
1405fn does_nothing_else(expr: &syn::Expr) -> bool {
1408 struct Effects(bool);
1409 impl<'ast> Visit<'ast> for Effects {
1410 fn visit_expr(&mut self, expr: &'ast syn::Expr) {
1411 match expr {
1412 syn::Expr::Binary(_)
1413 | syn::Expr::Unary(_)
1414 | syn::Expr::Paren(_)
1415 | syn::Expr::Group(_)
1416 | syn::Expr::Path(_)
1417 | syn::Expr::Lit(_)
1418 | syn::Expr::Field(_)
1419 | syn::Expr::Reference(_)
1420 | syn::Expr::Cast(_)
1421 | syn::Expr::Tuple(_) => syn::visit::visit_expr(self, expr),
1422 _ => self.0 = true,
1423 }
1424 }
1425 fn visit_bin_op(&mut self, op: &'ast syn::BinOp) {
1426 use syn::BinOp::*;
1427 if !matches!(
1428 op,
1429 Add(_)
1430 | Sub(_)
1431 | Mul(_)
1432 | Div(_)
1433 | Rem(_)
1434 | And(_)
1435 | Or(_)
1436 | BitXor(_)
1437 | BitAnd(_)
1438 | BitOr(_)
1439 | Shl(_)
1440 | Shr(_)
1441 | Eq(_)
1442 | Lt(_)
1443 | Le(_)
1444 | Ne(_)
1445 | Ge(_)
1446 | Gt(_)
1447 ) {
1448 self.0 = true; }
1450 }
1451 }
1452 let mut effects = Effects(false);
1453 effects.visit_expr(expr);
1454 !effects.0
1455}
1456
1457pub fn body_values(output: &syn::ReturnType) -> Vec<String> {
1460 body_values_with_errors(output, &[], false)
1461}
1462
1463fn body_values_with_errors(
1464 output: &syn::ReturnType,
1465 error_values: &[&str],
1466 extended: bool,
1467) -> Vec<String> {
1468 match output {
1469 syn::ReturnType::Default => vec!["()".to_string()],
1470 syn::ReturnType::Type(_, ty) => {
1471 if !extended && has_ident(ty.to_token_stream(), "impl") {
1474 return vec![];
1475 }
1476 values_of(ty, error_values, extended)
1477 }
1478 }
1479}
1480
1481fn product(parts: &[Vec<String>], format: impl Fn(&[&str]) -> String) -> Vec<String> {
1482 if parts.iter().any(Vec::is_empty) {
1483 return vec![];
1484 }
1485 let mut positions = vec![0; parts.len()];
1486 let mut row: Vec<_> = parts.iter().map(|part| part[0].as_str()).collect();
1487 let mut results = vec![];
1488 loop {
1489 results.push(format(&row));
1490 let Some(next) = (0..parts.len())
1491 .rev()
1492 .find(|&i| positions[i] + 1 < parts[i].len())
1493 else {
1494 return results;
1495 };
1496 positions[next] += 1;
1497 row[next] = &parts[next][positions[next]];
1498 for i in next + 1..parts.len() {
1499 positions[i] = 0;
1500 row[i] = &parts[i][0];
1501 }
1502 }
1503}
1504
1505fn values_of(ty: &syn::Type, error_values: &[&str], extended: bool) -> Vec<String> {
1506 let each = |inner: &syn::Type, wrap: &dyn Fn(&str) -> String| -> Vec<String> {
1507 values_of(inner, error_values, extended)
1508 .iter()
1509 .map(|v| wrap(v))
1510 .collect()
1511 };
1512 match ty {
1513 syn::Type::Paren(t) => values_of(&t.elem, error_values, extended),
1514 syn::Type::Group(t) => values_of(&t.elem, error_values, extended),
1515 syn::Type::Never(_) => vec![],
1516 syn::Type::ImplTrait(opaque) => iterator_type_values(opaque, error_values, extended),
1517 syn::Type::Tuple(t) => {
1519 let parts: Vec<Vec<String>> = t
1520 .elems
1521 .iter()
1522 .map(|ty| values_of(ty, error_values, extended))
1523 .collect();
1524 product(&parts, |row| match row {
1525 [one] => format!("({one},)"),
1526 _ => format!("({})", row.join(", ")),
1527 })
1528 }
1529 syn::Type::Array(t) => {
1530 let len = t.len.to_token_stream().to_string();
1531 each(&t.elem, &|v| format!("[{v}; {len}]"))
1532 }
1533 syn::Type::Reference(t) => match &*t.elem {
1534 syn::Type::Path(p) if p.path.is_ident("str") && t.mutability.is_none() => {
1535 vec!["\"\"".to_string(), "\"xyzzy\"".to_string()]
1536 }
1537 syn::Type::Slice(slice) => {
1538 let mut values = vec!["Vec::leak(Vec::new())".to_string()];
1539 values.extend(each(&slice.elem, &|v| format!("Vec::leak(vec![{v}])")));
1540 values
1541 }
1542 inner => each(inner, &|v| format!("Box::leak(Box::new({v}))")),
1543 },
1544 syn::Type::Path(p) if p.qself.is_none() => {
1545 let Some(last) = p.path.segments.last() else {
1546 return vec!["Default::default()".to_string()];
1547 };
1548 let mut bare = p.path.clone();
1550 if let Some(segment) = bare.segments.last_mut() {
1551 segment.arguments = syn::PathArguments::None;
1552 }
1553 let bare = squeezed(&bare.to_token_stream().to_string());
1554 let arguments: Vec<&syn::Type> = match &last.arguments {
1555 syn::PathArguments::AngleBracketed(list) => list
1556 .args
1557 .iter()
1558 .filter_map(|arg| match arg {
1559 syn::GenericArgument::Type(ty) => Some(ty),
1560 _ => None,
1561 })
1562 .collect(),
1563 _ => vec![],
1564 };
1565 let name = last.ident.to_string();
1566 let texts = |list: &[&str]| list.iter().map(|v| v.to_string()).collect::<Vec<_>>();
1567 let one = |text: String| "1.try_into().unwrap()".replace('1', &text);
1568 match (name.as_str(), &arguments[..]) {
1569 ("bool", []) => texts(&["true", "false"]),
1570 ("i8" | "i16" | "i32" | "i64" | "i128" | "isize", []) => texts(&["0", "1", "-1"]),
1571 ("u8" | "u16" | "u32" | "u64" | "u128" | "usize", []) => texts(&["0", "1"]),
1572 ("f32" | "f64", []) => texts(&["0.0", "1.0", "-1.0"]),
1573 (
1574 "NonZeroI8" | "NonZeroI16" | "NonZeroI32" | "NonZeroI64" | "NonZeroI128"
1575 | "NonZeroIsize",
1576 [],
1577 ) => vec![one("1".into()), one("(-1)".into())],
1578 (
1579 "NonZeroU8" | "NonZeroU16" | "NonZeroU32" | "NonZeroU64" | "NonZeroU128"
1580 | "NonZeroUsize",
1581 [],
1582 ) => vec![one("1".into())],
1583 ("NonZero", [inner]) => {
1584 let unsigned = squeezed(&inner.to_token_stream().to_string()).starts_with('u');
1585 let mut values = vec![one("1".into())];
1586 if !unsigned {
1587 values.push(one("(-1)".into()));
1588 }
1589 values
1590 }
1591 ("String", []) => texts(&["String::new()", "\"xyzzy\".into()"]),
1592 ("Result", arguments) => {
1593 let mut values = match arguments.first() {
1594 Some(ok) => each(ok, &|v| format!("Ok({v})")),
1595 None => vec!["Ok(Default::default())".to_string()],
1597 };
1598 values.extend(error_values.iter().map(|expression| {
1599 let end = if expression.rsplit('\n').next().unwrap_or("").contains("//") {
1601 "\n"
1602 } else {
1603 ""
1604 };
1605 format!("Err({expression}{end})")
1606 }));
1607 values
1608 }
1609 ("Option", [inner]) => {
1610 let mut values = vec!["None".to_string()];
1611 values.extend(each(inner, &|v| format!("Some({v})")));
1612 values
1613 }
1614 ("Vec", [inner]) => {
1615 let mut values = vec!["vec![]".to_string()];
1616 values.extend(each(inner, &|v| format!("vec![{v}]")));
1617 values
1618 }
1619 ("Box" | "Rc" | "Arc" | "Cell" | "RefCell" | "Mutex", [inner]) => {
1620 each(inner, &|v| format!("{bare}::new({v})"))
1621 }
1622 ("BinaryHeap" | "BTreeSet" | "HashSet" | "LinkedList" | "VecDeque", [inner]) => {
1623 let mut values = vec![format!("{bare}::new()")];
1624 values.extend(each(inner, &|v| format!("{bare}::from_iter([{v}])")));
1625 values
1626 }
1627 ("BTreeMap" | "HashMap", [key, value]) => {
1628 let mut values = vec![format!("{bare}::new()")];
1629 values.extend(product(
1630 &[
1631 values_of(key, error_values, extended),
1632 values_of(value, error_values, extended),
1633 ],
1634 |row| format!("{bare}::from_iter([({})])", row.join(", ")),
1635 ));
1636 values
1637 }
1638 ("Cow", [inner]) => {
1639 let borrowed: syn::Type = syn::parse_quote!(&#inner);
1640 values_of(&borrowed, error_values, extended)
1641 .iter()
1642 .flat_map(|v| {
1643 [
1644 format!("{bare}::Borrowed({v})"),
1645 format!("{bare}::Owned({v}.to_owned())"),
1646 ]
1647 })
1648 .collect()
1649 }
1650 ("HttpResponse", []) => vec![format!("{bare}::Ok().finish()")],
1651 (_, [inner]) if extended => {
1652 let mut values = vec![format!("{bare}::new()")];
1653 for value in values_of(inner, error_values, extended) {
1654 values.extend([
1655 format!("{bare}::from_iter([{value}])"),
1656 format!("{bare}::new({value})"),
1657 format!("{bare}::from({value})"),
1658 ]);
1659 }
1660 values
1661 }
1662 _ => vec!["Default::default()".to_string()],
1663 }
1664 }
1665 _ => vec!["Default::default()".to_string()],
1666 }
1667}
1668
1669pub(crate) fn is_skipped(attrs: &[syn::Attribute]) -> bool {
1672 fn marked(meta: &syn::Meta) -> bool {
1673 let path = meta.path();
1674 if path.segments.len() == 2
1675 && path.segments[0].ident == "mutants"
1676 && path.segments[1].ident == "skip"
1677 {
1678 return true;
1679 }
1680 if path.is_ident("cfg_attr")
1681 && let syn::Meta::List(list) = meta
1682 && let Ok(parts) = list.parse_args_with(
1683 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1684 )
1685 {
1686 return parts.iter().skip(1).any(marked);
1687 }
1688 false
1689 }
1690
1691 attrs.iter().any(|attr| marked(&attr.meta))
1692}
1693
1694pub(crate) fn cfg_possible_without_test(meta: &syn::Meta, desired: bool) -> bool {
1696 if meta.path().is_ident("test") {
1697 return !desired;
1698 }
1699 let syn::Meta::List(list) = meta else {
1700 return true;
1701 };
1702 let Ok(parts) = list.parse_args_with(
1703 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1704 ) else {
1705 return true;
1706 };
1707 if list.path.is_ident("not") && parts.len() == 1 {
1708 return cfg_possible_without_test(&parts[0], !desired);
1709 }
1710 if list.path.is_ident("all") || list.path.is_ident("any") {
1711 return if list.path.is_ident("all") == desired {
1712 parts
1713 .iter()
1714 .all(|part| cfg_possible_without_test(part, desired))
1715 } else {
1716 parts
1717 .iter()
1718 .any(|part| cfg_possible_without_test(part, desired))
1719 };
1720 }
1721 true
1722}
1723
1724fn cfg_value(meta: &syn::Meta, features: &BTreeSet<String>) -> Option<bool> {
1727 match meta {
1728 syn::Meta::NameValue(pair) if pair.path.is_ident("feature") => match &pair.value {
1729 syn::Expr::Lit(syn::ExprLit {
1730 lit: syn::Lit::Str(name),
1731 ..
1732 }) => Some(features.contains(&name.value())),
1733 _ => None,
1734 },
1735 syn::Meta::List(list) => {
1736 let parts = list
1737 .parse_args_with(
1738 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1739 )
1740 .ok()?;
1741 let mut values = parts.iter().map(|part| cfg_value(part, features));
1742 if list.path.is_ident("not") && parts.len() == 1 {
1743 values.next()?.map(|value| !value)
1744 } else if list.path.is_ident("all") {
1745 values
1747 .try_fold(Some(true), |all, value| match (all, value) {
1748 (_, Some(false)) => Err(()),
1749 (Some(true), Some(true)) => Ok(Some(true)),
1750 _ => Ok(None),
1751 })
1752 .unwrap_or(Some(false))
1753 } else if list.path.is_ident("any") {
1754 values
1755 .try_fold(Some(false), |any, value| match (any, value) {
1756 (_, Some(true)) => Err(()),
1757 (Some(false), Some(false)) => Ok(Some(false)),
1758 _ => Ok(None),
1759 })
1760 .unwrap_or(Some(true))
1761 } else {
1762 None
1763 }
1764 }
1765 _ => None,
1766 }
1767}
1768
1769fn cfg_is_off(attrs: &[syn::Attribute], features: &BTreeSet<String>) -> bool {
1770 attrs.iter().any(|attr| {
1771 attr.path().is_ident("cfg")
1772 && attr
1773 .parse_args::<syn::Meta>()
1774 .is_ok_and(|meta| cfg_value(&meta, features) == Some(false))
1775 })
1776}
1777
1778pub(crate) fn settled_cfg_attributes(
1781 source: &str,
1782 file: &syn::File,
1783 features: &BTreeSet<String>,
1784) -> Vec<(usize, usize)> {
1785 struct Settled<'a> {
1786 source: &'a str,
1787 features: &'a BTreeSet<String>,
1788 found: Vec<(usize, usize)>,
1789 }
1790 impl<'ast> Visit<'ast> for Settled<'_> {
1791 fn visit_attribute(&mut self, attr: &'ast syn::Attribute) {
1792 let range = attr.span().byte_range();
1793 if attr.path().is_ident("cfg")
1794 && attr
1795 .parse_args::<syn::Meta>()
1796 .is_ok_and(|meta| cfg_value(&meta, self.features) == Some(true))
1797 && self.source.get(range.clone()).is_some()
1798 {
1799 self.found.push((range.start, range.end));
1800 }
1801 }
1802 }
1803 let mut settled = Settled {
1804 source,
1805 features,
1806 found: vec![],
1807 };
1808 settled.visit_file(file);
1809 settled.found
1810}
1811
1812pub(crate) fn inactive_ranges(
1815 source: &str,
1816 file: &syn::File,
1817 features: &BTreeSet<String>,
1818) -> Vec<(usize, usize)> {
1819 struct Inactive<'a> {
1820 source: &'a str,
1821 features: &'a BTreeSet<String>,
1822 found: Vec<(usize, usize)>,
1823 own_vec: bool,
1825 }
1826 impl Inactive<'_> {
1827 fn off(&mut self, attrs: &[syn::Attribute], span: Span) -> bool {
1829 if !cfg_is_off(attrs, self.features) {
1830 return false;
1831 }
1832 let range = span.byte_range();
1833 if self.source.get(range.clone()).is_some() {
1834 self.found.push((range.start, range.end));
1835 }
1836 true
1837 }
1838 }
1839 macro_rules! nodes {
1840 ($($visit:ident, $default:path, $node:ty;)*) => {
1841 impl<'ast> Visit<'ast> for Inactive<'_> {
1842 $(fn $visit(&mut self, node: &'ast $node) {
1843 if !self.off(&node.attrs, node.span()) {
1844 $default(self, node);
1845 }
1846 })*
1847 fn visit_item(&mut self, node: &'ast syn::Item) {
1848 if !self.off(item_attrs(node), node.span()) {
1849 visit::visit_item(self, node);
1850 }
1851 }
1852 fn visit_impl_item(&mut self, node: &'ast syn::ImplItem) {
1853 let attrs = match node {
1854 syn::ImplItem::Const(item) => &item.attrs[..],
1855 syn::ImplItem::Fn(item) => &item.attrs,
1856 syn::ImplItem::Type(item) => &item.attrs,
1857 syn::ImplItem::Macro(item) => &item.attrs,
1858 _ => &[],
1859 };
1860 if !self.off(attrs, node.span()) {
1861 visit::visit_impl_item(self, node);
1862 }
1863 }
1864 fn visit_foreign_item(&mut self, node: &'ast syn::ForeignItem) {
1865 let attrs = match node {
1866 syn::ForeignItem::Fn(item) => &item.attrs[..],
1867 syn::ForeignItem::Static(item) => &item.attrs,
1868 syn::ForeignItem::Type(item) => &item.attrs,
1869 syn::ForeignItem::Macro(item) => &item.attrs,
1870 _ => &[],
1871 };
1872 if !self.off(attrs, node.span()) {
1873 visit::visit_foreign_item(self, node);
1874 }
1875 }
1876 fn visit_macro(&mut self, node: &'ast syn::Macro) {
1879 type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
1880 if node.path.segments.last().is_some_and(|name| name.ident == "vec")
1881 && !self.own_vec
1882 && let Ok(args) = node.parse_body_with(Args::parse_terminated)
1883 {
1884 for arg in &args {
1885 self.visit_expr(arg);
1886 }
1887 }
1888 }
1889 fn visit_trait_item(&mut self, node: &'ast syn::TraitItem) {
1890 let attrs = match node {
1891 syn::TraitItem::Const(item) => &item.attrs[..],
1892 syn::TraitItem::Fn(item) => &item.attrs,
1893 syn::TraitItem::Type(item) => &item.attrs,
1894 syn::TraitItem::Macro(item) => &item.attrs,
1895 _ => &[],
1896 };
1897 if !self.off(attrs, node.span()) {
1898 visit::visit_trait_item(self, node);
1899 }
1900 }
1901 }
1902 };
1903 }
1904 nodes! {
1905 visit_local, visit::visit_local, syn::Local;
1906 visit_arm, visit::visit_arm, syn::Arm;
1907 visit_field_value, visit::visit_field_value, syn::FieldValue;
1908 visit_variant, visit::visit_variant, syn::Variant;
1909 visit_field, visit::visit_field, syn::Field;
1910 visit_stmt_macro, visit::visit_stmt_macro, syn::StmtMacro;
1911 visit_expr_block, visit::visit_expr_block, syn::ExprBlock;
1912 visit_expr_if, visit::visit_expr_if, syn::ExprIf;
1913 visit_expr_call, visit::visit_expr_call, syn::ExprCall;
1914 visit_expr_method_call, visit::visit_expr_method_call, syn::ExprMethodCall;
1915 visit_expr_macro, visit::visit_expr_macro, syn::ExprMacro;
1916 visit_expr_match, visit::visit_expr_match, syn::ExprMatch;
1917 visit_expr_assign, visit::visit_expr_assign, syn::ExprAssign;
1918 visit_expr_return, visit::visit_expr_return, syn::ExprReturn;
1919 visit_expr_for_loop, visit::visit_expr_for_loop, syn::ExprForLoop;
1920 visit_expr_while, visit::visit_expr_while, syn::ExprWhile;
1921 visit_expr_loop, visit::visit_expr_loop, syn::ExprLoop;
1922 visit_expr_unsafe, visit::visit_expr_unsafe, syn::ExprUnsafe;
1923 visit_expr_binary, visit::visit_expr_binary, syn::ExprBinary;
1924 visit_expr_lit, visit::visit_expr_lit, syn::ExprLit;
1925 visit_expr_path, visit::visit_expr_path, syn::ExprPath;
1926 visit_expr_array, visit::visit_expr_array, syn::ExprArray;
1927 visit_expr_tuple, visit::visit_expr_tuple, syn::ExprTuple;
1928 visit_expr_reference, visit::visit_expr_reference, syn::ExprReference;
1929 visit_expr_unary, visit::visit_expr_unary, syn::ExprUnary;
1930 visit_expr_field, visit::visit_expr_field, syn::ExprField;
1931 visit_expr_index, visit::visit_expr_index, syn::ExprIndex;
1932 visit_expr_cast, visit::visit_expr_cast, syn::ExprCast;
1933 visit_expr_closure, visit::visit_expr_closure, syn::ExprClosure;
1934 visit_expr_struct, visit::visit_expr_struct, syn::ExprStruct;
1935 visit_expr_repeat, visit::visit_expr_repeat, syn::ExprRepeat;
1936 visit_expr_range, visit::visit_expr_range, syn::ExprRange;
1937 visit_expr_paren, visit::visit_expr_paren, syn::ExprParen;
1938 visit_expr_try, visit::visit_expr_try, syn::ExprTry;
1939 visit_expr_await, visit::visit_expr_await, syn::ExprAwait;
1940 visit_expr_break, visit::visit_expr_break, syn::ExprBreak;
1941 visit_expr_continue, visit::visit_expr_continue, syn::ExprContinue;
1942 visit_expr_let, visit::visit_expr_let, syn::ExprLet;
1943 visit_expr_async, visit::visit_expr_async, syn::ExprAsync;
1944 visit_expr_const, visit::visit_expr_const, syn::ExprConst;
1945 visit_expr_yield, visit::visit_expr_yield, syn::ExprYield;
1946 visit_expr_try_block, visit::visit_expr_try_block, syn::ExprTryBlock;
1947 visit_expr_raw_addr, visit::visit_expr_raw_addr, syn::ExprRawAddr;
1948 }
1949 if cfg_is_off(&file.attrs, features) {
1950 return vec![(0, source.len())];
1951 }
1952 let mut inactive = Inactive {
1953 source,
1954 features,
1955 found: vec![],
1956 own_vec: source.split("macro_rules").skip(1).any(|after| {
1958 after
1959 .trim_start()
1960 .strip_prefix('!')
1961 .is_some_and(|name| name.trim_start().starts_with("vec"))
1962 }),
1963 };
1964 inactive.visit_file(file);
1965 inactive.found
1966}
1967
1968pub(crate) fn reach(expr: &str) -> Option<(crate::plan::Reach, Option<u32>)> {
1973 use crate::plan::Reach;
1974 fn literal(expr: &syn::Expr) -> Option<i128> {
1975 match expr {
1976 syn::Expr::Lit(syn::ExprLit {
1977 lit: syn::Lit::Int(integer),
1978 ..
1979 }) => integer.base10_parse().ok(),
1980 syn::Expr::Paren(inner) => literal(&inner.expr),
1981 _ => None,
1982 }
1983 }
1984 let mut expr = &syn::parse_str::<syn::Expr>(expr).ok()?;
1985 while let syn::Expr::Paren(inner) = expr {
1986 expr = &inner.expr;
1987 }
1988 let syn::Expr::Binary(binary) = expr else {
1989 return None;
1990 };
1991 let (left, right) = (literal(&binary.left), literal(&binary.right));
1992 let power_of_two = |k: i128| k >= 2 && k & (k - 1) == 0;
1993 let reach = match binary.op {
1995 syn::BinOp::Mul(_) => left
1996 .or(right)
1997 .filter(|k| power_of_two(*k))
1998 .map(Reach::Multiples),
1999 syn::BinOp::Shl(_) => {
2000 let bits = right.filter(|bits| (1..=100).contains(bits))?;
2001 return Some((Reach::Multiples(1 << bits), Some(bits as u32)));
2002 }
2003 syn::BinOp::BitAnd(_) => left.or(right).filter(|mask| *mask >= 0).map(Reach::Bits),
2004 syn::BinOp::Rem(_) => right.filter(|limit| *limit >= 1).map(Reach::Below),
2005 _ => None,
2006 };
2007 reach.map(|reach| (reach, None))
2008}
2009
2010pub(crate) fn test_only_ranges(source: &str, file: &syn::File) -> Vec<(usize, usize)> {
2013 if is_test_only(&file.attrs) {
2014 return vec![(0, source.len())];
2015 }
2016 let mut found = vec![];
2017 for item in &file.items {
2018 test_only_items(source, item, &mut found);
2019 }
2020 found
2021}
2022
2023fn test_only_items(source: &str, item: &syn::Item, found: &mut Vec<(usize, usize)>) {
2024 let mut note = |attrs: &[syn::Attribute], span: Span| {
2025 let test_only = is_test_only(attrs);
2026 let range = span.byte_range();
2027 if test_only && source.get(range.clone()).is_some() {
2028 found.push((range.start, range.end));
2029 }
2030 test_only
2031 };
2032 if note(item_attrs(item), item.span()) {
2033 return;
2034 }
2035 match item {
2036 syn::Item::Mod(module) => {
2037 for inner in module.content.iter().flat_map(|(_, items)| items) {
2038 test_only_items(source, inner, found);
2039 }
2040 }
2041 syn::Item::Impl(block) => {
2042 for inner in &block.items {
2043 if let syn::ImplItem::Fn(function) = inner {
2044 note(&function.attrs, inner.span());
2045 }
2046 }
2047 }
2048 _ => {}
2049 }
2050}
2051
2052pub(crate) const LEFT_OUT: &str = "__tmt_left_out__";
2057
2058pub(crate) fn same_tokens(a: &str, b: &str) -> Option<bool> {
2059 same_tokens_of(a, b, false)
2060}
2061
2062pub(crate) fn same_built_tokens(a: &str, b: &str) -> Option<bool> {
2065 same_tokens_of(a, b, true)
2066}
2067
2068const KEYWORDS: [&str; 39] = [
2071 "as", "async", "await", "box", "break", "const", "continue", "crate", "do", "dyn", "else",
2072 "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move",
2073 "mut", "pub", "ref", "return", "static", "struct", "super", "trait", "try", "type", "unsafe",
2074 "use", "where", "while", "yield", "union",
2075];
2076
2077fn same_tokens_of(a: &str, b: &str, holes: bool) -> Option<bool> {
2078 fn tokens(
2083 stream: TokenStream,
2084 plain: bool,
2085 holes: bool,
2086 list: Option<(proc_macro2::Delimiter, bool)>,
2087 ) -> Vec<String> {
2088 let mut out = vec![];
2089 let mut trees = stream.into_iter().peekable();
2090 let (mut named, mut called) = (false, false);
2092 let mut callable = false;
2094 let mut ticked = false;
2096 let mut hashed = false;
2098 while let Some(tree) = trees.next() {
2099 let (was_named, was_called, was_callable) = (named, called, callable);
2100 let (was_ticked, was_hashed) = (ticked, hashed);
2101 (named, called, callable, ticked, hashed) = (false, false, false, false, false);
2102 match tree {
2103 TokenTree::Punct(hash) if hash.as_char() == '#' => {
2105 let bang =
2106 matches!(trees.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '!')
2107 .then(|| trees.next());
2108 let is_doc = matches!(trees.peek(), Some(TokenTree::Group(group))
2112 if group.delimiter() == proc_macro2::Delimiter::Bracket
2113 && matches!(group.stream().into_iter().next(),
2114 Some(TokenTree::Ident(name)) if name == "doc")
2115 && (plain
2116 || group
2117 .span()
2118 .source_text()
2119 .is_some_and(|written| written.starts_with('/'))));
2120 if is_doc {
2121 trees.next();
2122 continue;
2123 }
2124 out.push("#".to_string());
2125 if bang.is_some() {
2126 out.push("!".to_string());
2127 }
2128 hashed = true;
2129 }
2130 TokenTree::Group(group) => {
2131 let inner = tokens(
2133 group.stream(),
2134 plain && !was_called,
2135 holes,
2136 Some((group.delimiter(), was_callable)),
2137 );
2138 out.push(format!("{:?}({})", group.delimiter(), inner.join(" ")));
2139 callable = !was_hashed
2143 && matches!(
2144 group.delimiter(),
2145 proc_macro2::Delimiter::Parenthesis | proc_macro2::Delimiter::Bracket
2146 );
2147 }
2148 TokenTree::Punct(mark) => {
2149 called = was_named && mark.as_char() == '!';
2150 ticked = mark.as_char() == '\'';
2151 out.push(mark.to_string());
2152 }
2153 TokenTree::Ident(name) => {
2154 named = true;
2155 called = was_called;
2157 let name = name.to_string();
2158 callable = name == "fn"
2163 || (!was_ticked
2164 && !KEYWORDS.contains(&name.as_str())
2165 && !(holes && name == LEFT_OUT));
2166 out.push(name);
2167 }
2168 other => out.push(other.to_string()),
2169 }
2170 }
2171 if !plain {
2172 return out;
2173 }
2174 let mut kept: Vec<String> = Vec::with_capacity(out.len());
2178 let mut items = out.into_iter().peekable();
2179 while let Some(item) = items.next() {
2180 if !holes || item != LEFT_OUT {
2181 kept.push(item);
2182 continue;
2183 }
2184 if items.peek().is_some_and(|next| next == "," || next == ";") {
2185 items.next();
2186 } else if items.peek().is_none() && kept.last().is_some_and(|last| last == ",") {
2187 kept.pop();
2188 }
2189 }
2190 if kept.last().is_some_and(|last| last == ",") {
2194 let says_nothing = match list {
2195 Some((proc_macro2::Delimiter::Brace | proc_macro2::Delimiter::Bracket, _)) => true,
2196 Some((proc_macro2::Delimiter::Parenthesis, after_a_name)) => after_a_name,
2197 _ => false,
2198 };
2199 if says_nothing {
2200 kept.pop();
2201 }
2202 }
2203 kept
2204 }
2205 let lex = |text: &str| Some(tokens(text.parse::<TokenStream>().ok()?, true, holes, None));
2206 Some(lex(a)? == lex(b)?)
2207}
2208
2209fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
2210 match item {
2211 syn::Item::Const(item) => &item.attrs,
2212 syn::Item::Enum(item) => &item.attrs,
2213 syn::Item::ExternCrate(item) => &item.attrs,
2214 syn::Item::Fn(item) => &item.attrs,
2215 syn::Item::ForeignMod(item) => &item.attrs,
2216 syn::Item::Impl(item) => &item.attrs,
2217 syn::Item::Macro(item) => &item.attrs,
2218 syn::Item::Mod(item) => &item.attrs,
2219 syn::Item::Static(item) => &item.attrs,
2220 syn::Item::Struct(item) => &item.attrs,
2221 syn::Item::Trait(item) => &item.attrs,
2222 syn::Item::TraitAlias(item) => &item.attrs,
2223 syn::Item::Type(item) => &item.attrs,
2224 syn::Item::Union(item) => &item.attrs,
2225 syn::Item::Use(item) => &item.attrs,
2226 _ => &[],
2227 }
2228}
2229
2230pub(crate) fn is_test_only(attrs: &[syn::Attribute]) -> bool {
2232 attrs.iter().any(|attr| {
2233 let path = attr.path();
2234 if path.segments.last().is_some_and(|s| s.ident == "test") {
2235 return true;
2236 }
2237 path.is_ident("cfg")
2238 && attr
2239 .parse_args::<syn::Meta>()
2240 .is_ok_and(|meta| !cfg_possible_without_test(&meta, true))
2241 })
2242}
2243
2244impl<'ast> Visit<'ast> for Finder<'_> {
2245 fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
2246 fn visit_local(&mut self, node: &'ast syn::Local) {
2247 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2248 visit::visit_local(self, node);
2249 }
2250 }
2251 fn visit_pat(&mut self, node: &'ast syn::Pat) {
2252 if let syn::Pat::Type(binding) = node {
2253 self.visit_type(&binding.ty);
2254 }
2255 }
2256 fn visit_type_macro(&mut self, _: &'ast syn::TypeMacro) {}
2257 fn visit_type_array(&mut self, node: &'ast syn::TypeArray) {
2258 self.visit_type(&node.elem);
2259 self.constant(&[], &node.len);
2260 }
2261 fn visit_const_param(&mut self, node: &'ast syn::ConstParam) {
2262 self.visit_type(&node.ty);
2263 if let Some(default) = &node.default {
2264 self.constant(&node.attrs, default);
2265 }
2266 }
2267 fn visit_generic_argument(&mut self, node: &'ast syn::GenericArgument) {
2268 match node {
2269 syn::GenericArgument::Const(value) => self.constant(&[], value),
2270 _ => visit::visit_generic_argument(self, node),
2271 }
2272 }
2273 fn visit_variant(&mut self, node: &'ast syn::Variant) {
2274 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2275 self.visit_fields(&node.fields);
2276 if let Some((_, value)) = &node.discriminant {
2277 self.constant(&[], value);
2278 }
2279 }
2280 }
2281 fn visit_file(&mut self, node: &'ast syn::File) {
2282 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2283 visit::visit_file(self, node);
2284 }
2285 }
2286 fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
2287 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2288 visit::visit_item_enum(self, node);
2289 }
2290 }
2291 fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
2292 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2293 visit::visit_item_struct(self, node);
2294 }
2295 }
2296 fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
2297 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2298 visit::visit_item_union(self, node);
2299 }
2300 }
2301 fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
2302 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2303 visit::visit_item_trait(self, node);
2304 }
2305 }
2306 fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
2307 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2308 visit::visit_item_type(self, node);
2309 }
2310 }
2311 fn visit_field(&mut self, node: &'ast syn::Field) {
2312 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2313 visit::visit_field(self, node);
2314 }
2315 }
2316 fn visit_impl_item_type(&mut self, node: &'ast syn::ImplItemType) {
2317 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2318 visit::visit_impl_item_type(self, node);
2319 }
2320 }
2321 fn visit_trait_item_type(&mut self, node: &'ast syn::TraitItemType) {
2322 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2323 visit::visit_trait_item_type(self, node);
2324 }
2325 }
2326 fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
2327 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
2328 }
2329 fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
2330 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
2331 }
2332 fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
2333 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
2334 }
2335 fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
2336 self.typed_constant(
2337 &node.attrs,
2338 &node.ty,
2339 node.default.as_ref().map(|(_, value)| value),
2340 );
2341 }
2342 fn visit_expr_const(&mut self, node: &'ast syn::ExprConst) {
2343 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2344 self.const_depth += 1;
2345 self.visit_block(&node.block);
2346 self.const_depth -= 1;
2347 }
2348 }
2349
2350 fn visit_macro(&mut self, node: &'ast syn::Macro) {
2351 let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
2352 return;
2353 };
2354 if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
2355 return;
2356 }
2357 if name == "matches" {
2358 let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
2360 let expr: syn::Expr = input.parse()?;
2361 input.parse::<proc_macro2::TokenStream>()?;
2362 Ok(expr)
2363 });
2364 if let Ok(expr) = scrutinee {
2365 self.visit_expr(&expr);
2366 }
2367 return;
2368 }
2369 type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
2370 if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
2373 for arg in &args {
2374 self.visit_expr(arg);
2377 }
2378 }
2379 }
2380
2381 fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
2382 self.visit_expr(&node.expr);
2383 self.constant(&node.attrs, &node.len);
2384 }
2385
2386 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
2387 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2389 if node.content.is_none() {
2390 let path = node.attrs.iter().find_map(|attr| match &attr.meta {
2391 syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
2392 syn::Expr::Lit(syn::ExprLit {
2393 lit: syn::Lit::Str(s),
2394 ..
2395 }) => Some(s.value()),
2396 _ => None,
2397 },
2398 _ => None,
2399 });
2400 self.found.test_modules.push(TestModule {
2401 name: node.ident.to_string(),
2402 path,
2403 });
2404 }
2405 return;
2406 }
2407 visit::visit_item_mod(self, node);
2408 }
2409
2410 fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
2411 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2412 let constant = node.sig.constness.is_some() as usize;
2414 self.const_depth += constant;
2415 self.function_sites(&node.sig, &node.block);
2416 visit::visit_item_fn(self, node);
2417 self.const_depth -= constant;
2418 }
2419 }
2420
2421 fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
2422 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2423 let constant = node.sig.constness.is_some() as usize;
2425 self.const_depth += constant;
2426 self.function_sites(&node.sig, &node.block);
2427 visit::visit_impl_item_fn(self, node);
2428 self.const_depth -= constant;
2429 }
2430 }
2431
2432 fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
2433 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2434 let constant = node.sig.constness.is_some() as usize;
2435 self.const_depth += constant;
2436 if let Some(body) = &node.default {
2437 self.function_sites(&node.sig, body);
2438 }
2439 visit::visit_trait_item_fn(self, node);
2440 self.const_depth -= constant;
2441 }
2442 }
2443
2444 fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
2445 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2446 visit::visit_item_impl(self, node);
2447 }
2448 }
2449
2450 fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
2451 if node.constness.is_none() {
2452 visit::visit_expr_closure(self, node);
2453 }
2454 }
2455
2456 fn visit_block(&mut self, node: &'ast syn::Block) {
2457 for stmt in &node.stmts {
2458 if let syn::Stmt::Expr(expr, Some(semi)) = stmt
2459 && deletable(expr)
2460 && let (Some((start, _)), Some((_, end))) =
2461 (self.range(expr.span()), self.range(semi.span()))
2462 && in_order(start, end)
2463 {
2464 self.push(SiteKind::Stmt, start, end, expr.span());
2465 }
2466 }
2467 visit::visit_block(self, node);
2468 }
2469
2470 fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
2471 let name = node.method.to_string();
2472 if (name == "max" || name == "min")
2473 && node.args.len() == 1
2474 && node.turbofish.is_none()
2475 && node.attrs.is_empty()
2476 && let (
2477 Some((start, receiver_end)),
2478 Some((argument_start, argument_end)),
2479 Some((_, end)),
2480 ) = (
2481 self.range(node.receiver.span()),
2482 self.range(node.args[0].span()),
2483 self.range(node.paren_token.span.close()),
2484 )
2485 && in_order(receiver_end, argument_start)
2486 && in_order(argument_end, end)
2487 {
2488 let kind = SiteKind::MinMax {
2489 max: name == "max",
2490 receiver: self.source[start..receiver_end].to_string(),
2491 argument: self.source[argument_start..argument_end].to_string(),
2492 call: (receiver_end, argument_start),
2493 close: (argument_end, end),
2494 };
2495 self.push(kind, start, end, node.receiver.span());
2496 }
2497 if (name == "first" || name == "last")
2498 && node.args.is_empty()
2499 && node.turbofish.is_none()
2500 && node.attrs.is_empty()
2501 && !(name == "last" && yields_iterator(&node.receiver))
2502 && let (Some((start, receiver_end)), Some(method), Some((_, end))) = (
2503 self.range(node.receiver.span()),
2504 self.range(node.method.span()),
2505 self.range(node.paren_token.span.close()),
2506 )
2507 && in_order(receiver_end, method.0)
2508 && in_order(method.1, end)
2509 {
2510 let kind = SiteKind::SliceEnd {
2511 first: name == "first",
2512 receiver: self.source[start..receiver_end].to_string(),
2513 call: (receiver_end, end),
2514 method,
2515 };
2516 self.push(kind, start, end, node.receiver.span());
2517 }
2518 visit::visit_expr_method_call(self, node);
2519 }
2520
2521 fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
2522 let mut over = &*node.expr;
2523 while let syn::Expr::Paren(syn::ExprParen { expr, .. })
2524 | syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
2525 {
2526 over = expr;
2527 }
2528 if let syn::Expr::Range(syn::ExprRange {
2529 start: Some(from), ..
2530 }) = over
2531 && let Some((start, _)) = self.range(from.span())
2532 {
2533 self.for_ranges.insert(start);
2534 }
2535 visit::visit_expr_for_loop(self, node);
2536 }
2537
2538 fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
2539 if let (Some(from), Some(to)) = (&node.start, &node.end)
2542 && node.attrs.is_empty()
2543 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2544 (self.range(from.span()), self.range(to.span()))
2545 && in_order(lhs_end, rhs_start)
2546 {
2547 let kind = SiteKind::Range {
2548 inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
2549 lhs: self.source[start..lhs_end].to_string(),
2550 rhs: self.source[rhs_start..end].to_string(),
2551 gap: (lhs_end, rhs_start),
2552 };
2553 let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
2560 self.const_depth += built as usize;
2561 self.push(kind, start, end, from.span());
2562 self.const_depth -= built as usize;
2563 }
2564 visit::visit_expr_range(self, node);
2565 }
2566
2567 fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
2568 let catches_all = |arm: &syn::Arm| {
2571 arm.guard.is_none()
2572 && match &arm.pat {
2573 syn::Pat::Wild(_) => true,
2574 syn::Pat::Ident(p) => {
2575 p.subpat.is_none()
2576 && p.ident
2577 .to_string()
2578 .starts_with(|c: char| c.is_lowercase() || c == '_')
2579 }
2580 _ => false,
2581 }
2582 };
2583 let mut removable = vec![];
2584 let has_wildcard = node
2585 .arms
2586 .iter()
2587 .any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
2588 let final_catches_all = node.arms.last().is_some_and(catches_all);
2589 for arm in &node.arms {
2590 if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
2591 continue;
2592 }
2593 let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
2595 let literal =
2596 has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
2597 if !probe && !literal {
2598 continue;
2599 }
2600 let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
2601 self.range(arm.pat.span()),
2602 self.range(arm.span()),
2603 self.range(arm.fat_arrow_token.span()),
2604 ) else {
2605 continue;
2606 };
2607 let guard = match &arm.guard {
2608 None => ArmGuard::None(arrow),
2609 Some((_, expr)) if written_bool(expr) == Some(false) => continue,
2611 Some((_, expr)) => match self.range(expr.span()) {
2612 Some((from, to)) => ArmGuard::Existing(from, to),
2613 None => continue,
2614 },
2615 };
2616 let pattern = match guard {
2617 ArmGuard::Existing(from, to) => format!(
2618 "{} if {}",
2619 &self.source[start..pat_end],
2620 &self.source[from..to]
2621 ),
2622 ArmGuard::None(_) => self.source[start..pat_end].to_string(),
2623 };
2624 let end = arm
2625 .comma
2626 .as_ref()
2627 .and_then(|comma| self.range(comma.span()))
2628 .map_or(remove_end, |(_, end)| end);
2629 let at = arm.pat.span().start();
2630 removable.push(start);
2631 let site = Site {
2632 id: 0,
2633 kind: SiteKind::Arm {
2634 pattern: pattern.clone(),
2635 guard,
2636 removal: (remove_start, end),
2637 },
2638 line: at.line,
2639 column: at.column + 1,
2640 start,
2641 end,
2642 text: format!("{pattern} => .."),
2643 };
2644 if probe {
2645 self.add(site);
2646 } else {
2647 self.add_rebuild(site);
2648 }
2649 }
2650 for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
2653 if let Some((_, guard)) = &arm.guard
2654 && !matches!(**guard, syn::Expr::Let(_))
2655 && !in_let_chain(guard)
2656 && let (Some((start, end)), Some((pattern, _))) =
2657 (self.range(guard.span()), self.range(arm.pat.span()))
2658 {
2659 let can_be_false = !removable.contains(&pattern);
2660 let kind = SiteKind::Guard { can_be_false };
2661 if written_bool(guard) == Some(true) && !can_be_false {
2662 } else if written_bool(guard).is_some() {
2664 let at = guard.span().start();
2668 self.add_rebuild(Site {
2669 id: 0,
2670 kind,
2671 line: at.line,
2672 column: at.column + 1,
2673 start,
2674 end,
2675 text: self.source[start..end].to_string(),
2676 });
2677 } else {
2678 self.push(kind, start, end, guard.span());
2679 }
2680 }
2681 }
2682 visit::visit_expr_match(self, node);
2683 }
2684
2685 fn visit_arm(&mut self, arm: &'ast syn::Arm) {
2686 if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
2687 visit::visit_arm(self, arm);
2688 }
2689 }
2690
2691 fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
2692 if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
2693 visit::visit_field_value(self, field);
2694 }
2695 }
2696
2697 fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2698 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2699 return;
2700 }
2701 let from_base = node.rest.as_deref().and_then(|base| {
2703 if !node.attrs.is_empty() || node.qself.is_some() {
2704 return None;
2705 }
2706 let (from, to) = self.range(base.span())?;
2707 let written = &self.source[from..to];
2708 match base {
2709 base if is_plain_place(base) => Some(format!("({written})")),
2710 syn::Expr::Call(call)
2711 if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
2712 {
2713 let (from, to) = self.range(node.path.span())?;
2714 Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
2715 }
2716 _ => None,
2717 }
2718 });
2719 if node.rest.is_some() {
2720 for pair in node.fields.pairs() {
2721 let field = pair.value();
2722 if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
2723 continue;
2724 }
2725 let name = match &field.member {
2726 syn::Member::Named(name) => name.to_string(),
2727 syn::Member::Unnamed(index) => index.index.to_string(),
2728 };
2729 let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
2730 self.range(field.member.span()),
2731 self.range(field.expr.span()),
2732 self.range(field.span()),
2733 ) else {
2734 continue;
2735 };
2736 let remove_end = pair
2737 .punct()
2738 .and_then(|comma| self.range(comma.span()))
2739 .map_or(end, |(_, end)| end);
2740 let from_base = from_base
2741 .as_ref()
2742 .filter(|_| field.attrs.is_empty())
2743 .map(|base| format!("{base}.{name}"));
2744 let probe = from_base.is_some();
2745 let kind = SiteKind::Field {
2746 from_base,
2747 name,
2748 shorthand: field.colon_token.is_none(),
2749 removal: (remove_start, remove_end),
2750 };
2751 let at = field.member.span().start();
2752 let site = Site {
2753 id: 0,
2754 kind,
2755 line: at.line,
2756 column: at.column + 1,
2757 start: if probe { value } else { remove_start },
2758 end,
2759 text: self.source[start..end].to_string(),
2760 };
2761 if probe {
2762 self.add(site);
2763 } else {
2764 self.add_rebuild(site);
2765 }
2766 }
2767 }
2768 visit::visit_expr_struct(self, node);
2769 }
2770
2771 fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
2772 if let syn::UnOp::Not(bang) = &node.op
2773 && node.attrs.is_empty()
2774 && let (Some((start, _)), Some((operand_start, end))) =
2775 (self.range(bang.span()), self.range(node.expr.span()))
2776 && in_order(start, operand_start)
2777 {
2778 let kind = SiteKind::Not {
2779 bang: (start, operand_start),
2780 operand: self.source[operand_start..end].to_string(),
2781 };
2782 self.push(kind, start, end, bang.span());
2783 }
2784 if let syn::UnOp::Neg(minus) = &node.op
2785 && node.attrs.is_empty()
2786 && let (Some((start, _)), Some((operand_start, end))) =
2787 (self.range(minus.span()), self.range(node.expr.span()))
2788 && in_order(start, operand_start)
2789 {
2790 let zero = match &*node.expr {
2791 syn::Expr::Lit(syn::ExprLit {
2792 lit: syn::Lit::Int(lit),
2793 ..
2794 }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
2795 _ => false,
2797 };
2798 if !zero {
2799 let kind = SiteKind::Neg {
2800 minus: (start, operand_start),
2801 operand: self.source[operand_start..end].to_string(),
2802 literal: matches!(*node.expr, syn::Expr::Lit(_)),
2803 };
2804 self.push(kind, start, end, minus.span());
2805 }
2806 }
2807 visit::visit_expr_unary(self, node);
2808 }
2809
2810 fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
2811 if let Some(op) = cmp_op(&node.op)
2812 && node.attrs.is_empty()
2813 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2814 (self.range(node.left.span()), self.range(node.right.span()))
2815 && in_order(lhs_end, rhs_start)
2816 {
2817 let literal = match (int_literal(&node.left), int_literal(&node.right)) {
2818 (None, Some(k)) => LiteralSide::Rhs(k),
2819 (Some(k), None) => LiteralSide::Lhs(k),
2820 _ => LiteralSide::None,
2821 };
2822 let kind = SiteKind::Cmp {
2823 op,
2824 lhs: self.source[start..lhs_end].to_string(),
2825 rhs: self.source[rhs_start..end].to_string(),
2826 literal,
2827 gap: (lhs_end, rhs_start),
2828 };
2829 self.push(kind, start, end, node.left.span());
2830 } else if node.attrs.is_empty()
2831 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2832 (self.range(node.left.span()), self.range(node.right.span()))
2833 && in_order(lhs_end, rhs_start)
2834 {
2835 let lhs = self.source[start..lhs_end].to_string();
2836 let rhs = self.source[rhs_start..end].to_string();
2837 let gap = (lhs_end, rhs_start);
2838 let logic = match &node.op {
2839 syn::BinOp::And(_) => Some(true),
2840 syn::BinOp::Or(_) => Some(false),
2841 _ => None,
2842 };
2843 if let Some(and) = logic {
2844 if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
2845 self.push(
2846 SiteKind::Logic { and, lhs, rhs, gap },
2847 start,
2848 end,
2849 node.left.span(),
2850 );
2851 }
2852 } else if let Some((op, assign)) = arith_op(&node.op) {
2853 let kind = SiteKind::Arith {
2854 op,
2855 assign,
2856 lhs,
2857 rhs,
2858 gap,
2859 };
2860 let literals = is_literal(&node.left) && is_literal(&node.right);
2863 if !literals && (!assign || is_plain_place(&node.left)) {
2864 self.push(kind, start, end, node.left.span());
2865 } else {
2866 let at = node.left.span().start();
2869 self.found.rebuild_sites.push(Site {
2870 id: NO_ID,
2871 kind,
2872 line: at.line,
2873 column: at.column + 1,
2874 start,
2875 end,
2876 text: self.source[start..end].to_string(),
2877 });
2878 }
2879 }
2880 }
2881 visit::visit_expr_binary(self, node);
2882 }
2883}
2884
2885#[derive(Debug, PartialEq)]
2888pub struct Rendered {
2889 pub text: String,
2890 segments: Vec<(usize, usize, usize)>,
2893 inserted: Vec<(usize, usize, u32)>,
2895}
2896
2897impl Rendered {
2898 pub fn copied(&self, from: usize, to: usize) -> Option<(usize, usize)> {
2901 self.segments
2902 .iter()
2903 .find(|(_, start, len)| *start <= from && to <= start + len)
2904 .map(|(out, start, _)| (out + from - start, out + to - start))
2905 }
2906
2907 pub fn inserted_by(&self, offset: usize) -> Option<u32> {
2911 let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
2912 let (out, len, site) = self.inserted[idx.checked_sub(1)?];
2913 (offset - out < len).then_some(site)
2914 }
2915
2916 pub fn to_original(&self, offset: usize) -> usize {
2917 let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
2918 let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
2919 return 0;
2920 };
2921 orig + (offset - out).min(len)
2923 }
2924}
2925
2926struct Edit {
2927 pos: usize,
2928 end: usize,
2929 phase: u8,
2931 order: i64,
2933 text: String,
2934 site: u32,
2936}
2937
2938pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
2940 let rt = format!("crate::{RUNTIME_MOD}");
2941 let mut edits = vec![];
2942 for site in sites.iter().filter(|s| enabled(s.id)) {
2943 let wraps = matches!(
2947 site.kind,
2948 SiteKind::Return { .. }
2949 | SiteKind::Body { .. }
2950 | SiteKind::Guard { .. }
2951 | SiteKind::Field { .. }
2952 );
2953 let len = 2 * (site.end - site.start) as i64 + wraps as i64;
2955 let (open, close) = match &site.kind {
2956 SiteKind::Cmp { op, gap, .. } => {
2957 let func = if op.is_ordering() { "ord" } else { "eq" };
2958 edits.push(Edit {
2959 pos: gap.0,
2960 end: gap.1,
2961 phase: 1,
2962 order: 0,
2963 text: "), &(".into(),
2964 site: site.id,
2965 });
2966 (
2967 "(match (&(".to_string(),
2968 format!(
2969 ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
2970 {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
2971 id = site.id,
2972 code = op.code(),
2973 ),
2974 )
2975 }
2976 SiteKind::Logic { and, gap, .. } => {
2981 let id = site.id;
2984 edits.push(Edit {
2985 pos: gap.0,
2986 end: gap.1,
2987 phase: 1,
2988 order: 0,
2989 text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
2990 site: site.id,
2991 });
2992 (
2993 format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
2996 "), __tmt_c => __tmt_c == 1u8 })".to_string(),
2997 )
2998 }
2999 SiteKind::Arith {
3000 op, assign, gap, ..
3001 } => {
3002 let (holder, lhs_open, lhs_close) = if *assign {
3004 ("Aa", "&mut (", ")")
3005 } else {
3006 ("Ar", "", "")
3007 };
3008 edits.push(Edit {
3009 pos: gap.0,
3010 end: gap.1,
3011 phase: 1,
3012 order: 0,
3013 text: format!("{lhs_close}, "),
3014 site: site.id,
3015 });
3016 (
3017 format!("(match ({lhs_open}"),
3018 format!(
3019 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
3020 (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
3021 any = op.fallback_trait(*assign),
3022 prim = op.prim_trait(*assign),
3023 method = op.method(*assign),
3024 id = site.id,
3025 ),
3026 )
3027 }
3028 SiteKind::Not { bang, .. } => {
3029 edits.push(Edit {
3031 pos: bang.0,
3032 end: bang.1,
3033 phase: 1,
3034 order: 0,
3035 text: String::new(),
3036 site: site.id,
3037 });
3038 (
3039 "(match (".to_string(),
3040 format!(
3041 ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
3042 (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
3043 site.id
3044 ),
3045 )
3046 }
3047 SiteKind::Return { option, .. } => match option {
3048 None => (
3049 " let __tmt_v: bool = {".to_string(),
3050 format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
3051 ),
3052 Some(ty) => (
3053 format!(" let __tmt_v: {ty} = {{"),
3054 format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
3055 ),
3056 },
3057 SiteKind::MinMax {
3058 max, call, close, ..
3059 } => {
3060 edits.push(Edit {
3064 pos: call.0,
3065 end: call.1,
3066 phase: 1,
3067 order: 0,
3068 text: "), ".into(),
3069 site: site.id,
3070 });
3071 let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
3075 edits.push(Edit {
3076 pos: close.0,
3077 end: close.1,
3078 phase: 1,
3079 order: 0,
3080 text: format!(
3081 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
3082 if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
3083 site.id
3084 ),
3085 site: site.id,
3086 });
3087 ("(match (&(".to_string(), String::new())
3088 }
3089 SiteKind::SliceEnd {
3090 first,
3091 receiver,
3092 call,
3093 ..
3094 } => {
3095 let (same, other) = if *first {
3099 ("first", "last")
3100 } else {
3101 ("last", "first")
3102 };
3103 let id = site.id;
3104 let decide = format!(
3105 "#[allow(unused_imports)] use {rt}::{{AnyEnd as _, SliceEnd as _}}; \
3106 match (&{rt}::Ends(__TMT_BORROWED__)).tmt_other_end({id}u32, {first}) {{ \
3107 {rt}::End::Other => {{ let __tmt_o = (__TMT_PLACE__).{other}(); \
3108 if false {{ {rt}::same_type(&__tmt_o, &(__TMT_PLACE__).{same}()); }} __tmt_o }}, \
3109 {rt}::End::Same(__tmt_s) => {{ \
3110 let __tmt_r = (__TMT_PLACE__).{same}(); \
3111 __tmt_s.tmt_end_seen({id}u32, &__tmt_r); __tmt_r }} }}"
3112 );
3113 let (open, close) = if let Some(name) = variable_name(receiver) {
3118 let seen = if name == "__tmt_s" {
3120 "__tmt_t"
3121 } else {
3122 "__tmt_s"
3123 };
3124 let decide = decide
3125 .replace("__tmt_s", seen)
3126 .replace("__TMT_PLACE__", &name);
3127 let (head, tail) = decide
3128 .split_once("__TMT_BORROWED__")
3129 .expect("the receiver is borrowed once");
3130 (format!("({{ {head}&("), format!("){tail} }})"))
3131 } else {
3132 let decide = decide
3133 .replace("__TMT_BORROWED__", "__tmt_a")
3134 .replace("__TMT_PLACE__", "*__tmt_a");
3135 (
3136 "(match (&(".to_string(),
3137 format!(")) {{ __tmt_a => {{ {decide} }} }})"),
3138 )
3139 };
3140 edits.push(Edit {
3141 pos: call.0,
3142 end: call.1,
3143 phase: 1,
3144 order: 0,
3145 text: close,
3146 site: site.id,
3147 });
3148 (open, String::new())
3149 }
3150 SiteKind::Range { inclusive, gap, .. } => {
3151 edits.push(Edit {
3152 pos: gap.0,
3153 end: gap.1,
3154 phase: 1,
3155 order: 0,
3156 text: ", ".into(),
3157 site: site.id,
3158 });
3159 let method = if *inclusive {
3160 "tmt_range_inclusive"
3161 } else {
3162 "tmt_range"
3163 };
3164 (
3165 "(match (".to_string(),
3166 format!(
3167 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
3168 (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
3169 site.id
3170 ),
3171 )
3172 }
3173 SiteKind::Arm { guard, .. } => {
3174 match guard {
3177 ArmGuard::None(arrow) => edits.push(Edit {
3178 pos: *arrow,
3179 end: *arrow,
3180 phase: 2,
3181 order: 0,
3182 text: format!("if {rt}::arm({}u32) ", site.id),
3183 site: site.id,
3184 }),
3185 ArmGuard::Existing(from, to) => {
3186 let wider = 2 * (to - from + 1) as i64;
3187 edits.push(Edit {
3188 pos: *from,
3189 end: *from,
3190 phase: 2,
3191 order: -wider,
3192 text: format!("{rt}::arm({}u32) && (", site.id),
3193 site: site.id,
3194 });
3195 edits.push(Edit {
3196 pos: *to,
3197 end: *to,
3198 phase: 0,
3199 order: wider,
3200 text: ")".into(),
3201 site: site.id,
3202 });
3203 }
3204 }
3205 (String::new(), String::new())
3206 }
3207 SiteKind::Stmt => (
3208 format!("if {rt}::live({}u32) {{ ", site.id),
3209 " }".to_string(),
3210 ),
3211 SiteKind::Neg {
3213 operand,
3214 literal: true,
3215 ..
3216 } => (
3217 format!("(if {rt}::live({}u32) {{ ", site.id),
3218 format!(" }} else {{ {operand} }})"),
3219 ),
3220 SiteKind::Neg { minus, .. } => {
3221 edits.push(Edit {
3222 pos: minus.0,
3223 end: minus.1,
3224 phase: 1,
3225 order: 0,
3226 text: String::new(),
3227 site: site.id,
3228 });
3229 (
3230 "(match (".to_string(),
3231 format!(
3232 ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
3233 site.id
3234 ),
3235 )
3236 }
3237 SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
3238 SiteKind::Field {
3239 name,
3240 shorthand,
3241 from_base: Some(from_base),
3242 ..
3243 } => (
3244 format!(
3245 "{}if {rt}::live({}u32) {{ ",
3246 if *shorthand {
3247 format!("{name}: ")
3248 } else {
3249 String::new()
3250 },
3251 site.id
3252 ),
3253 format!(" }} else {{ {from_base} }}"),
3254 ),
3255 SiteKind::Field {
3256 from_base: None, ..
3257 } => continue,
3258 SiteKind::Body { value, .. } => (
3259 format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
3260 String::new(),
3261 ),
3262 };
3263 edits.push(Edit {
3264 pos: site.start,
3265 end: site.start,
3266 phase: 2,
3267 order: -len,
3268 text: open,
3269 site: site.id,
3270 });
3271 edits.push(Edit {
3272 pos: site.end,
3273 end: site.end,
3274 phase: 0,
3275 order: len,
3276 text: close,
3277 site: site.id,
3278 });
3279 }
3280 edits.sort_by_key(|e| (e.pos, e.phase, e.order));
3281
3282 let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
3284 let mut text = String::with_capacity(capacity);
3285 let mut segments = vec![];
3286 let mut inserted = vec![];
3287 let mut cursor = 0;
3288 for edit in edits {
3289 if edit.pos >= cursor {
3292 segments.push((text.len(), cursor, edit.pos - cursor));
3293 text.push_str(&source[cursor..edit.pos]);
3294 }
3295 let replaced = &source[cursor.max(edit.pos)..cursor.max(edit.end)];
3298 let lines = "\n".repeat(replaced.matches('\n').count());
3299 inserted.push((text.len(), edit.text.len() + lines.len(), edit.site));
3300 text.push_str(&edit.text);
3301 text.push_str(&lines);
3302 cursor = cursor.max(edit.end);
3303 }
3304 segments.push((text.len(), cursor, source.len() - cursor));
3305 text.push_str(&source[cursor..]);
3306 Rendered {
3307 text,
3308 segments,
3309 inserted,
3310 }
3311}
3312
3313pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
3316 let containing = || {
3319 sites.iter().filter(|s| {
3320 enabled(s.id)
3321 && s.start <= offset
3322 && offset <= s.end
3323 && !matches!(s.kind, SiteKind::Body { .. })
3324 })
3325 };
3326 let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
3327 return vec![];
3328 };
3329 containing()
3330 .filter(|s| s.end - s.start == smallest)
3331 .map(|s| s.id)
3332 .collect()
3333}
3334
3335#[cfg(test)]
3336mod tests {
3337 use super::*;
3338
3339 #[test]
3340 fn what_an_expression_can_be_is_read_from_its_last_operation() {
3341 use crate::plan::Reach;
3342 for (expr, expected) in [
3343 ("blocks * 8", Some(Reach::Multiples(8))),
3344 ("8 * blocks", Some(Reach::Multiples(8))),
3345 ("(blocks * (2))", Some(Reach::Multiples(2))),
3346 ("blocks << 3", Some(Reach::Multiples(8))),
3347 ("blocks << 9", Some(Reach::Multiples(512))),
3348 ("flags & 0xF0", Some(Reach::Bits(0xF0))),
3349 ("0b1010u8 & flags", Some(Reach::Bits(0b1010))),
3350 ("n % 10", Some(Reach::Below(10))),
3351 ("(a + b) % 7_u32", Some(Reach::Below(7))),
3352 ("cents * 10", None),
3354 ("blocks * 1", None),
3355 ("blocks * 0", None),
3356 ("a * b", None),
3357 ("3 << blocks", None),
3358 ("blocks << 0", None),
3359 ("blocks << 200", None),
3360 ("10 % n", None),
3361 ("n % 0", None),
3362 ("blocks * 8 + 1", None),
3363 ("(blocks * 8) as u8", None),
3364 ("-(blocks * 8)", None),
3365 ("blocks", None),
3366 ("flags | 0xF0", None),
3367 ("blocks / 8", None),
3368 ("x * 8.0", None),
3369 ("not rust (", None),
3370 ] {
3371 assert_eq!(reach(expr).map(|(reach, _)| reach), expected, "{expr}");
3372 assert_eq!(
3374 reach(expr).and_then(|(_, bits)| bits).is_some(),
3375 expr.contains("<<") && expected.is_some(),
3376 "{expr}"
3377 );
3378 }
3379 }
3380
3381 #[test]
3382 fn code_of_the_tests_is_told_from_the_rest() {
3383 let source = r#"
3384 pub fn open(n: u32) -> bool { n > 1 }
3385 #[test]
3386 fn at_the_top() { assert!(open(2)); }
3387 #[cfg(test)]
3388 mod tests { fn helper() -> u32 { 3 } }
3389 mod plain {
3390 pub fn inside(n: u32) -> bool { n > 4 }
3391 #[cfg(test)]
3392 fn only_tested() -> u32 { 5 }
3393 }
3394 struct S;
3395 impl S {
3396 fn method(&self) -> u32 { 6 }
3397 #[cfg(test)]
3398 fn test_method(&self) -> u32 { 7 }
3399 }
3400 #[cfg(not(test))]
3401 fn never_in_tests() -> u32 { 8 }
3402 "#;
3403 let file = parse_source(source).unwrap();
3404 let ranges = test_only_ranges(source, &file);
3405 let of_tests = |text: &str| {
3406 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
3407 ranges.iter().any(|(from, to)| *from <= at && at < *to)
3408 };
3409 for text in ["open(2)", "{ 3 }", "{ 5 }", "{ 7 }", "fn at_the_top"] {
3410 assert!(of_tests(text), "{text}");
3411 }
3412 for text in ["n > 1", "n > 4", "{ 6 }", "{ 8 }", "struct S", "mod plain"] {
3413 assert!(!of_tests(text), "{text}");
3414 }
3415 let whole = "#![cfg(test)]\nfn f() {}\n";
3416 let file = parse_source(whole).unwrap();
3417 assert_eq!(test_only_ranges(whole, &file), [(0, whole.len())]);
3418 }
3419
3420 #[test]
3421 fn comments_documentation_and_spacing_are_not_program_text() {
3422 let code = "/// Says.\n#[inline]\nfn f(a: u8) -> u8 {\n a + 1 // one more\n}\n";
3423 for same in [
3424 "#[inline] fn f(a:u8)->u8{a+1}",
3425 "/// Says something else.\n#[inline]\nfn f(a: u8) -> u8 { /* why */ a + 1 }",
3426 "#[doc = \"other\"] #[inline] fn f(a: u8) -> u8 { a + 1 }",
3427 ] {
3428 assert_eq!(same_tokens(code, same), Some(true), "{same}");
3429 }
3430 for other in [
3431 "#[inline] fn f(a: u8) -> u8 { a + 2 }",
3432 "fn f(a: u8) -> u8 { a + 1 }",
3433 "#[inline] fn f(a: u8) -> u8 { (a + 1) }",
3434 "#[inline] fn f(a: u8) -> u8 { a + 1 } fn g() {}",
3435 "#![inline] fn f(a: u8) -> u8 { a + 1 }",
3436 "#[inline] fn f(a: u8) -> u8 { [a + 1][0] }",
3437 ] {
3438 assert_eq!(same_tokens(code, other), Some(false), "{other}");
3439 }
3440 assert_eq!(
3441 same_tokens("#![doc = \"a\"] fn f() {}", "fn f() {}"),
3442 Some(true)
3443 );
3444 for (one, other) in [
3446 (r#"m!(#[doc = "old"]);"#, r#"m!(#[doc = "new"]);"#),
3447 (
3448 r#"const T: &str = stringify!(#[doc = "old"]);"#,
3449 r#"const T: &str = stringify!(#[doc = "new"]);"#,
3450 ),
3451 (
3452 "macro_rules! m { (#[doc = \"old\"]) => {1}; }",
3453 "macro_rules! m { (#[doc = \"new\"]) => {1}; }",
3454 ),
3455 (
3456 "std::vec![#[doc = \"old\"] 1]",
3457 "std::vec![#[doc = \"new\"] 1]",
3458 ),
3459 ] {
3460 assert_eq!(same_tokens(one, other), Some(false), "{one}");
3461 assert_eq!(same_tokens(one, one), Some(true), "{one}");
3462 }
3463 for (one, other) in [
3465 ("m! { /// old\n fn f() {} }", "m! { /// new\n fn f() {} }"),
3466 (
3467 "bitflags! { /** old */ struct F: u8 { /// a\n const A = 1; } }",
3468 "bitflags! { /** new */ struct F: u8 { /// b\n const A = 1; } }",
3469 ),
3470 (
3471 "macro_rules! m { () => { /// old\n fn f() {} }; }",
3472 "macro_rules! m { () => { /// new\n fn f() {} }; }",
3473 ),
3474 ] {
3475 assert_eq!(same_tokens(one, other), Some(true), "{one}");
3476 }
3477 assert_eq!(
3479 same_tokens(
3480 "fn f(a: bool) -> bool { !{ /** a */ a } }",
3481 "fn f(a: bool) -> bool { !{ /** b */ a } }"
3482 ),
3483 Some(true)
3484 );
3485 assert_eq!(
3486 same_tokens("m!(1); /// a\nfn f() {}", "m!(1); /// b\nfn f() {}"),
3487 Some(true)
3488 );
3489 for (one, other) in [
3491 ("enum E { A, B }", "enum E { A, B, }"),
3492 ("struct S(pub u8);", "struct S(pub u8,);"),
3493 (
3494 "fn f(a: u8) { g(a,); s.h(a,) }",
3495 "fn f(a: u8,) { g(a); s.h(a) }",
3496 ),
3497 ("const A: [u8; 2] = [1, 2];", "const A: [u8; 2] = [1, 2,];"),
3498 ("type Hook = fn(u8);", "type Hook = fn(u8,);"),
3499 (
3501 "fn f(s: &S, t: &[fn(u8)]) { (s.callback)(1); t[0](2) }",
3502 "fn f(s: &S, t: &[fn(u8)]) { (s.callback)(1,); t[0](2,) }",
3503 ),
3504 (
3505 "fn f(n: u8) -> u8 { match n { 1 => 2, _ => 0 } }",
3506 "fn f(n: u8) -> u8 { match n { 1 => 2, _ => 0, } }",
3507 ),
3508 ] {
3509 assert_eq!(same_tokens(one, other), Some(true), "{one}");
3510 }
3511 for (one, other) in [
3512 ("const T: (u8,) = (1,);", "const T: (u8) = (1);"),
3513 (
3516 "fn f() { let (x,) = (1u8,); }",
3517 "fn f() { let (x) = (1u8,); }",
3518 ),
3519 (
3520 "fn f() -> (u8,) { return (1,) }",
3521 "fn f() -> (u8,) { return (1) }",
3522 ),
3523 (
3524 "fn f() { let t = (Ok::<u8, u8>(1),); }",
3525 "fn f() { let t = (Ok::<u8, u8>(1)); }",
3526 ),
3527 (
3528 "fn f(a: (u8,), b: u8) -> bool { a > (b,) }",
3529 "fn f(a: (u8,), b: u8) -> bool { a > (b) }",
3530 ),
3531 (
3532 "fn f(x: u8) { for (a,) in [(x,)] {} }",
3533 "fn f(x: u8) { for (a) in [(x,)] {} }",
3534 ),
3535 (
3537 "fn f() -> impl Sized { #[allow(unused_parens)] (2u8,) }",
3538 "fn f() -> impl Sized { #[allow(unused_parens)] (2u8) }",
3539 ),
3540 ("fn f<'a>(x: &'a (u8,)) {}", "fn f<'a>(x: &'a (u8)) {}"),
3542 (
3543 "fn f() { let v = 'outer: loop { break 'outer (1u8,); }; }",
3544 "fn f() { let v = 'outer: loop { break 'outer (1u8); }; }",
3545 ),
3546 ("m!(a, b);", "m!(a, b,);"),
3547 ("enum E { A, B }", "enum E { A, B, C }"),
3548 ("fn f() { g(1, 2) }", "fn f() { g(1,, 2) }"),
3549 ] {
3550 assert_eq!(same_tokens(one, other), Some(false), "{one}");
3551 }
3552 assert_eq!(
3555 same_tokens(
3556 &format!("const A: [u8; 2] = [1, {LEFT_OUT}];"),
3557 "const A: [u8; 1] = [1];"
3558 ),
3559 Some(false)
3560 );
3561 let same_tokens = same_built_tokens;
3562 assert_eq!(
3565 same_tokens(
3566 &format!("fn f() -> impl Sized {{ {LEFT_OUT} (1u8,) }}"),
3567 &format!("fn f() -> impl Sized {{ {LEFT_OUT} (1u8) }}")
3568 ),
3569 Some(false)
3570 );
3571 let hole = LEFT_OUT;
3573 for with in [
3574 format!("enum E {{ A, {hole}, B }}"),
3575 format!("enum E {{ A, B, {hole}, }}"),
3576 format!("enum E {{ A, B, {hole} }}"),
3577 format!("enum E {{ {hole}, A, B }}"),
3578 format!("enum E {{ A, {hole} /* note */ , B, }}"),
3579 format!("{hole} enum E {{ A, B }}"),
3580 ] {
3581 assert_eq!(same_tokens(&with, "enum E { A, B }"), Some(true), "{with}");
3582 }
3583 assert_eq!(
3586 same_tokens(
3587 &format!("const T: (u8, u8) = (1, {hole});"),
3588 "const T: (u8, u8) = (1);"
3589 ),
3590 Some(true)
3591 );
3592 assert_eq!(
3594 same_tokens(
3595 &format!("fn f(n: u8) -> u8 {{ match n {{ 0 => 1, {hole} _ => 0, }} }}"),
3596 "fn f(n: u8) -> u8 { match n { 0 => 1, _ => 0 } }"
3597 ),
3598 Some(true)
3599 );
3600 assert_eq!(
3601 same_tokens(&format!("enum E {{ A, {hole}, B }}"), "enum E { A }"),
3602 Some(false)
3603 );
3604 assert_eq!(
3607 same_tokens(
3608 &format!("fn f() {{ a(); {hole}; b() }}"),
3609 "fn f() { a(); b() }"
3610 ),
3611 Some(true)
3612 );
3613 assert_eq!(
3614 same_tokens(&format!("struct S(pub u8, {hole},);"), "struct S(pub u8);"),
3615 Some(true)
3616 );
3617 assert_eq!(same_tokens(code, "fn f( {"), None);
3618 assert_eq!(same_tokens("fn f( {", code), None);
3619 }
3620
3621 #[test]
3622 fn a_cfg_is_decided_only_as_far_as_the_features_decide_it() {
3623 let on: BTreeSet<String> = ["basic".to_string()].into();
3624 for (predicate, expected) in [
3625 (r#"feature = "basic""#, Some(true)),
3626 (r#"feature = "extra""#, Some(false)),
3627 (r#"not(feature = "extra")"#, Some(true)),
3628 (r#"not(feature = "basic")"#, Some(false)),
3629 ("test", None),
3630 (r#"target_os = "linux""#, None),
3631 ("not(test)", None),
3632 ("all()", Some(true)),
3633 ("any()", Some(false)),
3634 (r#"all(feature = "basic", feature = "extra")"#, Some(false)),
3635 (r#"all(test, feature = "extra")"#, Some(false)),
3636 (r#"all(feature = "extra", test)"#, Some(false)),
3637 (r#"all(test, feature = "basic")"#, None),
3638 (
3639 r#"all(feature = "basic", not(feature = "extra"))"#,
3640 Some(true),
3641 ),
3642 (r#"any(feature = "basic", feature = "extra")"#, Some(true)),
3643 (r#"any(test, feature = "basic")"#, Some(true)),
3644 (r#"any(feature = "basic", test)"#, Some(true)),
3645 (r#"any(test, feature = "extra")"#, None),
3646 (r#"any(feature = "extra", feature = "more")"#, Some(false)),
3647 (r#"not(any(test, feature = "basic"))"#, Some(false)),
3648 (r#"not(test, feature = "basic")"#, None),
3649 ("feature = 3", None),
3650 (r#"unknown(feature = "extra")"#, None),
3651 ("all(=)", None),
3652 ] {
3653 let meta: syn::Meta = syn::parse_str(predicate).unwrap();
3654 assert_eq!(cfg_value(&meta, &on), expected, "{predicate}");
3655 }
3656 }
3657
3658 #[test]
3659 fn code_under_a_feature_that_is_off_is_not_in_the_build() {
3660 let source = r#"
3661 #[cfg(feature = "extra")]
3662 pub fn item(n: u32) -> bool { n > 1 }
3663 #[cfg(feature = "basic")]
3664 pub fn kept(n: u32) -> bool { n > 2 }
3665 #[cfg(test)]
3666 fn only_tests(n: u32) -> bool { n > 3 }
3667 #[cfg(feature = "extra")]
3668 mod module { pub fn inside(n: u32) -> bool { n > 4 } }
3669 struct S;
3670 impl S {
3671 #[cfg(feature = "extra")]
3672 fn method(&self, n: u32) -> bool { n > 5 }
3673 fn open(&self, n: u32) -> bool { n > 6 }
3674 }
3675 trait T {
3676 #[cfg(feature = "extra")]
3677 fn provided(&self, n: u32) -> bool { n > 7 }
3678 }
3679 #[cfg(feature = "extra")]
3680 impl T for S {}
3681 fn body(n: u32) -> u32 {
3682 #[cfg(feature = "extra")]
3683 let n = n + 8;
3684 #[cfg(feature = "extra")]
3685 { return n + 9; }
3686 #[cfg(feature = "extra")]
3687 if n > 10 { return 0; }
3688 #[cfg(feature = "extra")]
3689 assert!(n > 11);
3690 match n {
3691 #[cfg(feature = "extra")]
3692 12 => 0,
3693 _ => n + 13,
3694 }
3695 }
3696 #[cfg(not(feature = "extra"))]
3697 mod kept_module {
3698 #[cfg(feature = "extra")]
3699 const OFF: u32 = 14 + 1;
3700 const ON: u32 = 15 + 1;
3701 }
3702 "#;
3703 let file = parse_source(source).unwrap();
3704 let on: BTreeSet<String> = ["basic".to_string()].into();
3705 let ranges = inactive_ranges(source, &file, &on);
3706 let left_out = |text: &str| {
3707 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
3708 ranges.iter().any(|(from, to)| *from <= at && at < *to)
3709 };
3710 for off in [
3711 "n > 1 ", "n > 4", "n > 5", "n > 7", "n + 8", "n + 9", "n > 10", "n > 11", "12 =>",
3712 "14 + 1",
3713 ] {
3714 assert!(left_out(off), "{off}");
3715 }
3716 let listed = r#"
3718 pub const FORMATS: &[&str] = &["json", #[cfg(feature = "extra")] "yaml", #[cfg(feature = "basic")] "toml"];
3719 fn f() -> u8 { g(1, #[cfg(feature = "extra")] 2) }
3720 fn v(n: u8) -> Vec<bool> { std::vec![false, #[cfg(feature = "extra")] (n > 0)] }
3721 unsafe extern "C" { #[cfg(feature = "extra")] fn legacy(); fn kept(); }
3722 "#;
3723 let listed_file = parse_source(listed).unwrap();
3724 let listed_ranges = inactive_ranges(listed, &listed_file, &on);
3725 let texts: Vec<&str> = listed_ranges
3726 .iter()
3727 .map(|(from, to)| &listed[*from..*to])
3728 .collect();
3729 assert_eq!(
3730 texts,
3731 [
3732 "#[cfg(feature = \"extra\")] \"yaml\"",
3733 "#[cfg(feature = \"extra\")] 2",
3734 "#[cfg(feature = \"extra\")] (n > 0)",
3735 "#[cfg(feature = \"extra\")] fn legacy();"
3736 ]
3737 );
3738 let own = r#"
3741 mod m {
3742 macro_rules! vec { (#[$attr:meta] $value:expr) => { $value }; }
3743 pub fn value() -> u8 { vec![#[cfg(feature = "extra")] 1] }
3744 }
3745 "#;
3746 assert_eq!(inactive_ranges(own, &parse_source(own).unwrap(), &on), []);
3747 let shapes = r#"
3749 pub enum Format { Json, #[cfg(feature = "extra")] Yaml, #[cfg(feature = "basic")] Toml }
3750 pub struct Options { pub depth: u8, #[cfg(feature = "extra")] pub strict: bool }
3751 "#;
3752 let shapes_file = parse_source(shapes).unwrap();
3753 let shape_ranges = inactive_ranges(shapes, &shapes_file, &on);
3754 let texts: Vec<&str> = shape_ranges
3755 .iter()
3756 .map(|(from, to)| &shapes[*from..*to])
3757 .collect();
3758 assert_eq!(
3759 texts,
3760 [
3761 "#[cfg(feature = \"extra\")] Yaml",
3762 "#[cfg(feature = \"extra\")] pub strict: bool"
3763 ]
3764 );
3765 for on in ["n > 2", "n > 3", "n > 6", "n + 13", "15 + 1", "struct S"] {
3766 assert!(!left_out(on), "{on}");
3767 }
3768 let both: BTreeSet<String> = ["basic".to_string(), "extra".to_string()].into();
3771 let with_extra = inactive_ranges(source, &file, &both);
3772 assert_eq!(with_extra.len(), 1, "{with_extra:?}");
3773 assert!(source[with_extra[0].0..with_extra[0].1].starts_with("#[cfg(not(feature"));
3774 let whole = "#![cfg(feature = \"extra\")]\nfn f() {}\n";
3775 let file = parse_source(whole).unwrap();
3776 assert_eq!(inactive_ranges(whole, &file, &on), [(0, whole.len())]);
3777 }
3778
3779 fn all(_: u32) -> bool {
3780 true
3781 }
3782
3783 fn found(src: &str, first_id: u32) -> Result<Discovery> {
3786 let mut all = discover(src, 0)?;
3787 all.sites
3788 .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
3789 for (index, site) in all.sites.iter_mut().enumerate() {
3790 site.id = first_id + index as u32;
3791 }
3792 Ok(all)
3793 }
3794
3795 #[test]
3796 fn finds_a_comparison_with_a_literal() {
3797 let src = "pub fn is_eligible(age: u32) -> bool {\n age >= 18\n}\n";
3798 let found = found(src, 5).unwrap();
3799 assert_eq!(found.sites.len(), 1);
3800 let site = &found.sites[0];
3801 assert_eq!(
3802 (site.id, site.line, site.column, site.text.as_str()),
3803 (5, 2, 5, "age >= 18")
3804 );
3805 let SiteKind::Cmp {
3806 op,
3807 lhs,
3808 rhs,
3809 literal,
3810 ..
3811 } = &site.kind
3812 else {
3813 panic!()
3814 };
3815 assert_eq!(
3816 (*op, lhs.as_str(), rhs.as_str(), *literal),
3817 (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
3818 );
3819 }
3820
3821 #[test]
3822 fn literal_sides() {
3823 let src =
3824 "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
3825 let literals: Vec<LiteralSide> = found(src, 0)
3826 .unwrap()
3827 .sites
3828 .iter()
3829 .filter_map(|s| match &s.kind {
3830 SiteKind::Cmp { literal, .. } => Some(*literal),
3831 SiteKind::Neg { .. } => None,
3832 _ => panic!(),
3833 })
3834 .collect();
3835 assert_eq!(
3836 literals,
3837 [
3838 LiteralSide::Lhs(-5),
3839 LiteralSide::Rhs(3),
3840 LiteralSide::None,
3841 LiteralSide::None,
3842 LiteralSide::None
3843 ]
3844 );
3845 }
3846
3847 #[test]
3848 fn renders_a_comparison_probe() {
3849 let src = "fn f(a: u8) -> bool { a >= 18 }";
3850 let sites = found(src, 3).unwrap().sites;
3851 let out = render(src, &sites, &all);
3852 assert_eq!(
3853 out.text,
3854 "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
3855 use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
3856 (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
3857 );
3858 assert_eq!(render(src, &sites, &|_| false).text, src);
3859 }
3860
3861 #[test]
3862 fn renders_statement_guards_and_nested_sites() {
3863 let src = "fn f(v: &mut Vec<u8>, a: u8) -> Result<(), ()> {\n check((a < 3) == true)?;\n v.push(a);v.clear();\n Ok(())\n}";
3864 let sites = found(src, 0).unwrap().sites;
3865 let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3866 assert_eq!(
3867 kinds,
3868 [
3869 "check((a < 3) == true)?;",
3870 "v.push(a);",
3871 "v.clear();",
3872 "(a < 3) == true",
3873 "a < 3"
3874 ]
3875 );
3876 let out = render(src, &sites, &all);
3877 assert_eq!(
3878 out.text.lines().count(),
3879 src.lines().count(),
3880 "line numbers are preserved"
3881 );
3882 assert!(
3883 out.text
3884 .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
3885 "{}",
3886 out.text
3887 );
3888 assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
3889 syn::parse_file(&out.text).expect("instrumented source parses");
3890
3891 let inner = render(src, &sites, &|id| id == 4);
3893 assert!(
3894 inner.text.contains("check(((match (&(a), &(3))"),
3895 "{}",
3896 inner.text
3897 );
3898 assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
3899 syn::parse_file(&inner.text).unwrap();
3900 }
3901
3902 #[test]
3903 fn skips_tests_const_contexts_and_macros() {
3904 let src = r#"
3905 const LIMIT: bool = 1 < 2;
3906 static S: bool = 3 > 2;
3907 const fn c(a: u8) -> bool { a < 1 }
3908 fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
3909 enum E { A = (5 > 4) as isize }
3910 struct T;
3911 impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
3912 #[cfg(test)]
3913 mod tests { fn t(a: u8) -> bool { a == 1 } }
3914 #[cfg(test)]
3915 mod more_tests;
3916 #[cfg(test)]
3917 #[doc = "not a path"]
3918 mod documented;
3919 #[cfg(test)]
3920 #[path = "support/helpers.rs"]
3921 mod helpers;
3922 #[cfg(all(test, feature = "x"))]
3923 fn helper(a: u8) -> bool { a != 1 }
3924 #[test]
3925 fn a_test() { let a = 1; if a == 2 { panic!() } }
3926 #[tokio::test]
3927 async fn async_test() { let a = 1; if a == 3 { panic!() } }
3928 #[cfg(not(test))]
3929 fn real(a: u8) -> bool { a == 100 }
3930 #[cfg(feature = "test-utils")]
3931 fn also_real(a: u8) -> bool { a == 101 }
3932 fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
3933 "#;
3934 let found = found(src, 0).unwrap();
3935 let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
3936 assert_eq!(
3937 texts,
3938 [
3939 "a == 100",
3940 "a == 101",
3941 "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
3942 "0..=9 => ..",
3943 "a == 102"
3944 ]
3945 );
3946 assert_eq!(
3947 found.test_modules,
3948 [
3949 TestModule {
3950 name: "more_tests".into(),
3951 path: None
3952 },
3953 TestModule {
3954 name: "documented".into(),
3955 path: None
3956 },
3957 TestModule {
3958 name: "helpers".into(),
3959 path: Some("support/helpers.rs".into())
3960 },
3961 ]
3962 );
3963 }
3964
3965 #[test]
3966 fn deletable_statements() {
3967 let src = r#"
3968 async fn f(s: &mut S) -> Result<(), E> {
3969 s.validate()?;
3970 s.total += 1;
3971 s.flag = true;
3972 helper(s);
3973 s.flush().await?;
3974 s.sync().await;
3975 let x = s.get();
3976 println!("{x}");
3977 if x > 0 { return Ok(()); }
3978 s.done()
3979 }
3980 "#;
3981 let texts: Vec<String> = found(src, 0)
3982 .unwrap()
3983 .sites
3984 .into_iter()
3985 .filter(|s| s.kind == SiteKind::Stmt)
3986 .map(|s| s.text)
3987 .collect();
3988 assert_eq!(
3989 texts,
3990 [
3991 "s.validate()?;",
3992 "s.total += 1;",
3993 "s.flag = true;",
3994 "helper(s);",
3995 "s.flush().await?;",
3996 "s.sync().await;"
3997 ]
3998 );
3999 }
4000
4001 #[test]
4002 fn maps_offsets_back_and_blames_the_innermost_site() {
4003 let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
4004 let sites = found(src, 0).unwrap().sites;
4005 let out = render(src, &sites, &all);
4006 for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
4008 let hits: Vec<usize> = out
4009 .text
4010 .char_indices()
4011 .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
4012 .map(|(o, _)| o)
4013 .collect();
4014 assert!(
4015 !hits.is_empty(),
4016 "original offset {orig} ({ch}) is unreachable"
4017 );
4018 }
4019 let probe = out.text.find("ord(1u32").unwrap();
4021 let orig = out.to_original(probe);
4022 assert_eq!(blame(&sites, &all, orig), [1]);
4023 assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
4025 assert_eq!(
4026 blame(&sites, &all, src.find("fn").unwrap()),
4027 Vec::<u32>::new()
4028 );
4029 assert_eq!(out.to_original(0), 0);
4030 assert_eq!(out.to_original(out.text.len()), src.len());
4031 }
4032
4033 #[test]
4034 fn blame_is_inclusive_at_both_ends() {
4035 let src = "fn f(a: u8) -> bool { a > 1 }";
4036 let sites = found(src, 0).unwrap().sites;
4037 let (start, end) = (sites[0].start, sites[0].end);
4038 assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
4039 assert_eq!(blame(&sites, &all, start), [0]);
4040 assert_eq!(blame(&sites, &all, end), [0]);
4041 assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
4042 let out = render(src, &sites, &all);
4044 assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
4045 assert_eq!(
4046 out.to_original(out.text.find("tmt_val()) } })").unwrap()),
4047 end
4048 );
4049 assert_eq!(
4050 out.to_original(out.text.find("), &(").unwrap() + 2),
4051 sites[0].start + 1
4052 );
4053 }
4054
4055 #[test]
4056 fn finds_sites_in_impls_and_array_elements() {
4057 let src = r#"
4058 struct T(u8);
4059 impl T { fn small(&self) -> bool { self.0 < 3 } }
4060 #[cfg(test)]
4061 impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
4062 trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
4063 fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
4064 fn closure(a: u8) -> bool { (|| a < 7)() }
4065 "#;
4066 let texts: Vec<String> = found(src, 0)
4067 .unwrap()
4068 .sites
4069 .into_iter()
4070 .map(|s| s.text)
4071 .collect();
4072 assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
4073 }
4074
4075 #[test]
4076 fn logic_and_arithmetic_sites() {
4077 let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
4078 let found = found(src, 0).unwrap().sites;
4079 let kinds: Vec<String> = found
4080 .iter()
4081 .map(|s| match &s.kind {
4082 SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
4083 SiteKind::Arith { op, lhs, rhs, .. } => {
4084 format!("arith {} [{lhs}] [{rhs}]", op.symbol())
4085 }
4086 SiteKind::Not { operand, .. } => format!("not [{operand}]"),
4087 other => format!("{other:?}"),
4088 })
4089 .collect();
4090 assert_eq!(
4091 kinds,
4092 [
4093 "logic and=false [a && b] [!a]",
4094 "logic and=true [a] [b]",
4095 "not [a]",
4096 "arith + [x] [y * 2]",
4097 "arith * [y] [2]",
4098 "arith - [x] [1 % y]",
4099 "arith % [1] [y]",
4100 ]
4101 );
4102 let out = render(src, &found, &all).text;
4103 syn::parse_file(&out).expect("instrumented source parses");
4104 assert!(
4105 out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(1u32, true, a); __tmt_c } { 2u8 => crate::__tmt_rt::rhs(1u32, true, b), __tmt_c => __tmt_c == 1u8 })"),
4106 "{out}"
4107 );
4108 assert!(
4109 out.contains("(match (y, 2) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyMul as _, ArithPrim as _}; (&crate::__tmt_rt::Ar::new(__tmt_a, __tmt_b)).tmt_mul(4u32) } })"),
4110 "{out}"
4111 );
4112 for op in ArithOp::ALL {
4114 assert_ne!(op.swapped(), op);
4115 for assign in [false, true] {
4116 let method = op.method(assign);
4117 let fallback = format!("{} {method} ", op.fallback_trait(assign));
4118 assert!(
4119 crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
4120 "{method}"
4121 );
4122 assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
4123 assert!(
4124 crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
4125 "{op:?}"
4126 );
4127 }
4128 }
4129 }
4130
4131 #[test]
4132 fn let_chains_and_literal_arithmetic_are_left_alone() {
4133 let src = r#"
4134 fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
4135 if let Some(x) = o && a && x > 1 { return 1; }
4136 let k = 60 * 60;
4137 (n & 3) | (n << 1) ^ k
4138 }
4139 "#;
4140 let texts: Vec<String> = found(src, 0)
4141 .unwrap()
4142 .sites
4143 .into_iter()
4144 .map(|s| s.text)
4145 .collect();
4146 assert_eq!(
4147 texts,
4148 [
4149 "x > 1",
4150 "(n & 3) | (n << 1) ^ k",
4151 "n & 3",
4152 "(n << 1) ^ k",
4153 "n << 1"
4154 ]
4155 );
4156 }
4157
4158 #[test]
4159 fn attributes_const_methods_and_let_on_the_right() {
4160 let src = r#"
4161 struct T(u8);
4162 impl T {
4163 const fn in_const(&self) -> bool { self.0 < 1 }
4164 #[test]
4165 fn test_method(&self) -> bool { self.0 < 2 }
4166 fn real(&self) -> bool { self.0 < 3 }
4167 }
4168 trait Tr {
4169 #[cfg(test)]
4170 fn only_in_tests(&self, a: u8) -> bool { a < 4 }
4171 }
4172 fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
4173 #[cfg(feature = "x")]
4174 s.guarded();
4175 #[allow(unused)]
4176 s.total += 1;
4177 #[allow(unused)]
4178 s.check()?;
4179 #[allow(unused)]
4180 s.sync().await;
4181 s.plain();
4182 if a && let Some(v) = o { s.use_it(v); }
4183 Ok(())
4184 }
4185 "#;
4186 let texts: Vec<String> = found(src, 0)
4187 .unwrap()
4188 .sites
4189 .into_iter()
4190 .map(|s| s.text)
4191 .collect();
4192 assert_eq!(
4195 texts,
4196 [
4197 "self.0 < 3",
4198 "#[allow(unused)]\n s.total += 1;",
4199 "s.plain();",
4200 "#[allow(unused)]\n s.total += 1",
4201 "s.use_it(v);"
4202 ]
4203 );
4204 let found = found(src, 0).unwrap().sites;
4205 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
4206 }
4207
4208 #[test]
4209 fn compound_assignment_negation_and_bit_operators() {
4210 let src = "fn f(total: &mut u32, n: u32, ok: bool, m: Mask) -> u32 { *total += n; *total <<= 1; if !ok { return !n; } let _ = !m; n & 7 }";
4211 let sites = found(src, 0).unwrap().sites;
4212 let kinds: Vec<String> = sites
4213 .iter()
4214 .map(|s| match &s.kind {
4215 SiteKind::Arith {
4216 op,
4217 assign,
4218 lhs,
4219 rhs,
4220 ..
4221 } => format!(
4222 "{lhs} {}{} {rhs}",
4223 op.symbol(),
4224 if *assign { "=" } else { "" }
4225 ),
4226 SiteKind::Not { operand, .. } => format!("!{operand}"),
4227 SiteKind::Stmt => "stmt".to_string(),
4228 other => format!("{other:?}"),
4229 })
4230 .collect();
4231 assert_eq!(
4232 kinds,
4233 [
4234 "stmt",
4235 "stmt",
4236 "*total += n",
4237 "*total <<= 1",
4238 "!ok",
4239 "!n",
4240 "!m",
4241 "n & 7"
4242 ]
4243 );
4244 let out = render(src, &sites, &all).text;
4245 syn::parse_file(&out).expect("instrumented source parses");
4246 for expected in [
4247 "(match (&mut (*total), n) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyAddAssign as _, ArithAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_add_assign(2u32) } });",
4248 "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
4249 "if (match (ok) { __tmt_a => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyNot as _, NotPrim as _}; (&crate::__tmt_rt::Un::new(__tmt_a)).tmt_not(4u32) } }) {",
4250 "(match (n, 7) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyBitAnd as _, BitPrim as _}; (&crate::__tmt_rt::Ar::new(__tmt_a, __tmt_b)).tmt_bitand(7u32) } })",
4251 ] {
4252 assert!(out.contains(expected), "missing {expected}\nin {out}");
4253 }
4254 let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
4256 let sites = found(nested, 0).unwrap().sites;
4257 let out = render(nested, &sites, &all).text;
4258 syn::parse_file(&out).expect("instrumented source parses");
4259 assert!(
4260 out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
4261 "{out}"
4262 );
4263 let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
4265 let sites = found(capture, 0).unwrap().sites;
4266 let out = render(capture, &sites, &all).text;
4267 syn::parse_file(&out).expect("instrumented source parses");
4268 for arm in out.split("__tmt_c => ").skip(1) {
4270 assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
4271 }
4272 for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
4273 assert!(
4274 arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
4275 "{arm}"
4276 );
4277 }
4278 }
4279
4280 #[test]
4281 fn compound_assignment_is_probed_only_on_plain_places() {
4282 let src = r#"
4283 fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
4284 let mut local = 0u32;
4285 local += 1;
4286 s.count += 1;
4287 s.inner.total -= 2;
4288 *p *= 3;
4289 (*p) += 4;
4290 v[i] += 5;
4291 v[next()] += 6;
4292 s.get_mut().x += 7;
4293 *s.slot() += 8;
4294 }
4295 "#;
4296 let probed: Vec<String> = found(src, 0)
4297 .unwrap()
4298 .sites
4299 .into_iter()
4300 .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
4301 .map(|s| s.text)
4302 .collect();
4303 assert_eq!(
4304 probed,
4305 [
4306 "local += 1",
4307 "s.count += 1",
4308 "s.inner.total -= 2",
4309 "*p *= 3",
4310 "(*p) += 4"
4311 ]
4312 );
4313 let deletable = found(src, 0)
4315 .unwrap()
4316 .sites
4317 .iter()
4318 .filter(|s| s.kind == SiteKind::Stmt)
4319 .count();
4320 assert_eq!(deletable, 9);
4321 }
4322
4323 #[test]
4324 fn bool_functions_are_return_sites() {
4325 let src = r#"
4326 pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
4327 fn count(a: u8) -> u8 { a }
4328 fn unit(a: u8) { let _ = a; }
4329 const fn in_const(a: u8) -> bool { a > 2 }
4330 #[test]
4331 fn a_test() -> bool { true }
4332 struct T;
4333 impl T { fn method(&self) -> bool { true } }
4334 trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
4335 fn boxed() -> Box<bool> { Box::new(true) }
4336 fn qualified() -> core::primitive::bool { true }
4337 "#;
4338 let sites = discover(src, 0).unwrap().sites;
4339 let returns: Vec<(&str, &str, usize)> = sites
4340 .iter()
4341 .filter_map(|s| match &s.kind {
4342 SiteKind::Return {
4343 name, option: None, ..
4344 } => Some((name.as_str(), s.text.as_str(), s.line)),
4345 _ => None,
4346 })
4347 .collect();
4348 assert_eq!(
4349 returns,
4350 [
4351 ("is_ok", "fn is_ok(a: u8) -> bool", 2),
4352 ("method", "fn method(&self) -> bool", 9),
4353 ("provided", "fn provided(&self) -> bool", 10),
4354 ]
4355 );
4356 let out = render(src, &sites, &all).text;
4357 syn::parse_file(&out).expect("instrumented source parses");
4358 assert!(
4359 out.contains(
4360 "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
4361 if !crate::__tmt_rt::live(1u32) { return true; } \
4362 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
4363 ),
4364 "{out}"
4365 );
4366 assert!(
4367 out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
4368 "{out}"
4369 );
4370 assert_eq!(
4371 out.lines().count(),
4372 src.lines().count(),
4373 "line numbers are preserved"
4374 );
4375 let rendered = render(src, &sites, &all);
4377 let wrapper = rendered.text.find("ret(0u32").unwrap();
4378 assert_eq!(rendered.inserted_by(wrapper), Some(0));
4379 let replaced = rendered.text.find("return false; } let b").unwrap();
4382 assert_eq!(rendered.inserted_by(replaced), Some(2));
4383 assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
4384 }
4385
4386 #[test]
4387 fn ids_are_consecutive_across_every_kind_of_site() {
4388 let src = r#"
4389 fn a(x: u8) -> bool { x > 1 }
4390 fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
4391 fn c(s: &mut S) { s.n += 1; s.go(); }
4392 "#;
4393 let sites = discover(src, 10).unwrap().sites;
4394 let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
4395 assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
4396 let texts: Vec<&str> = sites
4397 .iter()
4398 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
4399 .map(|s| s.text.as_str())
4400 .collect();
4401 assert_eq!(
4402 texts,
4403 [
4404 "fn a(x: u8) -> bool",
4405 "x > 1",
4406 "fn b(x: u8) -> bool",
4407 "!(x > 2) && !!flag(x)",
4408 "!(x > 2)",
4409 "x > 2",
4410 "!!flag(x)",
4411 "!flag(x)",
4412 "s.n += 1;",
4413 "s.go();",
4414 "s.n += 1",
4415 ]
4416 );
4417 syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
4418 }
4419
4420 #[test]
4421 fn only_calls_and_assignments_are_deletable() {
4422 let src = r#"
4423 async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
4424 s.field;
4425 v[0];
4426 (s.a, s.b);
4427 s.value?;
4428 s.future.await;
4429 s.x = 1;
4430 s.x -= 1;
4431 s.x == 1;
4432 s.call().await?;
4433 Ok(())
4434 }
4435 "#;
4436 let texts: Vec<String> = found(src, 0)
4437 .unwrap()
4438 .sites
4439 .into_iter()
4440 .filter(|s| s.kind == SiteKind::Stmt)
4441 .map(|s| s.text)
4442 .collect();
4443 assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
4444 }
4445
4446 #[test]
4447 fn ranges_match_arms_min_max_and_option_results() {
4448 let src = r#"
4449 fn find(v: &[u32], limit: u32) -> Option<u32> {
4450 for i in 0..v.len() {
4451 let capped = v[i].min(limit).max(1);
4452 match capped {
4453 0 => return None,
4454 n if n > 5 => return Some(n),
4455 1..=3 => continue,
4456 other => { let _ = other; }
4457 }
4458 }
4459 let _ = &v[1..=2];
4460 for _ in 1..=limit as usize {}
4461 let _ = 'a'..'z';
4462 let _ = v.iter().max();
4463 None
4464 }
4465 fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
4466 fn hidden() -> Option<impl Sized> { Some(1) }
4467 fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
4468 "#;
4469 let sites = discover(src, 0).unwrap().sites;
4470 let kinds: Vec<String> = sites
4471 .iter()
4472 .filter_map(|s| match &s.kind {
4473 SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
4474 SiteKind::Range {
4475 inclusive,
4476 lhs,
4477 rhs,
4478 ..
4479 } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
4480 SiteKind::Arm { pattern, guard, .. } => Some(format!(
4481 "arm {pattern} guarded={}",
4482 matches!(guard, ArmGuard::Existing(..))
4483 )),
4484 SiteKind::MinMax {
4485 max,
4486 receiver,
4487 argument,
4488 ..
4489 } => Some(format!("minmax {receiver} {argument} max={max}")),
4490 _ => None,
4491 })
4492 .collect();
4493 assert_eq!(
4494 kinds,
4495 [
4496 "range 0 v.len() inclusive=false",
4497 "minmax v[i].min(limit) 1 max=true",
4498 "minmax v[i] limit max=false",
4499 "arm 0 guarded=false",
4501 "arm n if n > 5 guarded=true",
4502 "arm 1..=3 guarded=false",
4503 "range 1 limit as usize inclusive=true",
4505 "return first Some(\"Option<u32>\")",
4506 ]
4507 );
4508 let out = render(src, &sites, &all).text;
4509 syn::parse_file(&out).expect("instrumented source parses");
4510 assert_eq!(out.lines().count(), src.lines().count());
4511 let option = sites
4512 .iter()
4513 .find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
4514 .unwrap();
4515 assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
4516 assert!(
4517 out.contains(&format!(
4518 "crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
4519 option.id
4520 )),
4521 "{out}"
4522 );
4523 assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
4524 assert!(
4525 out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
4526 "{out}"
4527 );
4528 assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
4529 assert!(
4530 out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
4531 "{out}"
4532 );
4533 assert!(
4536 out.contains("(match (&(v[i]), limit) {")
4537 && out.contains(
4538 "Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
4539 )
4540 && out.contains(
4541 ".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
4542 ),
4543 "{out}"
4544 );
4545 assert!(
4546 !out.contains(".min(limit)") && !out.contains(".max(1)"),
4547 "{out}"
4548 );
4549 assert!(
4550 out.contains("v.iter().max()"),
4551 "an iterator's max is another method: {out}"
4552 );
4553 }
4554
4555 #[test]
4556 fn macro_arguments() {
4557 let src = r#"
4558 fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
4559 assert!(a < 100);
4560 debug_assert!(a < 101, "message {}", a < 102);
4561 assert_eq!(a < 1, b < 2, "context {}", a + 3);
4562 let _ = format!("{} {name}", a < 4, name = b < 5);
4563 write!(out, "{}", a < 6).unwrap();
4564 if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
4565 custom!(a < 10);
4566 let _ = vec![a < 11; 2];
4567 vec![a + b, (a < 12) as u32]
4568 }
4569 "#;
4570 let texts: Vec<String> = found(src, 0)
4571 .unwrap()
4572 .sites
4573 .into_iter()
4574 .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
4575 .map(|s| s.text)
4576 .collect();
4577 assert_eq!(
4578 texts,
4579 [
4580 "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
4581 "a < 12"
4582 ]
4583 );
4584 let found = found(src, 0).unwrap().sites;
4585 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
4586 }
4587
4588 #[test]
4589 fn non_ascii_source_keeps_byte_offsets() {
4590 let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
4591 let sites = found(src, 0).unwrap().sites;
4592 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
4593 assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
4594 syn::parse_file(&render(src, &sites, &all).text).unwrap();
4595 }
4596
4597 #[test]
4598 fn unparseable_source_is_an_error() {
4599 assert!(discover("fn f( {", 0).is_err());
4600 }
4601 fn labelled(src: &str) -> Vec<String> {
4603 discover(src, 0)
4604 .unwrap()
4605 .sites
4606 .iter()
4607 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
4608 .map(|s| {
4609 let kind = match &s.kind {
4610 SiteKind::Cmp { .. } => "cmp",
4611 SiteKind::Logic { .. } => "logic",
4612 SiteKind::Arith { .. } => "arith",
4613 SiteKind::Not { .. } => "not",
4614 SiteKind::Return { .. } => "return",
4615 SiteKind::MinMax { .. } => "minmax",
4616 SiteKind::SliceEnd { .. } => "end",
4617 SiteKind::Range { .. } => "range",
4618 SiteKind::Arm { .. } => "arm",
4619 SiteKind::Stmt => "stmt",
4620 SiteKind::Neg { .. } => "neg",
4621 SiteKind::Guard { .. } => "guard",
4622 SiteKind::Field { .. } => "field",
4623 SiteKind::Body { .. } => "body",
4624 };
4625 format!("{kind} {}", s.text)
4626 })
4627 .collect()
4628 }
4629
4630 #[test]
4631 fn byte_order_mark_and_interpreter_line_are_refused() {
4632 let body = "fn f(a: u8) -> bool { a > 1 }";
4633 assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
4634 assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
4635 assert_eq!(
4637 labelled(&format!("#![allow(dead_code)]\n{body}")),
4638 ["return fn f(a: u8) -> bool", "cmp a > 1"]
4639 );
4640 }
4641
4642 #[test]
4643 fn which_result_types_make_a_return_site() {
4644 let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
4645 fn b() -> Option { g() }\n\
4646 fn c() -> Vec<u8> { g() }\n\
4647 fn d() -> std::option::Option<u8> { g() }\n\
4648 fn e() -> <S>::bool { g() }\n\
4649 fn e2() -> <S as Tr>::bool { g() }\n\
4650 fn one(a: u8) -> bool { a > 1 }\n\
4651 fn two(a: u8) -> bool { let b = a; b > 1 }\n\
4652 fn early(a: u8) -> bool { return a > 1; }\n";
4653 let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
4654 .unwrap()
4655 .sites
4656 .into_iter()
4657 .filter_map(|s| match s.kind {
4658 SiteKind::Return {
4659 name,
4660 option,
4661 sole_expr,
4662 } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
4663 _ => None,
4664 })
4665 .collect();
4666 assert_eq!(
4667 returns,
4668 [
4669 (
4670 "d".to_string(),
4671 Some("std::option::Option<u8>".to_string()),
4672 Some("g()")
4673 ),
4674 ("one".to_string(), None, Some("a > 1")),
4676 ("two".to_string(), None, None),
4677 ]
4678 );
4679 }
4680
4681 #[test]
4682 fn places_chains_attributes_and_shadowed_macros() {
4683 assert_eq!(
4687 labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
4688 [
4689 "stmt #[allow(unused)] x += 1;",
4690 "stmt (x) += 2;",
4691 "arith (x) += 2"
4692 ]
4693 );
4694 assert_eq!(
4696 labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
4697 ["cmp a > 1", "stmt g(b);"]
4698 );
4699 assert_eq!(
4701 labelled(
4702 "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
4703 ),
4704 ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
4705 );
4706 assert_eq!(
4708 labelled(
4709 "macro_rules! vec { ($($t:tt)*) => {} }\n\
4710 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
4711 ),
4712 ["cmp a > 2"]
4713 );
4714 assert_eq!(
4715 labelled(
4716 "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
4717 ),
4718 ["return fn g(a: u8) -> bool", "cmp a > 2"]
4719 );
4720 }
4721
4722 #[test]
4723 fn first_and_last_of_what_may_be_a_slice() {
4724 assert_eq!(
4725 labelled(
4726 "fn f(v: &[u8], s: &S) { let _ = v.first(); let _ = s.items.last(); \
4727 let _ = s.all().last(); let _ = (v).first().copied(); }"
4728 ),
4729 [
4730 "end v.first()",
4731 "end s.items.last()",
4732 "end s.all().last()",
4733 "end (v).first()"
4734 ]
4735 );
4736 assert_eq!(
4739 labelled(
4740 "fn f(v: &[u8], t: &T) { let _ = t.first(1); let _ = t.last::<u8>(); \
4741 let _ = #[allow(unused)] v.last(); let _ = v.iter().last(); \
4742 let _ = (v.iter().map(g)).last(); let _ = t.name.split('/').last(); \
4743 let _ = v.first_mut(); }"
4744 ),
4745 [] as [&str; 0]
4746 );
4747 let src = "fn f(v: &[u8]) -> Option<&u8> { v.last() }";
4748 let found = discover(src, 0).unwrap();
4749 let out = render(src, &found.sites, &|_| true).text;
4750 assert!(out.contains("({ #[allow(unused_imports)] use"), "{out}");
4752 assert!(
4753 out.contains("match (&crate::__tmt_rt::Ends(&(v))).tmt_other_end("),
4754 "{out}"
4755 );
4756 assert_eq!(out.matches("(v)").count(), 4, "{out}");
4757 assert!(out.contains(", false) {"), "{out}");
4758 assert!(
4759 out.contains("End::Other => { let __tmt_o = (v).first(); if false { crate::__tmt_rt::same_type(&__tmt_o, &(v).last()); } __tmt_o }, crate::__tmt_rt::End::Same(__tmt_s) => { let __tmt_r = (v).last(); __tmt_s.tmt_end_seen("),
4760 "{out}"
4761 );
4762 let src = "fn f(s: &S) -> Option<&u8> { s.all()\n .first() }";
4764 let found = discover(src, 0).unwrap();
4765 let out = render(src, &found.sites, &|_| true).text;
4766 assert!(out.contains("(match (&(s.all())) { __tmt_a =>"), "{out}");
4767 assert!(
4768 out.contains("End::Other => { let __tmt_o = (*__tmt_a).last();"),
4769 "{out}"
4770 );
4771 assert!(out.contains("let __tmt_r = (*__tmt_a).first();"), "{out}");
4772 assert!(out.contains("__tmt_r } } } })\n }"), "{out}");
4773 assert_eq!(out.matches('\n').count(), 1, "{out}");
4774 let src = "fn f(v: &[u8]) -> Option<&u8> { v.last() }";
4775 let found = discover(src, 0).unwrap();
4776 let mutants: Vec<_> = found.sites.iter().flat_map(source_mutants).collect();
4778 let end = mutants.iter().find(|m| m.what == "last").unwrap();
4779 assert_eq!(
4780 (
4781 &src[end.start..end.end],
4782 end.replacement.as_str(),
4783 end.into.as_str()
4784 ),
4785 ("last", "first", "first")
4786 );
4787 }
4788
4789 #[test]
4790 fn min_max_and_ranges_that_are_left_alone() {
4791 assert_eq!(
4792 labelled(
4793 "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
4794 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
4795 ),
4796 ["minmax a.max(b)"]
4797 );
4798 let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
4800 for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
4801 assert_eq!(
4802 labelled(src),
4803 [
4804 "range a..10",
4805 "range 1..b",
4806 "range (a + 1)..(b * 2)",
4807 "arith a + 1",
4808 "arith b * 2",
4809 "neg -6"
4811 ]
4812 );
4813 let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
4814 assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
4816 assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
4817 assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
4818 }
4819
4820 #[test]
4821 fn which_arms_can_be_removed() {
4822 let src = "fn f(k: u8) -> u8 {\n\
4823 \x20 let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
4824 \x20 let b = match k { 1 => 1, NONE => 0 };\n\
4825 \x20 let c = match k { 1 => 1, n @ 0..=9 => n };\n\
4826 \x20 let d = match k {\n\
4827 \x20 1 => 1,\n\
4828 \x20 _ => 0,\n\
4829 \x20 };\n\
4830 \x20 a + b + c + d\n\
4831 }\n";
4832 let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
4833 .unwrap()
4834 .sites
4835 .into_iter()
4836 .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
4837 .map(|s| (s.id, s.line, s.column, s.text))
4838 .collect();
4839 assert_eq!(
4842 arms,
4843 [
4844 (9, 2, 23, "1 => ..".to_string()),
4846 (10, 2, 39, "2 => ..".to_string()),
4847 (11, 6, 9, "1 => ..".to_string()),
4848 ]
4849 );
4850 }
4851
4852 #[test]
4853 fn offsets_around_inserted_text() {
4854 let src = "fn f(a: u8) -> bool { a > 1 }";
4855 let sites = found(src, 0).unwrap().sites;
4856 let out = render(src, &sites, &all);
4857 let start = sites[0].start;
4858 let copied_a = out.text.find("a), &(").unwrap();
4861 assert_eq!(out.to_original(copied_a), start);
4862 assert_eq!(out.to_original(copied_a - 1), start);
4863 assert_eq!(out.to_original(copied_a + 1), start + 1);
4864 assert_eq!(out.to_original(out.text.len() + 10), src.len());
4866
4867 let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
4870 let sites = discover(src, 0).unwrap().sites;
4871 let out = render(src, &sites, &all);
4872 let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
4873 assert!(
4874 out.text[inner_probe..].starts_with("(match (b, 1)"),
4875 "{}",
4876 out.text
4877 );
4878 assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
4879 let arith = sites
4880 .iter()
4881 .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
4882 .unwrap();
4883 assert_eq!(
4884 blame(&sites, &all, out.to_original(inner_probe)),
4885 [arith.id]
4886 );
4887 assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
4889 assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
4890 let opening = "(match (b, ";
4892 let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
4893 assert!(out.text[inner_probe..].starts_with(opening));
4894 assert_eq!(out.inserted_by(first), Some(arith.id));
4895 assert_eq!(out.inserted_by(last), Some(arith.id));
4896 assert_eq!(out.inserted_by(last + 1), None);
4897 assert_eq!(out.inserted_by(0), None);
4898 }
4899 fn values(ty: &str) -> Vec<String> {
4900 let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
4901 .unwrap_or_else(|e| panic!("{ty}: {e}"));
4902 body_values(&function.sig.output)
4903 }
4904
4905 #[test]
4907 fn replacement_values_by_return_type() {
4908 let rows: &[(&str, &[&str])] = &[
4909 ("()", &["()"]),
4910 ("i8", &["0", "1", "-1"]),
4911 ("isize", &["0", "1", "-1"]),
4912 ("i128", &["0", "1", "-1"]),
4913 ("u8", &["0", "1"]),
4914 ("usize", &["0", "1"]),
4915 ("u128", &["0", "1"]),
4916 ("f32", &["0.0", "1.0", "-1.0"]),
4917 ("f64", &["0.0", "1.0", "-1.0"]),
4918 ("bool", &["true", "false"]),
4919 (
4920 "NonZeroI32",
4921 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4922 ),
4923 ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
4924 ("NonZero<u64>", &["1.try_into().unwrap()"]),
4925 (
4926 "NonZero<i64>",
4927 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4928 ),
4929 ("String", &["String::new()", "\"xyzzy\".into()"]),
4930 ("&str", &["\"\"", "\"xyzzy\""]),
4931 ("&'static str", &["\"\"", "\"xyzzy\""]),
4932 ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
4934 ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
4935 (
4936 "&mut bool",
4937 &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
4938 ),
4939 (
4940 "&[u8]",
4941 &[
4942 "Vec::leak(Vec::new())",
4943 "Vec::leak(vec![0])",
4944 "Vec::leak(vec![1])",
4945 ],
4946 ),
4947 (
4948 "&mut [bool]",
4949 &[
4950 "Vec::leak(Vec::new())",
4951 "Vec::leak(vec![true])",
4952 "Vec::leak(vec![false])",
4953 ],
4954 ),
4955 ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
4956 ("io::Result<()>", &["Ok(())"]),
4957 ("fmt::Result", &["Ok(Default::default())"]),
4959 ("Result", &["Ok(Default::default())"]),
4960 ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
4961 ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
4962 ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
4963 (
4964 "std::rc::Rc<u8>",
4965 &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
4966 ),
4967 ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
4968 ("RefCell<()>", &["RefCell::new(())"]),
4969 ("Mutex<()>", &["Mutex::new(())"]),
4970 ("Cell<()>", &["Cell::new(())"]),
4971 (
4972 "HashSet<u8>",
4973 &[
4974 "HashSet::new()",
4975 "HashSet::from_iter([0])",
4976 "HashSet::from_iter([1])",
4977 ],
4978 ),
4979 (
4980 "BTreeSet<()>",
4981 &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
4982 ),
4983 (
4984 "BinaryHeap<()>",
4985 &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
4986 ),
4987 (
4988 "LinkedList<()>",
4989 &["LinkedList::new()", "LinkedList::from_iter([()])"],
4990 ),
4991 (
4992 "VecDeque<()>",
4993 &["VecDeque::new()", "VecDeque::from_iter([()])"],
4994 ),
4995 (
4996 "HashMap<bool, u8>",
4997 &[
4998 "HashMap::new()",
4999 "HashMap::from_iter([(true, 0)])",
5000 "HashMap::from_iter([(true, 1)])",
5001 "HashMap::from_iter([(false, 0)])",
5002 "HashMap::from_iter([(false, 1)])",
5003 ],
5004 ),
5005 (
5006 "std::collections::BTreeMap<(), ()>",
5007 &[
5008 "std::collections::BTreeMap::new()",
5009 "std::collections::BTreeMap::from_iter([((), ())])",
5010 ],
5011 ),
5012 (
5013 "Cow<'a, str>",
5014 &[
5015 "Cow::Borrowed(\"\")",
5016 "Cow::Owned(\"\".to_owned())",
5017 "Cow::Borrowed(\"xyzzy\")",
5018 "Cow::Owned(\"xyzzy\".to_owned())",
5019 ],
5020 ),
5021 ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
5022 ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
5023 (
5024 "(u8, bool)",
5025 &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
5026 ),
5027 ("(bool,)", &["(true,)", "(false,)"]),
5028 ("HttpResponse", &["HttpResponse::Ok().finish()"]),
5029 (
5030 "actix_web::HttpResponse",
5031 &["actix_web::HttpResponse::Ok().finish()"],
5032 ),
5033 ("Config", &["Default::default()"]),
5034 ("Self", &["Default::default()"]),
5035 ("<T as Tr>::Out", &["Default::default()"]),
5036 ("<T as Tr>::String", &["Default::default()"]),
5038 ("<T>::bool", &["Default::default()"]),
5039 ("fn(u8) -> u8", &["Default::default()"]),
5040 ("*const u8", &["Default::default()"]),
5041 (
5043 "Result<Option<String>, E>",
5044 &[
5045 "Ok(None)",
5046 "Ok(Some(String::new()))",
5047 "Ok(Some(\"xyzzy\".into()))",
5048 ],
5049 ),
5050 ("(Vec<()>)", &["vec![]", "vec![()]"]),
5051 ("Option<Config>", &["None", "Some(Default::default())"]),
5052 ("!", &[]),
5054 ("impl Iterator<Item = u8>", &[]),
5055 ("Box<impl Fn()>", &[]),
5056 ("Option<!>", &["None"]),
5057 ];
5058 for (ty, expected) in rows {
5059 assert_eq!(values(ty), *expected, "{ty}");
5060 }
5061 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
5063 assert_eq!(body_values(&unit.sig.output), ["()"]);
5064 }
5065
5066 #[test]
5067 fn which_functions_get_their_body_replaced() {
5068 let src = r#"
5069 fn plain(a: u8) -> u8 { a + 1 }
5070 fn already(a: u8) -> bool { let _ = a; true }
5071 fn sole() -> bool { true }
5072 fn spaced() -> (u8, bool) { ( 0 , true ) }
5073 unsafe fn raw(a: u8) -> u8 { a }
5074 fn empty() {}
5075 fn one_call(s: &mut S) { s.go(); }
5076 fn two_calls(s: &mut S) { s.go(); s.stop(); }
5077 fn typed(s: &mut S) -> u8 { s.exit(); }
5078 fn tight() -> bool {true}
5079 #[rustfmt::skip]
5080 fn formatted(a: u8) -> u8 { a + 6 }
5081 #[mutants::timeout(5)]
5082 fn slow(a: u8) -> u8 { a + 7 }
5083 impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
5084 trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
5085 fn one_let(a: u8) { let _ = a; }
5086 fn never() -> ! { loop {} }
5087 fn hidden() -> impl Sized { 1 }
5088 #[mutants::skip]
5089 fn marked(a: u8) -> u8 { a + 2 }
5090 #[cfg_attr(test, mutants::skip)]
5091 fn marked_in_tests(a: u8) -> u8 { a + 3 }
5092 #[mutants::skip]
5093 impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
5094 #[mutants::skip]
5095 mod generated { fn inner(a: u8) -> u8 { a + 5 } }
5096 trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
5097 async fn later() -> u8 { 9 }
5098 "#;
5099 let sites = discover(src, 0).unwrap().sites;
5100 let bodies: Vec<String> = sites
5101 .iter()
5102 .filter_map(|s| match &s.kind {
5103 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
5104 _ => None,
5105 })
5106 .collect();
5107 assert_eq!(
5108 bodies,
5109 [
5110 "plain 0",
5111 "plain 1",
5112 "already true",
5113 "already false",
5114 "sole false",
5116 "spaced (0, false)",
5117 "spaced (1, true)",
5118 "spaced (1, false)",
5119 "two_calls ()",
5121 "typed 0",
5123 "typed 1",
5124 "tight false",
5125 "formatted 0",
5127 "formatted 1",
5128 "slow 0",
5129 "slow 1",
5130 "one_let ()",
5131 "provided 0",
5132 "provided 1",
5133 "later 0",
5134 "later 1",
5135 ]
5136 );
5137 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
5139 for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
5140 assert!(!texts.contains(&skipped), "{skipped}");
5141 }
5142 for mutated in ["a + 1", "a + 6", "a + 7"] {
5143 assert!(texts.contains(&mutated), "{mutated}");
5144 }
5145 let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
5146 assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
5147
5148 let body = sites
5149 .iter()
5150 .find(|s| matches!(s.kind, SiteKind::Body { .. }))
5151 .unwrap();
5152 assert_eq!(
5153 (body.line, body.column, body.text.as_str()),
5154 (2, 13, "fn plain(a: u8) -> u8")
5155 );
5156 let out = render(src, &sites, &all).text;
5157 syn::parse_file(&out).expect("instrumented source parses");
5158 assert_eq!(out.lines().count(), src.lines().count());
5159 assert!(
5160 out.contains(
5161 "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
5162 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
5163 ),
5164 "{out}"
5165 );
5166 let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
5169 let sites = discover(tight, 0).unwrap().sites;
5170 let out = render(tight, &sites, &all).text;
5171 syn::parse_file(&out).expect("instrumented source parses");
5172 assert!(
5173 out.starts_with(
5174 "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
5175 if !crate::__tmt_rt::live(1u32) { return true; } \
5176 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
5177 ),
5178 "{out}"
5179 );
5180 assert!(
5181 out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
5182 "{out}"
5183 );
5184 }
5185
5186 #[test]
5187 fn a_guard_that_is_written_true_or_false_has_only_the_other_for_a_mutant() {
5188 let src = "fn f(k: u8) -> u8 { match k { 0 if true => 1, 1 if (false) => 2, n if n > 3 => 3, _ => 4 } }";
5190 let found = discover(src, 0).unwrap();
5191 let guards = |sites: &[Site]| -> Vec<String> {
5192 sites
5193 .iter()
5194 .filter(|site| matches!(site.kind, SiteKind::Guard { .. }))
5195 .map(|site| {
5196 let into: Vec<String> =
5197 source_mutants(site).into_iter().map(|m| m.into).collect();
5198 format!("{} -> {}", site.text, into.join(" "))
5199 })
5200 .collect()
5201 };
5202 assert_eq!(guards(&found.sites), ["n > 3 -> true"]);
5203 assert_eq!(guards(&found.rebuild_sites), ["(false) -> true"]);
5206 let stuck = discover(
5208 "fn f(k: Option<u8>) -> u8 { match k { Some(0) if true => 1, Some(_) => 2, None => 3 } }",
5209 0,
5210 );
5211 assert_eq!(guards(&stuck.unwrap().rebuild_sites), ["true -> false"]);
5212 let split = discover("fn f(a: bool, b: bool) -> bool {\n a ||\n b\n}", 0).unwrap();
5215 let or = split
5216 .sites
5217 .iter()
5218 .find(|site| matches!(site.kind, SiteKind::Logic { .. }))
5219 .unwrap();
5220 assert_eq!(source_mutants(or)[0].replacement, "(a) && \n(b)");
5221 let mut mutants = source_mutants(&Site {
5222 id: 0,
5223 kind: SiteKind::Stmt,
5224 line: 1,
5225 column: 1,
5226 start: 0,
5227 end: 7,
5228 text: String::new(),
5229 });
5230 keep_line_ends("a(\n1\n);\nb", &mut mutants);
5231 assert_eq!(mutants[0].replacement, "\n\n");
5232 let arms: Vec<&str> = found
5235 .sites
5236 .iter()
5237 .chain(&found.rebuild_sites)
5238 .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
5239 .map(|site| site.text.as_str())
5240 .collect();
5241 assert_eq!(arms, ["0 if true => ..", "n if n > 3 => .."]);
5242 }
5243
5244 #[test]
5245 fn minus_guards_and_fields() {
5246 let src = r#"
5247 fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
5248 let a = -x + -5 - -0 + (-0.0 * -y) as i32;
5249 let b = match k {
5250 Kind::A(n) if n > 1 => 1,
5251 Kind::A(n) if let Some(m) = half(n) => m,
5252 Kind::B if x > 0 && let Some(m) = half(x) => m,
5253 #[cfg(any())]
5254 Kind::B if x > 2 => 2,
5255 Kind::B => 3,
5256 };
5257 let c = match b { n if n > 3 => 1, _ => 0 };
5258 let first = Options { depth: a, name, ..base };
5259 let second = Options { depth: -b, ..Default::default() };
5260 let third = Wrap::<u8> { 0: c, ..Wrap::new() };
5261 let _ = Options { depth: 1, ..base.clone() };
5262 let _ = Options { depth: 2, ..make(3) };
5263 let _ = Options { depth: 6, ..(pick())() };
5264 let _ = -2.5 + y;
5265 let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
5266 let _ = Options { depth: 5, name: n, strict: false };
5267 first
5268 }
5269 "#;
5270 let sites = found(src, 0).unwrap().sites;
5271 let kinds: Vec<String> = sites
5272 .iter()
5273 .filter_map(|s| match &s.kind {
5274 SiteKind::Neg {
5275 operand, literal, ..
5276 } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
5277 SiteKind::Guard { can_be_false } => {
5278 Some(format!("guard {} | can_be_false={can_be_false}", s.text))
5279 }
5280 SiteKind::Field {
5281 name,
5282 shorthand,
5283 from_base: Some(from_base),
5284 ..
5285 } => Some(format!(
5286 "field {} | {name} | shorthand={shorthand} | {from_base}",
5287 s.text
5288 )),
5289 _ => None,
5290 })
5291 .collect();
5292 assert_eq!(
5293 kinds,
5294 [
5295 "neg -x | x | literal=false",
5296 "neg -5 | 5 | literal=true",
5297 "neg -0.0 | 0.0 | literal=true",
5299 "neg -y | y | literal=false",
5300 "guard n > 1 | can_be_false=true",
5302 "guard n > 3 | can_be_false=false",
5304 "field depth: a | depth | shorthand=false | (base).depth",
5305 "field name | name | shorthand=true | (base).name",
5306 "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
5307 "neg -b | b | literal=false",
5308 "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
5309 "neg -2.5 | 2.5 | literal=true",
5310 "field strict: true | strict | shorthand=false | (*other).strict",
5313 ]
5314 );
5315 let field = sites
5317 .iter()
5318 .find(|s| s.text == "depth: a")
5319 .expect("the field is a site");
5320 let line = src.lines().nth(field.line - 1).unwrap();
5321 assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
5322 assert_eq!(&src[field.start..field.end], "a");
5323 let out = render(src, &sites, &all).text;
5324 syn::parse_file(&out).expect("instrumented source parses");
5325 assert_eq!(out.lines().count(), src.lines().count());
5326 for expected in [
5327 "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
5329 "u32) { -__tmt_a } else { __tmt_a } })",
5331 "u32) { -5 } else { 5 })",
5332 "Kind::A(n) if crate::__tmt_rt::ret(",
5334 "u32, (match (&(n), &(1))",
5335 "n if crate::__tmt_rt::arm(",
5336 ") && (crate::__tmt_rt::ret(",
5337 "depth: if crate::__tmt_rt::live(",
5338 "{ a } else { (base).depth }",
5339 "name: if crate::__tmt_rt::live(",
5341 "{ name } else { (base).name }, ..base }",
5342 "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
5343 "0: if crate::__tmt_rt::live(",
5344 "Options { depth: 1, ..base.clone() }",
5345 "Options { depth: 2, ..make(3) }",
5346 "Options { depth: 6, ..(pick())() }",
5347 "Options { depth: 5, name: n, strict: false }",
5348 ] {
5349 assert!(out.contains(expected), "{expected}\n{out}");
5350 }
5351 assert!(
5352 !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
5353 "{out}"
5354 );
5355 }
5356 fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
5358 sites
5359 .iter()
5360 .flat_map(|site| {
5361 source_mutants(site).into_iter().map(|m| {
5362 let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
5363 syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
5364 format!("{} -> {}: {}", m.what, m.into, text.trim())
5365 })
5366 })
5367 .collect()
5368 }
5369
5370 #[test]
5371 fn what_cannot_be_probed_is_mutated_in_the_source() {
5372 let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
5375 fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
5376 fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
5377 impl S { const fn k(&self) -> u8 { -self.0 } }\n\
5378 trait T { const fn d(a: u8) -> u8 { a } }\n";
5379 let found = discover(src, 0).unwrap();
5380 assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
5381 let places: Vec<(usize, usize, &str)> = found
5382 .rebuild_sites
5383 .iter()
5384 .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
5385 .map(|s| (s.line, s.column, s.text.as_str()))
5386 .collect();
5387 assert_eq!(
5388 places,
5389 [
5390 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
5391 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
5392 (1, 36, "a < b"),
5393 (2, 28, "*m.entry(k).or_insert(0) += 1"),
5394 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
5395 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
5396 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
5397 (3, 53, "0..n"),
5399 (4, 10, "const fn k(&self) -> u8"),
5400 (4, 10, "const fn k(&self) -> u8"),
5401 (4, 36, "-self.0"),
5402 (5, 11, "const fn d(a: u8) -> u8"),
5403 (5, 11, "const fn d(a: u8) -> u8"),
5404 ]
5405 );
5406 assert_eq!(
5407 found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
5408 (0..found.sites.len() as u32).collect::<Vec<_>>()
5409 );
5410 let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
5411 assert_eq!(
5412 numbered,
5413 [
5414 "fn f(m: &mut Map, k: u8)",
5415 "*m.entry(k).or_insert(0) += 1;",
5416 "m.total -= 1;",
5417 "m.total -= 1",
5418 ]
5419 );
5420 assert_eq!(
5421 mutated(src, &found.rebuild_sites)
5422 .iter()
5423 .map(|line| line.lines().next().unwrap().to_string())
5424 .take(5)
5425 .collect::<Vec<_>>(),
5426 [
5427 "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
5428 "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
5429 "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
5430 "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
5431 "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
5432 ]
5433 );
5434 let whats: Vec<String> = found
5435 .rebuild_sites
5436 .iter()
5437 .flat_map(|site| {
5438 source_mutants(site)
5439 .into_iter()
5440 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
5441 })
5442 .skip(5)
5443 .collect();
5444 assert_eq!(
5445 whats,
5446 [
5447 "*m.entry(k).or_insert(0) += 1: += -> -=",
5448 "*m.entry(k).or_insert(0) += 1: += -> *=",
5449 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
5450 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
5451 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
5452 "0..n: .. -> ..=",
5453 "const fn k(&self) -> u8: body -> 0",
5454 "const fn k(&self) -> u8: body -> 1",
5455 "-self.0: - -> ",
5456 "const fn d(a: u8) -> u8: body -> 0",
5457 "const fn d(a: u8) -> u8: body -> 1",
5458 ]
5459 );
5460 }
5461
5462 #[test]
5463 fn fields_are_removed_from_arbitrary_struct_updates() {
5464 for base in ["base", "make(seed)", "builder.make(seed)"] {
5466 for field in ["value: 9", "value"] {
5467 for attribute in ["", "#[cfg(any())] "] {
5468 let original =
5469 format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
5470 let found = discover(&original, 0).unwrap();
5471 let fields: Vec<_> = found
5472 .sites
5473 .iter()
5474 .chain(&found.rebuild_sites)
5475 .flat_map(source_mutants)
5476 .filter(|mutant| mutant.what == "field" && mutant.into == "value")
5477 .collect();
5478 if attribute.is_empty() {
5479 assert_eq!(fields.len(), 1, "{original}");
5480 let m = &fields[0];
5481 let changed = format!(
5482 "{}{}{}",
5483 &original[..m.start],
5484 m.replacement,
5485 &original[m.end..]
5486 );
5487 assert_eq!(
5488 changed,
5489 format!("fn f() -> S {{ S {{ other: 2, ..{base} }} }}")
5490 );
5491 syn::parse_file(&changed).unwrap();
5492 } else {
5493 assert!(fields.is_empty(), "{original}");
5494 }
5495 }
5496 }
5497 }
5498 let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
5499 assert!(
5500 plain
5501 .sites
5502 .iter()
5503 .chain(&plain.rebuild_sites)
5504 .flat_map(source_mutants)
5505 .all(|m| m.what != "field")
5506 );
5507 }
5508
5509 #[test]
5510 fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
5511 for outer in ["Wrapper", "Option", "Result"] {
5513 for inner in ["bool", "impl Iterator<Item = u8>"] {
5514 for error in [false, true] {
5515 let error_values: &[&str] = if error { &["7"] } else { &[] };
5516 let extra = if outer == "Result" { ", u8" } else { "" };
5517 let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
5518 let found = discover_with_errors(&source, 0, error_values).unwrap();
5519 let values: Vec<&str> = found
5520 .sites
5521 .iter()
5522 .chain(&found.rebuild_sites)
5523 .filter_map(|site| match &site.kind {
5524 SiteKind::Body { value, .. } => Some(value.as_str()),
5525 _ => None,
5526 })
5527 .collect();
5528 let example = match (outer, inner) {
5529 ("Wrapper", "bool") => "Wrapper::from_iter([false])",
5530 ("Option", "bool") => "Some(false)",
5531 ("Result", "bool") => "Ok(false)",
5532 ("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
5533 ("Option", _) => "Some(::core::iter::once(1))",
5534 ("Result", _) => "Ok(::core::iter::once(1))",
5535 _ => unreachable!(),
5536 };
5537 assert!(values.contains(&example), "{source}: {values:?}");
5538 assert_eq!(
5539 values.contains(&"Err(7)"),
5540 outer == "Result" && error,
5541 "{source}"
5542 );
5543 if inner != "bool" {
5544 assert!(found.sites.is_empty(), "{source}");
5545 }
5546 }
5547 }
5548 }
5549 }
5550
5551 #[test]
5552 fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
5553 let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
5554 fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
5555 let found = discover(source, 0).unwrap();
5556 let removals: Vec<_> = found
5557 .sites
5558 .iter()
5559 .chain(&found.rebuild_sites)
5560 .flat_map(source_mutants)
5561 .filter(|mutant| mutant.replacement.is_empty())
5562 .map(|mutant| &source[mutant.start..mutant.end])
5563 .collect();
5564 assert!(removals.contains(&"v.clear();"), "{removals:?}");
5565 assert!(removals.contains(&"0 => 4,"), "{removals:?}");
5566 assert!(
5567 removals.contains(&"#[allow(unused)] 1 => 5,"),
5568 "{removals:?}"
5569 );
5570 }
5571
5572 #[test]
5573 fn source_mutants_of_every_kind() {
5574 let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
5575 let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
5576 O { on: x, a, ..base } }";
5577 let sites = found(src, 0).unwrap().sites;
5578 assert_eq!(mutated(src, &sites).len(), 18);
5580 let changes: Vec<String> = sites
5581 .iter()
5582 .flat_map(source_mutants)
5583 .map(|m| {
5584 format!(
5585 "{} -> {} | `{}` becomes `{}`",
5586 m.what,
5587 m.into,
5588 &src[m.start..m.end],
5589 m.replacement
5590 )
5591 })
5592 .collect();
5593 assert_eq!(
5594 changes,
5595 [
5596 "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
5598 "arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
5599 "guard -> true | `n >= 1` becomes `true`",
5600 ">= -> < | ` >= ` becomes ` < `",
5601 "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
5602 "! -> | `!` becomes ``",
5603 "!= -> == | ` != ` becomes ` == `",
5604 "<= -> > | ` <= ` becomes ` > `",
5605 "- -> | `-` becomes ``",
5606 "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
5607 "> -> == | ` > ` becomes ` == `",
5608 "> -> < | ` > ` becomes ` < `",
5609 "> -> >= | ` > ` becomes ` >= `",
5610 "% -> / | ` % ` becomes ` / `",
5611 "% -> + | `a % b` becomes `(a + b)`",
5612 "== -> != | ` == ` becomes ` != `",
5613 "field -> on | `on: x,` becomes ``",
5614 "field -> a | `a,` becomes ``",
5615 ]
5616 );
5617 let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
5619 let sites = discover(src, 0).unwrap().sites;
5620 for site in &sites {
5621 let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
5622 assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
5623 }
5624 let ends = |src: &str| -> Vec<String> {
5626 discover(src, 0)
5627 .unwrap()
5628 .sites
5629 .iter()
5630 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
5631 .flat_map(source_mutants)
5632 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
5633 .collect()
5634 };
5635 assert_eq!(
5636 ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
5637 ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
5638 );
5639 assert_eq!(
5640 ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
5641 ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
5642 );
5643 }
5644
5645 #[test]
5646 fn iterators_to_return_instead() {
5647 let values = |ty: &str| {
5648 let function: syn::ItemFn =
5649 syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
5650 iterator_values(&function.sig.output)
5651 };
5652 assert_eq!(
5653 values("impl Iterator<Item = bool>"),
5654 [
5655 "::core::iter::empty()",
5656 "::core::iter::once(true)",
5657 "::core::iter::once(false)"
5658 ]
5659 );
5660 assert_eq!(
5661 values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
5662 3
5663 );
5664 assert_eq!(
5666 values("impl Iterator<Extra = u8, Item = ()>"),
5667 ["::core::iter::empty()", "::core::iter::once(())"]
5668 );
5669 assert_eq!(
5671 values("impl Iterator<Item = impl Sized>"),
5672 ["::core::iter::empty()"]
5673 );
5674 for other in [
5675 "impl Sized",
5676 "impl Iterator",
5677 "impl IntoIterator<Item = u8>",
5678 "Box<dyn Iterator<Item = u8>>",
5679 "u8",
5680 "()",
5681 ] {
5682 assert!(values(other).is_empty(), "{other}");
5683 }
5684 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
5685 assert!(iterator_values(&unit.sig.output).is_empty());
5686 }
5687
5688 fn built(src: &str) -> Vec<String> {
5690 let found = discover(src, 0).unwrap();
5691 found
5692 .rebuild_sites
5693 .iter()
5694 .flat_map(source_mutants)
5695 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
5696 .collect()
5697 }
5698
5699 #[test]
5700 fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
5701 let bodies = |src: &str| -> Vec<(String, bool)> {
5702 discover(src, 0)
5703 .unwrap()
5704 .sites
5705 .iter()
5706 .filter_map(|site| match &site.kind {
5707 SiteKind::Body {
5708 value, sole_expr, ..
5709 } => Some((value.clone(), sole_expr.is_some())),
5710 _ => None,
5711 })
5712 .collect()
5713 };
5714 let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
5715 assert_eq!(values("fn t() -> bool { true }"), ["false"]);
5717 assert_eq!(values("fn n() -> u8 { 0 }"), ["1"]);
5718 assert_eq!(
5719 values("fn s() -> String { String :: new () }"),
5720 ["\"xyzzy\".into()"]
5721 );
5722 assert_eq!(
5724 values("fn s() -> &'static str { \" \" }"),
5725 ["\"\"", "\"xyzzy\""]
5726 );
5727 for (body, only_computes) in [
5730 ("n > 0", true),
5731 ("!(self.limit < n) && n as u8 != 3", true),
5732 ("(n, 1).0 > *&n", true),
5733 ("self.push(n) > 0", false),
5734 ("next() > 0", false),
5735 ("matches!(n, 1)", false),
5736 ("(if n > 1 { n } else { 0 }) > 0", false),
5737 ("list[n] > 0", false),
5738 ("check(n)? > 0", false),
5739 ("(self.count += n) == ()", false),
5740 ("(self.count = n) == ()", false),
5741 ] {
5742 let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
5743 let all = bodies(&src);
5744 assert_eq!(all.len(), 2, "{body}");
5745 assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
5746 }
5747 }
5748
5749 #[test]
5750 fn items_are_named_by_what_is_around_them() {
5751 let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
5752 mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
5753 impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
5754 impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
5755 trait Tr { fn provided(&self) {} fn required(&self); }\n\
5756 static S: u8 = 3;\nlet";
5757 assert!(named_items(src).is_empty());
5759 let src = src.strip_suffix("let").unwrap();
5760 let items = named_items(src);
5761 let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
5762 assert_eq!(
5763 names,
5764 [
5765 "top",
5766 "top::inner",
5767 "m::in_mod",
5768 "m::K",
5769 "Store::commit",
5770 "Store::LIMIT",
5771 "<fmt::Display for Id<T>>::fmt",
5772 "Tr::provided",
5773 "Tr::required",
5774 "S",
5775 ]
5776 );
5777 let at = |text: &str| src.find(text).unwrap();
5779 assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
5780 assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
5781 assert_eq!(enclosing_item(&items, at("fn top")), "top");
5782 assert_eq!(enclosing_item(&items, at("mod m")), "");
5783 assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
5784 assert_eq!(enclosing_item(&items, src.len()), "");
5785 let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
5787 assert_eq!(enclosing_item(&items, first - 1), "");
5788 assert_eq!(enclosing_item(&items, first), "m::in_mod");
5789 assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
5790 assert_eq!(enclosing_item(&items, after), "");
5791 let text = "ab\nçd e\n";
5793 assert_eq!(offset_of(text, 1, 1), Some(0));
5794 assert_eq!(offset_of(text, 1, 2), Some(1));
5795 assert_eq!(offset_of(text, 2, 1), Some(3));
5796 assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
5797 assert_eq!(offset_of(text, 2, 99), Some(text.len()));
5798 assert_eq!(offset_of(text, 0, 1), None);
5799 assert_eq!(offset_of(text, 1, 0), None);
5800 }
5801
5802 #[test]
5803 fn only_the_range_of_a_for_is_probed() {
5804 let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
5805 for _ in a..b {}\n\
5806 for _ in (a..=b) {}\n\
5807 for _ in (a..b).rev() {}\n\
5808 let kept = a..b;\n\
5809 let _ = &v[a as usize..b as usize];\n\
5810 for _ in kept.clone() {}\n\
5811 for _ in 0..3 {}\n\
5812 let _ = &v[0..3];\n\
5813 (a..=b).count() }";
5814 let all = discover(src, 0).unwrap();
5815 let ranges = |sites: &[Site]| -> Vec<usize> {
5816 sites
5817 .iter()
5818 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
5819 .map(|site| site.line)
5820 .collect()
5821 };
5822 assert_eq!(ranges(&all.sites), [2, 3]);
5824 assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
5827 let literal: Vec<(&str, String)> = all
5828 .rebuild_sites
5829 .iter()
5830 .filter(|site| site.line == 8 || site.line == 9)
5831 .flat_map(|site| {
5832 source_mutants(site)
5833 .into_iter()
5834 .map(move |mutant| (site.text.as_str(), mutant.replacement))
5835 })
5836 .collect();
5837 assert_eq!(
5838 literal,
5839 [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
5840 );
5841 }
5842
5843 #[test]
5844 fn what_marks_code_as_not_to_be_mutated() {
5845 let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
5846 #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
5847 #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
5848 #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
5849 #[mutants::skip] mod generated;\n\
5850 #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
5851 mod plain;\n\
5852 mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
5853 #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
5854 let all = discover(src, 0).unwrap();
5855 let texts: Vec<&str> = found_arith(&all.sites);
5856 assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
5857 assert_eq!(
5859 all.test_modules,
5860 [
5861 TestModule {
5862 name: "generated".to_string(),
5863 path: None
5864 },
5865 TestModule {
5866 name: "other".to_string(),
5867 path: Some("gen/other.rs".to_string())
5868 },
5869 ]
5870 );
5871 }
5872
5873 fn found_arith(sites: &[Site]) -> Vec<&str> {
5874 sites
5875 .iter()
5876 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
5877 .map(|site| site.text.as_str())
5878 .collect()
5879 }
5880
5881 #[test]
5882 fn a_replaced_operator_keeps_its_operands() {
5883 assert_eq!(
5886 built("const X: i32 = 8 - 2 * 3;"),
5887 [
5888 "const X: i32 = 8 + 2 * 3;",
5889 "const X: i32 = (8) / (2 * 3);",
5890 "const X: i32 = 8 - 2 / 3;",
5891 "const X: i32 = 8 - (2 + 3);",
5892 ]
5893 );
5894 assert_eq!(
5895 built("const B: bool = P || Q && R;"),
5896 [
5897 "const B: bool = (P) && (Q && R);",
5898 "const B: bool = P || (Q || R);",
5899 ]
5900 );
5901 assert_eq!(
5902 built("const M: u8 = A & B | C;"),
5903 [
5904 "const M: u8 = (A & B) & (C);",
5905 "const M: u8 = (A & B) ^ (C);",
5906 "const M: u8 = (A | B) | C;",
5907 "const M: u8 = (A ^ B) | C;",
5908 ]
5909 );
5910 assert_eq!(
5911 built("const S: u8 = 1 << 2 + 1;"),
5912 [
5913 "const S: u8 = 1 >> 2 + 1;",
5914 "const S: u8 = 1 << 2 - 1;",
5915 "const S: u8 = 1 << (2) * (1);",
5916 ]
5917 );
5918 assert_eq!(
5920 built("const C: bool = A + 1 < B;")[..3],
5921 [
5922 "const C: bool = A + 1 == B;",
5923 "const C: bool = A + 1 > B;",
5924 "const C: bool = A + 1 <= B;",
5925 ]
5926 );
5927 let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
5928 for expected in [
5929 "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
5930 "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
5931 "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
5932 ] {
5933 assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
5934 }
5935 }
5936
5937 #[test]
5938 fn excluded_parent_items_do_not_contribute_const_sites() {
5939 let source = r#"
5940 #[cfg(test)] enum TestEnum { A = 1 + 2 }
5941 #[mutants::skip] struct Skip { a: [u8; 2 + 3] }
5942 #[cfg(test)] type Alias = [u8; 3 + 4];
5943 #[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
5944 #[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
5945 struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
5946 fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
5947 const DATA: [u8; 7 + 8] = [0; 15];
5948 "#;
5949 let found = discover(source, 0).unwrap();
5950 let sites: Vec<_> = found
5951 .rebuild_sites
5952 .iter()
5953 .map(|site| site.text.as_str())
5954 .collect();
5955 assert_eq!(sites, ["7 + 8"]);
5956 }
5957
5958 #[test]
5959 fn compile_time_expressions_get_source_mutants_but_never_probes() {
5960 for (place, context) in [
5962 ("inline", "let _ = const { 6 * 7 };"),
5963 ("repeat", "let _ = [0u8; 6 * 7];"),
5964 ("type length", "let _: [u8; 6 * 7];"),
5965 ("discriminant", "enum Value { One = 6 * 7 }"),
5966 ("const argument", "let _: Items<{ 6 * 7 }>;"),
5967 ("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
5968 ] {
5969 for qualifier in ["", "const "] {
5970 for marker in ["", "#[mutants::skip] "] {
5971 let source =
5972 format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
5973 let found = discover(&source, 0).unwrap();
5974 let variants: Vec<_> = found
5975 .rebuild_sites
5976 .iter()
5977 .filter(|site| site.text == "6 * 7")
5978 .flat_map(source_mutants)
5979 .map(|mutant| mutant.into)
5980 .collect();
5981 let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
5982 assert_eq!(variants, expected, "{place}: {source}");
5983 assert!(
5984 found.sites.iter().all(|site| site.text != "6 * 7"),
5985 "{source}"
5986 );
5987 assert_eq!(
5988 found.sites.iter().any(|site| site.text == "x * 2"),
5989 marker.is_empty() && qualifier.is_empty(),
5990 "{source}"
5991 );
5992 }
5993 }
5994 }
5995 }
5996
5997 #[test]
5998 fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
5999 let source = r#"
6000 /// The mutants::skip attribute is documented here.
6001 #[cfg(any(test, feature = "production"))]
6002 fn public(x: u32) -> u32 { x + 1 }
6003
6004 #[cfg(all(test, feature = "production"))]
6005 fn for_tests(x: u32) -> u32 { x + 2 }
6006
6007 #[cfg_attr(any(), mutants::skip)]
6008 fn skipped(x: u32) -> u32 { x + 3 }
6009 "#;
6010 let found = discover(source, 0).unwrap();
6011 let arithmetic: Vec<_> = found
6012 .sites
6013 .iter()
6014 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
6015 .map(|site| site.text.as_str())
6016 .collect();
6017 assert_eq!(arithmetic, ["x + 1"]);
6018 }
6019
6020 #[test]
6021 fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
6022 let src = "const HALF: u64 = SPAN / 2;\n\
6023 static LIMIT: i32 = -(1 << 4);\n\
6024 impl S { const K: bool = A < B; }\n\
6025 trait T { const D: u8 = 3 + 4; const R: u8; }\n\
6026 #[cfg(test)]\n\
6027 const ONLY_IN_TESTS: u8 = 5 + 6;\n\
6028 #[mutants::skip]\n\
6029 const MARKED: u8 = 7 + 8;\n\
6030 #[cfg(test)]\n\
6031 static TEST_LIMIT: u8 = 9 + 1;\n\
6032 impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
6033 trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
6034 fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
6035 fn one(s: &mut S) { s.go(); }\n\
6036 fn two(s: &mut S) { s.go(); s.stop(); }\n\
6037 fn value(s: &mut S) -> u8 { s.get() }\n";
6038 let found = discover(src, 0).unwrap();
6039 let built: Vec<String> = found
6040 .rebuild_sites
6041 .iter()
6042 .flat_map(|site| {
6043 source_mutants(site)
6044 .into_iter()
6045 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
6046 })
6047 .collect();
6048 assert_eq!(
6049 built,
6050 [
6051 "SPAN / 2: / -> *",
6052 "SPAN / 2: / -> %",
6053 "-(1 << 4): - -> ",
6054 "1 << 4: << -> >>",
6055 "A < B: < -> ==",
6056 "A < B: < -> >",
6057 "A < B: < -> <=",
6058 "3 + 4: + -> -",
6059 "3 + 4: + -> *",
6060 "2 + 3: + -> -",
6061 "2 + 3: + -> *",
6062 "60 * 60: * -> /",
6064 "60 * 60: * -> +",
6065 ]
6066 );
6067 mutated(src, &found.rebuild_sites);
6068 let probed: Vec<&str> = found
6070 .sites
6071 .iter()
6072 .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
6073 .map(|s| s.text.as_str())
6074 .collect();
6075 assert_eq!(probed, ["x + 60 * 60"]);
6076 assert_eq!(found.single_statement_bodies, ["one"]);
6078 let bodies: Vec<String> = found
6079 .sites
6080 .iter()
6081 .filter_map(|s| match &s.kind {
6082 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
6083 _ => None,
6084 })
6085 .collect();
6086 assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
6087 }
6088 #[test]
6089 fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
6090 for context in [
6092 "fn f() { @let _ = [0u8; 6 * 7]; }",
6093 "fn f() { let _ = @const { 6 * 7 }; }",
6094 "struct Items<@const N: usize = { 6 * 7 }>;",
6095 "@enum E { A = 6 * 7 }",
6096 "enum E { @A = 6 * 7 }",
6097 "enum E { @A([u8; 6 * 7]) }",
6098 "@struct S { a: [u8; 6 * 7] }",
6099 "struct S { @a: [u8; 6 * 7] }",
6100 "@union U { a: [u8; 6 * 7] }",
6101 "@trait T { const D: [u8; 6 * 7]; }",
6102 "trait T { @type A = [u8; 6 * 7]; }",
6103 "@type A = [u8; 6 * 7];",
6104 "impl T for S { @type A = [u8; 6 * 7]; }",
6105 ] {
6106 for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
6107 let source = context.replace('@', attribute);
6108 let found = discover(&source, 0).unwrap();
6109 let expected: &[&str] = if attribute.is_empty() {
6110 &["6 * 7"]
6111 } else {
6112 &[]
6113 };
6114 assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
6115 assert!(found_arith(&found.sites).is_empty(), "{source}");
6116 }
6117 }
6118 for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
6120 let source =
6121 format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
6122 let found = discover(&source, 0).unwrap();
6123 assert!(found.sites.is_empty(), "{source}");
6124 assert!(found.rebuild_sites.is_empty(), "{source}");
6125 }
6126 }
6127
6128 #[test]
6129 fn compile_time_expressions_are_found_inside_types() {
6130 let built = |source: &str| -> Vec<String> {
6131 let found = discover(source, 0).unwrap();
6132 assert!(found_arith(&found.sites).is_empty(), "{source}");
6133 found_arith(&found.rebuild_sites)
6134 .into_iter()
6135 .map(str::to_string)
6136 .collect()
6137 };
6138 assert_eq!(
6140 built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
6141 ["1 + 2", "3 + 4"]
6142 );
6143 assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
6145 assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
6148 }
6149
6150 #[test]
6151 fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
6152 let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
6153 #[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
6154 #[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
6155 #[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
6156 #[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
6157 #[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
6158 let found = discover(src, 0).unwrap();
6159 assert_eq!(
6160 found_arith(&found.sites),
6161 ["a + 1", "a + 2", "a + 5", "a + 6"]
6162 );
6163 }
6164
6165 #[test]
6166 fn which_arms_are_probed_built_or_left_alone() {
6167 let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
6168 \x20 let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
6169 \x20 let q = match k { Kind::A => 1, Kind::B => 2 };\n\
6170 \x20 let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
6171 \x20 p + q + r\n\
6172 }\n";
6173 let found = discover(src, 0).unwrap();
6174 let arms = |sites: &[Site]| -> Vec<String> {
6175 sites
6176 .iter()
6177 .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
6178 .map(|site| site.text.clone())
6179 .collect()
6180 };
6181 assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
6183 assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
6187 let in_arms: Vec<&str> = found_arith(&found.sites)
6189 .into_iter()
6190 .filter(|text| text.starts_with("a + "))
6191 .collect();
6192 assert_eq!(in_arms, ["a + 3", "a + 4"]);
6193 }
6194
6195 #[test]
6196 fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
6197 let src = "fn f(a: u8, base: S) {\n\
6198 \x20 let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
6199 \x20 g(#[mutants::skip] S { v: a + 4, ..base });\n\
6200 \x20 g(#[cfg(test)] S { v: a + 5, ..base });\n\
6201 \x20 g(#[allow(unused)] S { v: a + 6, ..base });\n\
6202 \x20 g(<S as Tr>::Out { v: a + 7, ..base });\n\
6203 }\n";
6204 let found = discover(src, 0).unwrap();
6205 let fields = |sites: &[Site]| -> Vec<String> {
6206 sites
6207 .iter()
6208 .filter_map(|site| match &site.kind {
6209 SiteKind::Field { from_base, .. } => Some(format!(
6210 "{} | {}",
6211 site.text,
6212 from_base.as_deref().unwrap_or("-")
6213 )),
6214 _ => None,
6215 })
6216 .collect()
6217 };
6218 assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
6220 assert_eq!(
6223 fields(&found.rebuild_sites),
6224 ["v: a + 6 | -", "v: a + 7 | -"]
6225 );
6226 assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
6227 }
6228
6229 #[test]
6230 fn body_values_that_are_only_built() {
6231 let bodies = |sites: &[Site]| -> Vec<String> {
6232 sites
6233 .iter()
6234 .filter_map(|site| match &site.kind {
6235 SiteKind::Body { value, .. } => Some(value.clone()),
6236 _ => None,
6237 })
6238 .collect()
6239 };
6240 let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
6243 assert_eq!(bodies(&found.sites), ["Default::default()"]);
6244 assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
6245 assert_eq!(
6246 bodies(&found.rebuild_sites),
6247 [
6248 "Wrapper::from_iter([true])",
6249 "Wrapper::new(true)",
6250 "Wrapper::from(true)",
6251 "Wrapper::from_iter([false])",
6252 "Wrapper::new(false)",
6253 "Wrapper::from(false)",
6254 ]
6255 );
6256 assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
6258 let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
6261 let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
6262 assert!(bodies(&found.sites).is_empty());
6263 assert_eq!(
6264 bodies(&found.rebuild_sites),
6265 [
6266 "::core::iter::empty()",
6267 "::core::iter::once(::core::iter::empty())",
6268 "::core::iter::once(::core::iter::once(0))",
6269 "::core::iter::once(::core::iter::once(1))",
6270 ]
6271 );
6272 let function: syn::ItemFn =
6273 syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
6274 assert_eq!(
6275 iterator_values(&function.sig.output),
6276 ["::core::iter::empty()"]
6277 );
6278 }
6279}