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 Range {
87 inclusive: bool,
88 lhs: String,
89 rhs: String,
90 gap: (usize, usize),
91 },
92 Arm {
95 pattern: String,
96 guard: ArmGuard,
98 removal: (usize, usize),
99 },
100 Stmt,
102 Neg {
104 minus: (usize, usize),
106 operand: String,
107 literal: bool,
109 },
110 Guard {
112 can_be_false: bool,
115 },
116 Field {
118 name: String,
119 shorthand: bool,
121 from_base: Option<String>,
123 removal: (usize, usize),
125 },
126 Body {
129 name: String,
130 value: String,
131 sole_expr: Option<(usize, usize)>,
135 },
136}
137
138#[derive(Clone, Copy, PartialEq, Eq, Debug)]
139pub enum ArmGuard {
140 None(usize),
142 Existing(usize, usize),
144}
145
146#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
147#[serde(rename_all = "snake_case")]
148pub enum ArithOp {
149 Add,
150 Sub,
151 Mul,
152 Div,
153 Rem,
154 BitAnd,
155 BitOr,
156 BitXor,
157 Shl,
158 Shr,
159}
160
161impl ArithOp {
162 pub fn binding(self) -> u8 {
164 match self {
165 ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
166 ArithOp::Add | ArithOp::Sub => 4,
167 ArithOp::Shl | ArithOp::Shr => 3,
168 ArithOp::BitAnd => 2,
169 ArithOp::BitXor => 1,
170 ArithOp::BitOr => 0,
171 }
172 }
173
174 pub const ALL: [ArithOp; 10] = [
175 ArithOp::Add,
176 ArithOp::Sub,
177 ArithOp::Mul,
178 ArithOp::Div,
179 ArithOp::Rem,
180 ArithOp::BitAnd,
181 ArithOp::BitOr,
182 ArithOp::BitXor,
183 ArithOp::Shl,
184 ArithOp::Shr,
185 ];
186
187 pub fn symbol(self) -> &'static str {
188 match self {
189 ArithOp::Add => "+",
190 ArithOp::Sub => "-",
191 ArithOp::Mul => "*",
192 ArithOp::Div => "/",
193 ArithOp::Rem => "%",
194 ArithOp::BitAnd => "&",
195 ArithOp::BitOr => "|",
196 ArithOp::BitXor => "^",
197 ArithOp::Shl => "<<",
198 ArithOp::Shr => ">>",
199 }
200 }
201
202 pub fn swapped(self) -> ArithOp {
204 match self {
205 ArithOp::Add => ArithOp::Sub,
206 ArithOp::Sub => ArithOp::Add,
207 ArithOp::Mul => ArithOp::Div,
208 ArithOp::Div => ArithOp::Mul,
209 ArithOp::Rem => ArithOp::Div,
210 ArithOp::BitAnd => ArithOp::BitOr,
211 ArithOp::BitOr => ArithOp::BitAnd,
212 ArithOp::BitXor => ArithOp::BitAnd,
213 ArithOp::Shl => ArithOp::Shr,
214 ArithOp::Shr => ArithOp::Shl,
215 }
216 }
217
218 pub fn swapped2(self) -> Option<ArithOp> {
220 Some(match self {
221 ArithOp::Add => ArithOp::Mul,
222 ArithOp::Sub => ArithOp::Div,
223 ArithOp::Mul => ArithOp::Add,
224 ArithOp::Div => ArithOp::Rem,
225 ArithOp::Rem => ArithOp::Add,
226 ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
227 ArithOp::BitXor => ArithOp::BitOr,
228 ArithOp::Shl | ArithOp::Shr => return None,
229 })
230 }
231
232 pub fn second(self, assign: bool) -> Option<ArithOp> {
236 if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
237 return None;
238 }
239 self.swapped2()
240 }
241
242 pub fn is_bitwise(self) -> bool {
244 matches!(
245 self,
246 ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
247 )
248 }
249
250 fn stem(self) -> (&'static str, &'static str) {
252 match self {
253 ArithOp::Add => ("add", "Add"),
254 ArithOp::Sub => ("sub", "Sub"),
255 ArithOp::Mul => ("mul", "Mul"),
256 ArithOp::Div => ("div", "Div"),
257 ArithOp::Rem => ("rem", "Rem"),
258 ArithOp::BitAnd => ("bitand", "BitAnd"),
259 ArithOp::BitOr => ("bitor", "BitOr"),
260 ArithOp::BitXor => ("bitxor", "BitXor"),
261 ArithOp::Shl => ("shl", "Shl"),
262 ArithOp::Shr => ("shr", "Shr"),
263 }
264 }
265
266 pub(crate) fn method(self, assign: bool) -> String {
268 format!(
269 "tmt_{}{}",
270 self.stem().0,
271 if assign { "_assign" } else { "" }
272 )
273 }
274
275 pub(crate) fn fallback_trait(self, assign: bool) -> String {
277 format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
278 }
279
280 fn prim_trait(self, assign: bool) -> &'static str {
282 match (self.is_bitwise(), assign) {
283 (false, false) => "ArithPrim",
284 (true, false) => "BitPrim",
285 (false, true) => "ArithAssignPrim",
286 (true, true) => "BitAssignPrim",
287 }
288 }
289}
290
291#[derive(Clone, PartialEq, Eq, Debug)]
292pub struct Site {
293 pub id: u32,
294 pub kind: SiteKind,
295 pub line: usize,
297 pub column: usize,
298 pub start: usize,
300 pub end: usize,
301 pub text: String,
302}
303
304#[derive(Debug, PartialEq, Eq)]
305pub struct TestModule {
306 pub name: String,
307 pub path: Option<String>,
309}
310
311#[derive(Debug, Default)]
312pub struct Discovery {
313 pub sites: Vec<Site>,
314 pub rebuild_sites: Vec<Site>,
319 pub single_statement_bodies: Vec<String>,
322 pub test_modules: Vec<TestModule>,
324}
325
326pub fn discover(source: &str, first_id: u32) -> Result<Discovery> {
328 discover_with_errors(source, first_id, &[])
329}
330
331pub(crate) fn discover_with_errors(
332 source: &str,
333 first_id: u32,
334 error_values: &[&str],
335) -> Result<Discovery> {
336 let file = parse_source(source)?;
337 Ok(discover_parsed(source, &file, first_id, error_values))
338}
339
340pub(crate) fn parse_source(source: &str) -> Result<syn::File> {
341 if source.starts_with('\u{feff}') || (source.starts_with("#!") && !source.starts_with("#![")) {
344 anyhow::bail!("starts with a byte order mark or a `#!` line");
345 }
346 syn::parse_file(source).context("not parseable as a Rust source file")
347}
348
349pub(crate) fn discover_parsed(
350 source: &str,
351 file: &syn::File,
352 first_id: u32,
353 error_values: &[&str],
354) -> Discovery {
355 let local_macros = file
358 .items
359 .iter()
360 .filter_map(|item| match item {
361 syn::Item::Macro(m) => m.ident.as_ref().map(|i| i.to_string()),
362 _ => None,
363 })
364 .collect();
365 let mut finder = Finder {
366 source,
367 next_id: first_id,
368 found: Discovery::default(),
369 local_macros,
370 const_depth: 0,
371 error_values,
372 for_ranges: std::collections::HashSet::new(),
373 };
374 finder.visit_file(file);
375 finder.found
376}
377
378struct Finder<'s> {
379 error_values: &'s [&'s str],
380 local_macros: Vec<String>,
382 source: &'s str,
383 next_id: u32,
384 found: Discovery,
385 const_depth: usize,
387 for_ranges: std::collections::HashSet<usize>,
389}
390
391impl Finder<'_> {
392 fn function_sites(&mut self, sig: &syn::Signature, body: &syn::Block) {
395 if body.stmts.is_empty() {
396 return;
397 }
398 let braces = body.brace_token.span;
399 let (Some((_, start)), Some((end, _)), Some((sig_start, sig_end))) = (
400 self.range(braces.open()),
401 self.range(braces.close()),
402 self.range(sig.span()),
403 ) else {
404 return;
405 };
406 if !in_order(start, end) {
407 return;
408 }
409 let at = sig.span().start();
410 let text = self.source[sig_start..sig_end].to_string();
411 let (sole_expr, sole_plain) = match &body.stmts[..] {
412 [syn::Stmt::Expr(expr, None)] => {
413 let range = self.range(expr.span());
414 (range, range.filter(|_| does_nothing_else(expr)))
415 }
416 _ => (None, None),
417 };
418 let push = |finder: &mut Self, kind: SiteKind| {
419 finder.add(Site {
420 id: 0,
421 kind,
422 line: at.line,
423 column: at.column + 1,
424 start,
425 end,
426 text: text.clone(),
427 });
428 };
429 let name = sig.ident.to_string();
430 if let Some(option) = self.result_kind(&sig.output)
431 && !may_bypass_result_probe(body)
432 {
433 let kind = SiteKind::Return {
434 name: name.clone(),
435 option,
436 sole_expr,
437 };
438 push(self, kind);
439 }
440 let one_deletable_statement = matches!(sig.output, syn::ReturnType::Default)
443 && matches!(&body.stmts[..], [syn::Stmt::Expr(expr, Some(_))] if deletable(expr));
444 if sig.unsafety.is_some() {
445 return;
446 }
447 if one_deletable_statement {
448 self.found.single_statement_bodies.push(name);
449 return;
450 }
451 let written = sole_expr.map(|(from, to)| tokens_of(&self.source[from..to]));
452 let is_written = |value: &str| {
453 written
454 .as_deref()
455 .is_some_and(|text| text == tokens_of(value))
456 };
457 let probe_values = body_values_with_errors(&sig.output, self.error_values, false);
458 let probe_index = (probe_values.len() > 32).then(|| {
460 probe_values
461 .iter()
462 .map(String::as_str)
463 .collect::<HashSet<_>>()
464 });
465 for value in body_values_with_errors(&sig.output, self.error_values, true) {
466 let is_probe = probe_index.as_ref().map_or_else(
467 || probe_values.contains(&value),
468 |index| index.contains(value.as_str()),
469 );
470 if !is_probe && !is_written(&value) {
471 self.add_rebuild(Site {
472 id: NO_ID,
473 kind: SiteKind::Body {
474 name: name.clone(),
475 value,
476 sole_expr: sole_plain,
477 },
478 line: at.line,
479 column: at.column + 1,
480 start,
481 end,
482 text: text.clone(),
483 });
484 }
485 }
486 for value in probe_values {
487 if !is_written(&value) {
488 push(
489 self,
490 SiteKind::Body {
491 name: name.clone(),
492 value,
493 sole_expr: sole_plain,
494 },
495 );
496 }
497 }
498 }
499
500 fn result_kind(&self, output: &syn::ReturnType) -> Option<Option<String>> {
503 let syn::ReturnType::Type(_, ty) = output else {
504 return None;
505 };
506 match &**ty {
507 syn::Type::Path(p) if p.path.is_ident("bool") => Some(None),
509 syn::Type::Path(p)
510 if p.qself.is_none()
511 && p.path.segments.last().is_some_and(|s| {
512 s.ident == "Option"
513 && matches!(s.arguments, syn::PathArguments::AngleBracketed(_))
514 }) =>
515 {
516 match self
517 .range(ty.span())
518 .map(|(from, to)| &self.source[from..to])
519 {
520 Some(written) if !written.contains("impl ") => Some(Some(written.to_string())),
522 _ => None,
523 }
524 }
525 _ => None,
526 }
527 }
528 fn range(&self, span: Span) -> Option<(usize, usize)> {
529 let range = span.byte_range();
530 let located = !range.is_empty() && self.source.get(range.clone()).is_some();
533 located.then_some((range.start, range.end))
534 }
535
536 fn push(&mut self, kind: SiteKind, start: usize, end: usize, span: Span) {
537 let at = span.start();
538 self.add(Site {
539 id: 0,
540 kind,
541 line: at.line,
542 column: at.column + 1,
543 start,
544 end,
545 text: self.source[start..end].to_string(),
546 });
547 }
548
549 fn constant(&mut self, attrs: &[syn::Attribute], value: &syn::Expr) {
552 if !is_test_only(attrs) && !is_skipped(attrs) {
553 self.const_depth += 1;
554 self.visit_expr(value);
555 self.const_depth -= 1;
556 }
557 }
558
559 fn typed_constant(
560 &mut self,
561 attrs: &[syn::Attribute],
562 ty: &syn::Type,
563 value: Option<&syn::Expr>,
564 ) {
565 if !is_test_only(attrs) && !is_skipped(attrs) {
566 self.visit_type(ty);
567 if let Some(value) = value {
568 self.constant(&[], value);
569 }
570 }
571 }
572
573 fn add_rebuild(&mut self, mut site: Site) {
575 site.id = NO_ID;
576 self.found.rebuild_sites.push(site);
577 }
578
579 fn add(&mut self, mut site: Site) {
580 if self.const_depth > 0 {
581 self.add_rebuild(site);
582 } else {
583 site.id = self.next_id;
584 self.found.sites.push(site);
585 self.next_id += 1;
586 }
587 }
588}
589
590fn cmp_op(op: &syn::BinOp) -> Option<CmpOp> {
591 Some(match op {
592 syn::BinOp::Lt(_) => CmpOp::Lt,
593 syn::BinOp::Le(_) => CmpOp::Le,
594 syn::BinOp::Gt(_) => CmpOp::Gt,
595 syn::BinOp::Ge(_) => CmpOp::Ge,
596 syn::BinOp::Eq(_) => CmpOp::Eq,
597 syn::BinOp::Ne(_) => CmpOp::Ne,
598 _ => return None,
599 })
600}
601
602fn arith_op(op: &syn::BinOp) -> Option<(ArithOp, bool)> {
604 use syn::BinOp as B;
605 Some(match op {
606 B::Add(_) => (ArithOp::Add, false),
607 B::Sub(_) => (ArithOp::Sub, false),
608 B::Mul(_) => (ArithOp::Mul, false),
609 B::Div(_) => (ArithOp::Div, false),
610 B::Rem(_) => (ArithOp::Rem, false),
611 B::BitAnd(_) => (ArithOp::BitAnd, false),
612 B::BitOr(_) => (ArithOp::BitOr, false),
613 B::BitXor(_) => (ArithOp::BitXor, false),
614 B::Shl(_) => (ArithOp::Shl, false),
615 B::Shr(_) => (ArithOp::Shr, false),
616 B::AddAssign(_) => (ArithOp::Add, true),
617 B::SubAssign(_) => (ArithOp::Sub, true),
618 B::MulAssign(_) => (ArithOp::Mul, true),
619 B::DivAssign(_) => (ArithOp::Div, true),
620 B::RemAssign(_) => (ArithOp::Rem, true),
621 B::BitAndAssign(_) => (ArithOp::BitAnd, true),
622 B::BitOrAssign(_) => (ArithOp::BitOr, true),
623 B::BitXorAssign(_) => (ArithOp::BitXor, true),
624 B::ShlAssign(_) => (ArithOp::Shl, true),
625 B::ShrAssign(_) => (ArithOp::Shr, true),
626 _ => return None,
627 })
628}
629
630fn is_plain_place(expr: &syn::Expr) -> bool {
639 match expr {
640 syn::Expr::Path(e) => e.attrs.is_empty(),
641 syn::Expr::Field(e) => is_plain_place(&e.base),
642 syn::Expr::Unary(syn::ExprUnary {
643 op: syn::UnOp::Deref(_),
644 expr,
645 ..
646 }) => is_plain_place(expr),
647 syn::Expr::Paren(e) => is_plain_place(&e.expr),
648 syn::Expr::Group(e) => is_plain_place(&e.expr),
649 _ => false,
650 }
651}
652
653fn is_literal(expr: &syn::Expr) -> bool {
654 match expr {
655 syn::Expr::Paren(e) => is_literal(&e.expr),
656 syn::Expr::Group(e) => is_literal(&e.expr),
657 syn::Expr::Lit(_) => true,
658 syn::Expr::Unary(syn::ExprUnary {
659 op: syn::UnOp::Neg(_),
660 expr,
661 ..
662 }) => is_literal(expr),
663 _ => false,
664 }
665}
666
667fn in_order(earlier: usize, later: usize) -> bool {
671 earlier <= later }
673
674fn in_let_chain(expr: &syn::Expr) -> bool {
676 match expr {
677 syn::Expr::Let(_) => true,
678 syn::Expr::Binary(syn::ExprBinary {
679 op: syn::BinOp::And(_),
680 left,
681 right,
682 ..
683 }) => in_let_chain(left) || matches!(**right, syn::Expr::Let(_)),
684 _ => false,
685 }
686}
687
688const EXPR_MACROS: [&str; 18] = [
692 "assert_eq",
693 "assert_ne",
694 "debug_assert_eq",
695 "debug_assert_ne",
696 "vec",
697 "format",
698 "print",
699 "println",
700 "eprint",
701 "eprintln",
702 "write",
703 "writeln",
704 "panic",
705 "unreachable",
706 "todo",
707 "unimplemented",
708 "format_args",
709 "matches",
710];
711
712fn is_assign_op(op: &syn::BinOp) -> bool {
713 use syn::BinOp::*;
714 matches!(
715 op,
716 AddAssign(_)
717 | SubAssign(_)
718 | MulAssign(_)
719 | DivAssign(_)
720 | RemAssign(_)
721 | BitXorAssign(_)
722 | BitAndAssign(_)
723 | BitOrAssign(_)
724 | ShlAssign(_)
725 | ShrAssign(_)
726 )
727}
728
729fn int_literal(expr: &syn::Expr) -> Option<i128> {
730 match expr {
731 syn::Expr::Paren(e) => int_literal(&e.expr),
732 syn::Expr::Group(e) => int_literal(&e.expr),
733 syn::Expr::Lit(syn::ExprLit {
734 lit: syn::Lit::Int(lit),
735 ..
736 }) => lit.base10_parse().ok(),
737 syn::Expr::Unary(syn::ExprUnary {
738 op: syn::UnOp::Neg(_),
739 expr,
740 ..
741 }) => int_literal(expr).and_then(i128::checked_neg),
742 _ => None,
743 }
744}
745
746fn deletable(expr: &syn::Expr) -> bool {
748 match expr {
749 syn::Expr::Call(e) => e.attrs.is_empty(),
750 syn::Expr::MethodCall(e) => e.attrs.is_empty(),
751 syn::Expr::Assign(e) => e.attrs.is_empty(),
752 syn::Expr::Binary(e) => is_assign_op(&e.op),
754 syn::Expr::Try(e) => e.attrs.is_empty() && deletable_call(&e.expr),
755 syn::Expr::Await(e) => e.attrs.is_empty() && deletable_call(&e.base),
756 _ => false,
757 }
758}
759
760fn deletable_call(expr: &syn::Expr) -> bool {
761 match expr {
762 syn::Expr::Call(_) | syn::Expr::MethodCall(_) => true,
763 syn::Expr::Await(e) => deletable_call(&e.base),
764 _ => false,
765 }
766}
767
768fn has_ident(tokens: TokenStream, name: &str) -> bool {
769 tokens.into_iter().any(|tree| match tree {
770 TokenTree::Ident(ident) => ident == name,
771 TokenTree::Group(group) => has_ident(group.stream(), name),
772 _ => false,
773 })
774}
775
776pub const NO_ID: u32 = u32::MAX;
778
779#[derive(Debug, PartialEq, Eq, Clone)]
782pub struct NamedItem {
783 pub start: usize,
784 pub end: usize,
785 pub name: String,
786}
787
788pub fn named_items(source: &str) -> Vec<NamedItem> {
791 struct Namer {
792 path: Vec<String>,
793 items: Vec<NamedItem>,
794 }
795 impl Namer {
796 fn inside(&mut self, name: String, span: Option<Span>, visit: impl FnOnce(&mut Self)) {
797 self.path.push(name);
798 if let Some(span) = span {
799 let range = span.byte_range();
800 self.items.push(NamedItem {
801 start: range.start,
802 end: range.end,
803 name: self.path.join("::"),
804 });
805 }
806 visit(self);
807 self.path.pop();
808 }
809 }
810 impl<'ast> Visit<'ast> for Namer {
811 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
812 self.inside(node.ident.to_string(), None, |namer| {
813 visit::visit_item_mod(namer, node)
814 });
815 }
816 fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
817 self.inside(node.ident.to_string(), None, |namer| {
818 visit::visit_item_trait(namer, node)
819 });
820 }
821 fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
822 let of = squeezed(&node.self_ty.to_token_stream().to_string());
823 let name = match &node.trait_ {
824 Some((_, path, _)) => {
825 format!(
826 "<{} for {of}>",
827 squeezed(&path.to_token_stream().to_string())
828 )
829 }
830 None => of,
831 };
832 self.inside(name, None, |namer| visit::visit_item_impl(namer, node));
833 }
834 fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
835 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
836 visit::visit_item_fn(namer, node)
837 });
838 }
839 fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
840 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
841 visit::visit_impl_item_fn(namer, node)
842 });
843 }
844 fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
845 self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
846 visit::visit_trait_item_fn(namer, node)
847 });
848 }
849 fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
850 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
851 }
852 fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
853 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
854 }
855 fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
856 self.inside(node.ident.to_string(), Some(node.span()), |_| {});
857 }
858 }
859 let Ok(file) = syn::parse_file(source) else {
860 return vec![];
861 };
862 let mut namer = Namer {
863 path: vec![],
864 items: vec![],
865 };
866 namer.visit_file(&file);
867 namer.items
868}
869
870pub fn enclosing_item(items: &[NamedItem], offset: usize) -> &str {
872 items
873 .iter()
874 .filter(|item| item.start <= offset && offset < item.end)
875 .min_by_key(|item| item.end - item.start)
876 .map_or("", |item| item.name.as_str())
877}
878
879pub fn offset_of(source: &str, line: usize, column: usize) -> Option<usize> {
881 let start: usize = source
882 .split_inclusive('\n')
883 .take(line.checked_sub(1)?)
884 .map(str::len)
885 .sum();
886 let rest = source.get(start..)?;
887 let within = rest
888 .char_indices()
889 .nth(column.checked_sub(1)?)
890 .map_or(rest.len(), |(at, _)| at);
891 Some(start + within)
892}
893
894pub(crate) struct ItemIndex<'a>(Vec<(usize, &'a str)>);
896
897impl<'a> ItemIndex<'a> {
898 pub(crate) fn new(items: &'a [NamedItem]) -> Self {
899 use std::{cmp::Reverse, collections::BinaryHeap};
900
901 let mut starts: Vec<_> = items.iter().enumerate().collect();
902 starts.sort_unstable_by_key(|&(_, item)| item.start);
903 let mut boundaries: Vec<_> = items
904 .iter()
905 .flat_map(|item| [item.start, item.end])
906 .collect();
907 boundaries.sort_unstable();
908
909 let mut starts = starts.into_iter().peekable();
910 let mut active = BinaryHeap::new();
911 let mut intervals = Vec::new();
912 for boundary in boundaries {
913 while let Some(&(index, item)) =
914 starts.peek().filter(|(_, item)| item.start <= boundary)
915 {
916 starts.next();
917 active.push(Reverse((item.end - item.start, index)));
919 }
920 while active
921 .peek()
922 .is_some_and(|&Reverse((_, index))| items[index].end <= boundary)
923 {
924 active.pop();
925 }
926 let name = active
927 .peek()
928 .map_or("", |&Reverse((_, index))| items[index].name.as_str());
929 if intervals
930 .last()
931 .is_none_or(|&(_, previous)| previous != name)
932 {
933 intervals.push((boundary, name));
934 }
935 }
936 Self(intervals)
937 }
938
939 pub(crate) fn at(&self, offset: usize) -> &'a str {
940 let end = self.0.partition_point(|&(start, _)| start <= offset);
941 self.0[..end].last().map_or("", |&(_, name)| name)
942 }
943}
944
945#[cfg(test)]
946#[test]
947fn indexed_item_boundaries_agree_with_the_previous_search() {
948 let items = [
949 (6, 10, "first tie"),
950 (0, 16, "outer"),
951 (2, 6, "before tie"),
952 (6, 10, "second tie"),
953 (4, 13, "overlap"),
954 (7, 9, "inner"),
955 (7, 7, "empty"),
956 (17, 18, "after outer"),
957 ]
958 .map(|(start, end, name)| NamedItem {
959 start,
960 end,
961 name: name.to_string(),
962 });
963 let indexed = ItemIndex::new(&items);
964 for offset in 0..=20 {
965 assert_eq!(
966 indexed.at(offset),
967 enclosing_item(&items, offset),
968 "{offset}"
969 );
970 assert_eq!(ItemIndex::new(&[]).at(offset), "");
971 }
972}
973
974#[derive(Clone, PartialEq, Eq, Debug)]
976pub struct SourceMutant {
977 pub start: usize,
978 pub end: usize,
979 pub replacement: String,
980 pub what: String,
983 pub into: String,
984}
985
986pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
992 let SiteKind::Cmp { op, gap, .. } = &site.kind else {
993 return None;
994 };
995 let replacement = match op {
996 CmpOp::Le => "<",
997 CmpOp::Ge => ">",
998 _ => return None,
999 };
1000 Some(SourceMutant {
1001 start: gap.0,
1002 end: gap.1,
1003 replacement: format!(" {replacement} "),
1004 what: op.symbol().to_string(),
1005 into: replacement.to_string(),
1006 })
1007}
1008
1009pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
1010 let change =
1011 |start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
1012 start,
1013 end,
1014 replacement,
1015 what: what.to_string(),
1016 into: into.to_string(),
1017 };
1018 let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
1021 let operands = gap
1023 .0
1024 .checked_sub(site.start)
1025 .zip(gap.1.checked_sub(site.start))
1026 .and_then(|(left, right)| {
1027 Some((
1028 site.text.get(..left)?.trim_end(),
1029 site.text.get(right..)?.trim_start(),
1030 ))
1031 });
1032 match (binds, operands) {
1033 (std::cmp::Ordering::Less, Some((left, right))) => change(
1034 site.start,
1035 site.end,
1036 format!("({left} {to} {right})"),
1037 &from,
1038 &to,
1039 ),
1040 (std::cmp::Ordering::Greater, Some((left, right))) => change(
1041 site.start,
1042 site.end,
1043 format!("({left}) {to} ({right})"),
1044 &from,
1045 &to,
1046 ),
1047 _ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
1048 }
1049 };
1050 let same = std::cmp::Ordering::Equal;
1051 match &site.kind {
1052 SiteKind::Cmp { op, gap, .. } => {
1053 let others: &[CmpOp] = match op {
1054 CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
1055 CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
1056 CmpOp::Le => &[CmpOp::Gt],
1057 CmpOp::Ge => &[CmpOp::Lt],
1058 CmpOp::Eq => &[CmpOp::Ne],
1059 CmpOp::Ne => &[CmpOp::Eq],
1060 };
1061 others
1062 .iter()
1063 .map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
1064 .collect()
1065 }
1066 SiteKind::Logic { and, gap, .. } => {
1067 let (from, to, binds) = if *and {
1069 ("&&", "||", std::cmp::Ordering::Less)
1070 } else {
1071 ("||", "&&", std::cmp::Ordering::Greater)
1072 };
1073 vec![operator(gap, from.into(), to.into(), binds)]
1074 }
1075 SiteKind::Arith {
1076 op, assign, gap, ..
1077 } => {
1078 let eq = if *assign { "=" } else { "" };
1079 [Some(op.swapped()), op.second(*assign)]
1080 .into_iter()
1081 .flatten()
1082 .map(|other| {
1083 operator(
1084 gap,
1085 format!("{}{eq}", op.symbol()),
1086 format!("{}{eq}", other.symbol()),
1087 if *assign {
1089 same
1090 } else {
1091 other.binding().cmp(&op.binding())
1092 },
1093 )
1094 })
1095 .collect()
1096 }
1097 SiteKind::Not { bang, .. } => vec![change(bang.0, bang.1, String::new(), "!", "")],
1098 SiteKind::Neg { minus, .. } => vec![change(minus.0, minus.1, String::new(), "-", "")],
1099 SiteKind::Body { value, .. } => {
1100 vec![change(
1101 site.start,
1102 site.end,
1103 format!(" {value} "),
1104 "body",
1105 value,
1106 )]
1107 }
1108 SiteKind::Arm {
1109 pattern,
1110 guard,
1111 removal,
1112 } => vec![match guard {
1113 ArmGuard::None(_) => change(removal.0, removal.1, String::new(), "arm", pattern),
1114 ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
1115 }],
1116 SiteKind::Guard { can_be_false } => [true, false]
1117 .into_iter()
1118 .filter(|value| *value || *can_be_false)
1119 .map(|value| {
1120 change(
1121 site.start,
1122 site.end,
1123 value.to_string(),
1124 "guard",
1125 &value.to_string(),
1126 )
1127 })
1128 .collect(),
1129 SiteKind::Field { name, removal, .. } => {
1130 vec![change(removal.0, removal.1, String::new(), "field", name)]
1131 }
1132 SiteKind::Stmt => vec![change(site.start, site.end, String::new(), "statement", "")],
1133 SiteKind::Range { inclusive, gap, .. } => {
1135 let (from, to) = if *inclusive {
1136 ("..=", "..")
1137 } else {
1138 ("..", "..=")
1139 };
1140 vec![change(gap.0, gap.1, to.to_string(), from, to)]
1141 }
1142 SiteKind::Return { .. } | SiteKind::MinMax { .. } => vec![],
1143 }
1144}
1145
1146pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
1148 let gap = match &site.kind {
1149 SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
1150 gap
1151 }
1152 _ => return,
1153 };
1154 if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
1155 let span = operator.span().byte_range();
1156 for mutant in mutants {
1157 mutant.start = gap.0 + span.start;
1158 mutant.end = gap.0 + span.end;
1159 mutant.replacement.clone_from(&mutant.into);
1160 }
1161 }
1162}
1163
1164pub fn iterator_values(output: &syn::ReturnType) -> Vec<String> {
1167 let syn::ReturnType::Type(_, ty) = output else {
1168 return vec![];
1169 };
1170 let syn::Type::ImplTrait(opaque) = &**ty else {
1171 return vec![];
1172 };
1173 iterator_type_values(opaque, &[], false)
1174}
1175
1176fn iterator_type_values(
1177 opaque: &syn::TypeImplTrait,
1178 error_values: &[&str],
1179 extended: bool,
1180) -> Vec<String> {
1181 let item = opaque.bounds.iter().find_map(|bound| {
1182 let syn::TypeParamBound::Trait(bound) = bound else {
1183 return None;
1184 };
1185 let last = bound.path.segments.last()?;
1186 let syn::PathArguments::AngleBracketed(list) = &last.arguments else {
1187 return None;
1188 };
1189 (last.ident == "Iterator").then_some(())?;
1190 list.args.iter().find_map(|arg| match arg {
1191 syn::GenericArgument::AssocType(item) if item.ident == "Item" => Some(&item.ty),
1192 _ => None,
1193 })
1194 });
1195 let Some(item) = item else {
1196 return vec![];
1197 };
1198 if !extended && has_ident(item.to_token_stream(), "impl") {
1199 return vec!["::core::iter::empty()".to_string()];
1200 }
1201 let mut values = vec!["::core::iter::empty()".to_string()];
1202 values.extend(
1203 values_of(item, error_values, extended)
1204 .iter()
1205 .map(|value| format!("::core::iter::once({value})")),
1206 );
1207 values
1208}
1209
1210fn squeezed(text: &str) -> String {
1212 text.chars().filter(|c| !c.is_whitespace()).collect()
1213}
1214
1215fn tokens_of(text: &str) -> String {
1218 match text.parse::<TokenStream>() {
1219 Ok(tokens) => tokens.to_string(),
1220 Err(_) => text.to_string(),
1221 }
1222}
1223
1224fn may_bypass_result_probe(body: &syn::Block) -> bool {
1227 struct EarlyExit(bool);
1228
1229 impl<'ast> Visit<'ast> for EarlyExit {
1230 fn visit_expr(&mut self, expr: &'ast syn::Expr) {
1231 if self.0 {
1232 return;
1233 }
1234 match expr {
1235 syn::Expr::Return(_) | syn::Expr::Try(_) | syn::Expr::Verbatim(_) => self.0 = true,
1236 syn::Expr::Async(_) | syn::Expr::Closure(_) | syn::Expr::Const(_) => {}
1237 _ => visit::visit_expr(self, expr),
1238 }
1239 }
1240
1241 fn visit_macro(&mut self, _: &'ast syn::Macro) {
1242 self.0 = true;
1243 }
1244
1245 fn visit_item(&mut self, _: &'ast syn::Item) {}
1246 fn visit_pat(&mut self, _: &'ast syn::Pat) {}
1247 fn visit_type(&mut self, _: &'ast syn::Type) {}
1248 }
1249
1250 let mut exits = EarlyExit(false);
1251 exits.visit_block(body);
1252 exits.0
1253}
1254
1255fn does_nothing_else(expr: &syn::Expr) -> bool {
1258 struct Effects(bool);
1259 impl<'ast> Visit<'ast> for Effects {
1260 fn visit_expr(&mut self, expr: &'ast syn::Expr) {
1261 match expr {
1262 syn::Expr::Binary(_)
1263 | syn::Expr::Unary(_)
1264 | syn::Expr::Paren(_)
1265 | syn::Expr::Group(_)
1266 | syn::Expr::Path(_)
1267 | syn::Expr::Lit(_)
1268 | syn::Expr::Field(_)
1269 | syn::Expr::Reference(_)
1270 | syn::Expr::Cast(_)
1271 | syn::Expr::Tuple(_) => syn::visit::visit_expr(self, expr),
1272 _ => self.0 = true,
1273 }
1274 }
1275 fn visit_bin_op(&mut self, op: &'ast syn::BinOp) {
1276 use syn::BinOp::*;
1277 if !matches!(
1278 op,
1279 Add(_)
1280 | Sub(_)
1281 | Mul(_)
1282 | Div(_)
1283 | Rem(_)
1284 | And(_)
1285 | Or(_)
1286 | BitXor(_)
1287 | BitAnd(_)
1288 | BitOr(_)
1289 | Shl(_)
1290 | Shr(_)
1291 | Eq(_)
1292 | Lt(_)
1293 | Le(_)
1294 | Ne(_)
1295 | Ge(_)
1296 | Gt(_)
1297 ) {
1298 self.0 = true; }
1300 }
1301 }
1302 let mut effects = Effects(false);
1303 effects.visit_expr(expr);
1304 !effects.0
1305}
1306
1307pub fn body_values(output: &syn::ReturnType) -> Vec<String> {
1310 body_values_with_errors(output, &[], false)
1311}
1312
1313fn body_values_with_errors(
1314 output: &syn::ReturnType,
1315 error_values: &[&str],
1316 extended: bool,
1317) -> Vec<String> {
1318 match output {
1319 syn::ReturnType::Default => vec!["()".to_string()],
1320 syn::ReturnType::Type(_, ty) => {
1321 if !extended && has_ident(ty.to_token_stream(), "impl") {
1324 return vec![];
1325 }
1326 values_of(ty, error_values, extended)
1327 }
1328 }
1329}
1330
1331fn product(parts: &[Vec<String>], format: impl Fn(&[&str]) -> String) -> Vec<String> {
1332 if parts.iter().any(Vec::is_empty) {
1333 return vec![];
1334 }
1335 let mut positions = vec![0; parts.len()];
1336 let mut row: Vec<_> = parts.iter().map(|part| part[0].as_str()).collect();
1337 let mut results = vec![];
1338 loop {
1339 results.push(format(&row));
1340 let Some(next) = (0..parts.len())
1341 .rev()
1342 .find(|&i| positions[i] + 1 < parts[i].len())
1343 else {
1344 return results;
1345 };
1346 positions[next] += 1;
1347 row[next] = &parts[next][positions[next]];
1348 for i in next + 1..parts.len() {
1349 positions[i] = 0;
1350 row[i] = &parts[i][0];
1351 }
1352 }
1353}
1354
1355fn values_of(ty: &syn::Type, error_values: &[&str], extended: bool) -> Vec<String> {
1356 let each = |inner: &syn::Type, wrap: &dyn Fn(&str) -> String| -> Vec<String> {
1357 values_of(inner, error_values, extended)
1358 .iter()
1359 .map(|v| wrap(v))
1360 .collect()
1361 };
1362 match ty {
1363 syn::Type::Paren(t) => values_of(&t.elem, error_values, extended),
1364 syn::Type::Group(t) => values_of(&t.elem, error_values, extended),
1365 syn::Type::Never(_) => vec![],
1366 syn::Type::ImplTrait(opaque) => iterator_type_values(opaque, error_values, extended),
1367 syn::Type::Tuple(t) => {
1369 let parts: Vec<Vec<String>> = t
1370 .elems
1371 .iter()
1372 .map(|ty| values_of(ty, error_values, extended))
1373 .collect();
1374 product(&parts, |row| match row {
1375 [one] => format!("({one},)"),
1376 _ => format!("({})", row.join(", ")),
1377 })
1378 }
1379 syn::Type::Array(t) => {
1380 let len = t.len.to_token_stream().to_string();
1381 each(&t.elem, &|v| format!("[{v}; {len}]"))
1382 }
1383 syn::Type::Reference(t) => match &*t.elem {
1384 syn::Type::Path(p) if p.path.is_ident("str") && t.mutability.is_none() => {
1385 vec!["\"\"".to_string(), "\"xyzzy\"".to_string()]
1386 }
1387 syn::Type::Slice(slice) => {
1388 let mut values = vec!["Vec::leak(Vec::new())".to_string()];
1389 values.extend(each(&slice.elem, &|v| format!("Vec::leak(vec![{v}])")));
1390 values
1391 }
1392 inner => each(inner, &|v| format!("Box::leak(Box::new({v}))")),
1393 },
1394 syn::Type::Path(p) if p.qself.is_none() => {
1395 let Some(last) = p.path.segments.last() else {
1396 return vec!["Default::default()".to_string()];
1397 };
1398 let mut bare = p.path.clone();
1400 if let Some(segment) = bare.segments.last_mut() {
1401 segment.arguments = syn::PathArguments::None;
1402 }
1403 let bare = squeezed(&bare.to_token_stream().to_string());
1404 let arguments: Vec<&syn::Type> = match &last.arguments {
1405 syn::PathArguments::AngleBracketed(list) => list
1406 .args
1407 .iter()
1408 .filter_map(|arg| match arg {
1409 syn::GenericArgument::Type(ty) => Some(ty),
1410 _ => None,
1411 })
1412 .collect(),
1413 _ => vec![],
1414 };
1415 let name = last.ident.to_string();
1416 let texts = |list: &[&str]| list.iter().map(|v| v.to_string()).collect::<Vec<_>>();
1417 let one = |text: String| "1.try_into().unwrap()".replace('1', &text);
1418 match (name.as_str(), &arguments[..]) {
1419 ("bool", []) => texts(&["true", "false"]),
1420 ("i8" | "i16" | "i32" | "i64" | "i128" | "isize", []) => texts(&["0", "1", "-1"]),
1421 ("u8" | "u16" | "u32" | "u64" | "u128" | "usize", []) => texts(&["0", "1"]),
1422 ("f32" | "f64", []) => texts(&["0.0", "1.0", "-1.0"]),
1423 (
1424 "NonZeroI8" | "NonZeroI16" | "NonZeroI32" | "NonZeroI64" | "NonZeroI128"
1425 | "NonZeroIsize",
1426 [],
1427 ) => vec![one("1".into()), one("(-1)".into())],
1428 (
1429 "NonZeroU8" | "NonZeroU16" | "NonZeroU32" | "NonZeroU64" | "NonZeroU128"
1430 | "NonZeroUsize",
1431 [],
1432 ) => vec![one("1".into())],
1433 ("NonZero", [inner]) => {
1434 let unsigned = squeezed(&inner.to_token_stream().to_string()).starts_with('u');
1435 let mut values = vec![one("1".into())];
1436 if !unsigned {
1437 values.push(one("(-1)".into()));
1438 }
1439 values
1440 }
1441 ("String", []) => texts(&["String::new()", "\"xyzzy\".into()"]),
1442 ("Result", arguments) => {
1443 let mut values = match arguments.first() {
1444 Some(ok) => each(ok, &|v| format!("Ok({v})")),
1445 None => vec!["Ok(Default::default())".to_string()],
1447 };
1448 values.extend(error_values.iter().map(|expression| {
1449 let end = if expression.rsplit('\n').next().unwrap_or("").contains("//") {
1451 "\n"
1452 } else {
1453 ""
1454 };
1455 format!("Err({expression}{end})")
1456 }));
1457 values
1458 }
1459 ("Option", [inner]) => {
1460 let mut values = vec!["None".to_string()];
1461 values.extend(each(inner, &|v| format!("Some({v})")));
1462 values
1463 }
1464 ("Vec", [inner]) => {
1465 let mut values = vec!["vec![]".to_string()];
1466 values.extend(each(inner, &|v| format!("vec![{v}]")));
1467 values
1468 }
1469 ("Box" | "Rc" | "Arc" | "Cell" | "RefCell" | "Mutex", [inner]) => {
1470 each(inner, &|v| format!("{bare}::new({v})"))
1471 }
1472 ("BinaryHeap" | "BTreeSet" | "HashSet" | "LinkedList" | "VecDeque", [inner]) => {
1473 let mut values = vec![format!("{bare}::new()")];
1474 values.extend(each(inner, &|v| format!("{bare}::from_iter([{v}])")));
1475 values
1476 }
1477 ("BTreeMap" | "HashMap", [key, value]) => {
1478 let mut values = vec![format!("{bare}::new()")];
1479 values.extend(product(
1480 &[
1481 values_of(key, error_values, extended),
1482 values_of(value, error_values, extended),
1483 ],
1484 |row| format!("{bare}::from_iter([({})])", row.join(", ")),
1485 ));
1486 values
1487 }
1488 ("Cow", [inner]) => {
1489 let borrowed: syn::Type = syn::parse_quote!(&#inner);
1490 values_of(&borrowed, error_values, extended)
1491 .iter()
1492 .flat_map(|v| {
1493 [
1494 format!("{bare}::Borrowed({v})"),
1495 format!("{bare}::Owned({v}.to_owned())"),
1496 ]
1497 })
1498 .collect()
1499 }
1500 ("HttpResponse", []) => vec![format!("{bare}::Ok().finish()")],
1501 (_, [inner]) if extended => {
1502 let mut values = vec![format!("{bare}::new()")];
1503 for value in values_of(inner, error_values, extended) {
1504 values.extend([
1505 format!("{bare}::from_iter([{value}])"),
1506 format!("{bare}::new({value})"),
1507 format!("{bare}::from({value})"),
1508 ]);
1509 }
1510 values
1511 }
1512 _ => vec!["Default::default()".to_string()],
1513 }
1514 }
1515 _ => vec!["Default::default()".to_string()],
1516 }
1517}
1518
1519pub(crate) fn is_skipped(attrs: &[syn::Attribute]) -> bool {
1522 fn marked(meta: &syn::Meta) -> bool {
1523 let path = meta.path();
1524 if path.segments.len() == 2
1525 && path.segments[0].ident == "mutants"
1526 && path.segments[1].ident == "skip"
1527 {
1528 return true;
1529 }
1530 if path.is_ident("cfg_attr")
1531 && let syn::Meta::List(list) = meta
1532 && let Ok(parts) = list.parse_args_with(
1533 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1534 )
1535 {
1536 return parts.iter().skip(1).any(marked);
1537 }
1538 false
1539 }
1540
1541 attrs.iter().any(|attr| marked(&attr.meta))
1542}
1543
1544pub(crate) fn cfg_possible_without_test(meta: &syn::Meta, desired: bool) -> bool {
1546 if meta.path().is_ident("test") {
1547 return !desired;
1548 }
1549 let syn::Meta::List(list) = meta else {
1550 return true;
1551 };
1552 let Ok(parts) = list.parse_args_with(
1553 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1554 ) else {
1555 return true;
1556 };
1557 if list.path.is_ident("not") && parts.len() == 1 {
1558 return cfg_possible_without_test(&parts[0], !desired);
1559 }
1560 if list.path.is_ident("all") || list.path.is_ident("any") {
1561 return if list.path.is_ident("all") == desired {
1562 parts
1563 .iter()
1564 .all(|part| cfg_possible_without_test(part, desired))
1565 } else {
1566 parts
1567 .iter()
1568 .any(|part| cfg_possible_without_test(part, desired))
1569 };
1570 }
1571 true
1572}
1573
1574fn cfg_value(meta: &syn::Meta, features: &BTreeSet<String>) -> Option<bool> {
1577 match meta {
1578 syn::Meta::NameValue(pair) if pair.path.is_ident("feature") => match &pair.value {
1579 syn::Expr::Lit(syn::ExprLit {
1580 lit: syn::Lit::Str(name),
1581 ..
1582 }) => Some(features.contains(&name.value())),
1583 _ => None,
1584 },
1585 syn::Meta::List(list) => {
1586 let parts = list
1587 .parse_args_with(
1588 syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1589 )
1590 .ok()?;
1591 let mut values = parts.iter().map(|part| cfg_value(part, features));
1592 if list.path.is_ident("not") && parts.len() == 1 {
1593 values.next()?.map(|value| !value)
1594 } else if list.path.is_ident("all") {
1595 values
1597 .try_fold(Some(true), |all, value| match (all, value) {
1598 (_, Some(false)) => Err(()),
1599 (Some(true), Some(true)) => Ok(Some(true)),
1600 _ => Ok(None),
1601 })
1602 .unwrap_or(Some(false))
1603 } else if list.path.is_ident("any") {
1604 values
1605 .try_fold(Some(false), |any, value| match (any, value) {
1606 (_, Some(true)) => Err(()),
1607 (Some(false), Some(false)) => Ok(Some(false)),
1608 _ => Ok(None),
1609 })
1610 .unwrap_or(Some(true))
1611 } else {
1612 None
1613 }
1614 }
1615 _ => None,
1616 }
1617}
1618
1619fn cfg_is_off(attrs: &[syn::Attribute], features: &BTreeSet<String>) -> bool {
1620 attrs.iter().any(|attr| {
1621 attr.path().is_ident("cfg")
1622 && attr
1623 .parse_args::<syn::Meta>()
1624 .is_ok_and(|meta| cfg_value(&meta, features) == Some(false))
1625 })
1626}
1627
1628pub(crate) fn inactive_ranges(
1631 source: &str,
1632 file: &syn::File,
1633 features: &BTreeSet<String>,
1634) -> Vec<(usize, usize)> {
1635 struct Inactive<'a> {
1636 source: &'a str,
1637 features: &'a BTreeSet<String>,
1638 found: Vec<(usize, usize)>,
1639 }
1640 impl Inactive<'_> {
1641 fn off(&mut self, attrs: &[syn::Attribute], span: Span) -> bool {
1643 if !cfg_is_off(attrs, self.features) {
1644 return false;
1645 }
1646 let range = span.byte_range();
1647 if self.source.get(range.clone()).is_some() {
1648 self.found.push((range.start, range.end));
1649 }
1650 true
1651 }
1652 }
1653 macro_rules! nodes {
1654 ($($visit:ident, $default:path, $node:ty;)*) => {
1655 impl<'ast> Visit<'ast> for Inactive<'_> {
1656 $(fn $visit(&mut self, node: &'ast $node) {
1657 if !self.off(&node.attrs, node.span()) {
1658 $default(self, node);
1659 }
1660 })*
1661 fn visit_item(&mut self, node: &'ast syn::Item) {
1662 if !self.off(item_attrs(node), node.span()) {
1663 visit::visit_item(self, node);
1664 }
1665 }
1666 fn visit_impl_item(&mut self, node: &'ast syn::ImplItem) {
1667 let attrs = match node {
1668 syn::ImplItem::Const(item) => &item.attrs[..],
1669 syn::ImplItem::Fn(item) => &item.attrs,
1670 syn::ImplItem::Type(item) => &item.attrs,
1671 syn::ImplItem::Macro(item) => &item.attrs,
1672 _ => &[],
1673 };
1674 if !self.off(attrs, node.span()) {
1675 visit::visit_impl_item(self, node);
1676 }
1677 }
1678 fn visit_trait_item(&mut self, node: &'ast syn::TraitItem) {
1679 let attrs = match node {
1680 syn::TraitItem::Const(item) => &item.attrs[..],
1681 syn::TraitItem::Fn(item) => &item.attrs,
1682 syn::TraitItem::Type(item) => &item.attrs,
1683 syn::TraitItem::Macro(item) => &item.attrs,
1684 _ => &[],
1685 };
1686 if !self.off(attrs, node.span()) {
1687 visit::visit_trait_item(self, node);
1688 }
1689 }
1690 }
1691 };
1692 }
1693 nodes! {
1694 visit_local, visit::visit_local, syn::Local;
1695 visit_arm, visit::visit_arm, syn::Arm;
1696 visit_field_value, visit::visit_field_value, syn::FieldValue;
1697 visit_stmt_macro, visit::visit_stmt_macro, syn::StmtMacro;
1698 visit_expr_block, visit::visit_expr_block, syn::ExprBlock;
1699 visit_expr_if, visit::visit_expr_if, syn::ExprIf;
1700 visit_expr_call, visit::visit_expr_call, syn::ExprCall;
1701 visit_expr_method_call, visit::visit_expr_method_call, syn::ExprMethodCall;
1702 visit_expr_macro, visit::visit_expr_macro, syn::ExprMacro;
1703 visit_expr_match, visit::visit_expr_match, syn::ExprMatch;
1704 visit_expr_assign, visit::visit_expr_assign, syn::ExprAssign;
1705 visit_expr_return, visit::visit_expr_return, syn::ExprReturn;
1706 visit_expr_for_loop, visit::visit_expr_for_loop, syn::ExprForLoop;
1707 visit_expr_while, visit::visit_expr_while, syn::ExprWhile;
1708 visit_expr_loop, visit::visit_expr_loop, syn::ExprLoop;
1709 visit_expr_unsafe, visit::visit_expr_unsafe, syn::ExprUnsafe;
1710 visit_expr_binary, visit::visit_expr_binary, syn::ExprBinary;
1711 }
1712 if cfg_is_off(&file.attrs, features) {
1713 return vec![(0, source.len())];
1714 }
1715 let mut inactive = Inactive {
1716 source,
1717 features,
1718 found: vec![],
1719 };
1720 inactive.visit_file(file);
1721 inactive.found
1722}
1723
1724pub(crate) fn reach(expr: &str) -> Option<(crate::plan::Reach, Option<u32>)> {
1729 use crate::plan::Reach;
1730 fn literal(expr: &syn::Expr) -> Option<i128> {
1731 match expr {
1732 syn::Expr::Lit(syn::ExprLit {
1733 lit: syn::Lit::Int(integer),
1734 ..
1735 }) => integer.base10_parse().ok(),
1736 syn::Expr::Paren(inner) => literal(&inner.expr),
1737 _ => None,
1738 }
1739 }
1740 let mut expr = &syn::parse_str::<syn::Expr>(expr).ok()?;
1741 while let syn::Expr::Paren(inner) = expr {
1742 expr = &inner.expr;
1743 }
1744 let syn::Expr::Binary(binary) = expr else {
1745 return None;
1746 };
1747 let (left, right) = (literal(&binary.left), literal(&binary.right));
1748 let power_of_two = |k: i128| k >= 2 && k & (k - 1) == 0;
1749 let reach = match binary.op {
1751 syn::BinOp::Mul(_) => left
1752 .or(right)
1753 .filter(|k| power_of_two(*k))
1754 .map(Reach::Multiples),
1755 syn::BinOp::Shl(_) => {
1756 let bits = right.filter(|bits| (1..=100).contains(bits))?;
1757 return Some((Reach::Multiples(1 << bits), Some(bits as u32)));
1758 }
1759 syn::BinOp::BitAnd(_) => left.or(right).filter(|mask| *mask >= 0).map(Reach::Bits),
1760 syn::BinOp::Rem(_) => right.filter(|limit| *limit >= 1).map(Reach::Below),
1761 _ => None,
1762 };
1763 reach.map(|reach| (reach, None))
1764}
1765
1766pub(crate) fn test_only_ranges(source: &str, file: &syn::File) -> Vec<(usize, usize)> {
1769 if is_test_only(&file.attrs) {
1770 return vec![(0, source.len())];
1771 }
1772 let mut found = vec![];
1773 for item in &file.items {
1774 test_only_items(source, item, &mut found);
1775 }
1776 found
1777}
1778
1779fn test_only_items(source: &str, item: &syn::Item, found: &mut Vec<(usize, usize)>) {
1780 let mut note = |attrs: &[syn::Attribute], span: Span| {
1781 let test_only = is_test_only(attrs);
1782 let range = span.byte_range();
1783 if test_only && source.get(range.clone()).is_some() {
1784 found.push((range.start, range.end));
1785 }
1786 test_only
1787 };
1788 if note(item_attrs(item), item.span()) {
1789 return;
1790 }
1791 match item {
1792 syn::Item::Mod(module) => {
1793 for inner in module.content.iter().flat_map(|(_, items)| items) {
1794 test_only_items(source, inner, found);
1795 }
1796 }
1797 syn::Item::Impl(block) => {
1798 for inner in &block.items {
1799 if let syn::ImplItem::Fn(function) = inner {
1800 note(&function.attrs, inner.span());
1801 }
1802 }
1803 }
1804 _ => {}
1805 }
1806}
1807
1808pub(crate) fn same_tokens(a: &str, b: &str) -> Option<bool> {
1811 fn tokens(stream: TokenStream, out: &mut Vec<String>) {
1812 let mut trees = stream.into_iter().peekable();
1813 while let Some(tree) = trees.next() {
1814 match tree {
1815 TokenTree::Punct(hash) if hash.as_char() == '#' => {
1817 let bang =
1818 matches!(trees.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '!')
1819 .then(|| trees.next());
1820 let is_doc = matches!(trees.peek(), Some(TokenTree::Group(group))
1821 if group.delimiter() == proc_macro2::Delimiter::Bracket
1822 && matches!(group.stream().into_iter().next(),
1823 Some(TokenTree::Ident(name)) if name == "doc"));
1824 if is_doc {
1825 trees.next();
1826 continue;
1827 }
1828 out.push("#".to_string());
1829 if bang.is_some() {
1830 out.push("!".to_string());
1831 }
1832 }
1833 TokenTree::Group(group) => {
1834 out.push(format!("{:?}(", group.delimiter()));
1835 tokens(group.stream(), out);
1836 out.push(")".to_string());
1837 }
1838 other => out.push(other.to_string()),
1839 }
1840 }
1841 }
1842 let lex = |text: &str| -> Option<Vec<String>> {
1843 let mut out = vec![];
1844 tokens(text.parse::<TokenStream>().ok()?, &mut out);
1845 Some(out)
1846 };
1847 Some(lex(a)? == lex(b)?)
1848}
1849
1850fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
1851 match item {
1852 syn::Item::Const(item) => &item.attrs,
1853 syn::Item::Enum(item) => &item.attrs,
1854 syn::Item::ExternCrate(item) => &item.attrs,
1855 syn::Item::Fn(item) => &item.attrs,
1856 syn::Item::ForeignMod(item) => &item.attrs,
1857 syn::Item::Impl(item) => &item.attrs,
1858 syn::Item::Macro(item) => &item.attrs,
1859 syn::Item::Mod(item) => &item.attrs,
1860 syn::Item::Static(item) => &item.attrs,
1861 syn::Item::Struct(item) => &item.attrs,
1862 syn::Item::Trait(item) => &item.attrs,
1863 syn::Item::TraitAlias(item) => &item.attrs,
1864 syn::Item::Type(item) => &item.attrs,
1865 syn::Item::Union(item) => &item.attrs,
1866 syn::Item::Use(item) => &item.attrs,
1867 _ => &[],
1868 }
1869}
1870
1871pub(crate) fn is_test_only(attrs: &[syn::Attribute]) -> bool {
1873 attrs.iter().any(|attr| {
1874 let path = attr.path();
1875 if path.segments.last().is_some_and(|s| s.ident == "test") {
1876 return true;
1877 }
1878 path.is_ident("cfg")
1879 && attr
1880 .parse_args::<syn::Meta>()
1881 .is_ok_and(|meta| !cfg_possible_without_test(&meta, true))
1882 })
1883}
1884
1885impl<'ast> Visit<'ast> for Finder<'_> {
1886 fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
1887 fn visit_local(&mut self, node: &'ast syn::Local) {
1888 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1889 visit::visit_local(self, node);
1890 }
1891 }
1892 fn visit_pat(&mut self, node: &'ast syn::Pat) {
1893 if let syn::Pat::Type(binding) = node {
1894 self.visit_type(&binding.ty);
1895 }
1896 }
1897 fn visit_type_macro(&mut self, _: &'ast syn::TypeMacro) {}
1898 fn visit_type_array(&mut self, node: &'ast syn::TypeArray) {
1899 self.visit_type(&node.elem);
1900 self.constant(&[], &node.len);
1901 }
1902 fn visit_const_param(&mut self, node: &'ast syn::ConstParam) {
1903 self.visit_type(&node.ty);
1904 if let Some(default) = &node.default {
1905 self.constant(&node.attrs, default);
1906 }
1907 }
1908 fn visit_generic_argument(&mut self, node: &'ast syn::GenericArgument) {
1909 match node {
1910 syn::GenericArgument::Const(value) => self.constant(&[], value),
1911 _ => visit::visit_generic_argument(self, node),
1912 }
1913 }
1914 fn visit_variant(&mut self, node: &'ast syn::Variant) {
1915 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1916 self.visit_fields(&node.fields);
1917 if let Some((_, value)) = &node.discriminant {
1918 self.constant(&[], value);
1919 }
1920 }
1921 }
1922 fn visit_file(&mut self, node: &'ast syn::File) {
1923 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1924 visit::visit_file(self, node);
1925 }
1926 }
1927 fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
1928 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1929 visit::visit_item_enum(self, node);
1930 }
1931 }
1932 fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
1933 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1934 visit::visit_item_struct(self, node);
1935 }
1936 }
1937 fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
1938 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1939 visit::visit_item_union(self, node);
1940 }
1941 }
1942 fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
1943 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1944 visit::visit_item_trait(self, node);
1945 }
1946 }
1947 fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
1948 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1949 visit::visit_item_type(self, node);
1950 }
1951 }
1952 fn visit_field(&mut self, node: &'ast syn::Field) {
1953 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1954 visit::visit_field(self, node);
1955 }
1956 }
1957 fn visit_impl_item_type(&mut self, node: &'ast syn::ImplItemType) {
1958 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1959 visit::visit_impl_item_type(self, node);
1960 }
1961 }
1962 fn visit_trait_item_type(&mut self, node: &'ast syn::TraitItemType) {
1963 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1964 visit::visit_trait_item_type(self, node);
1965 }
1966 }
1967 fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
1968 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1969 }
1970 fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
1971 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1972 }
1973 fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
1974 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1975 }
1976 fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
1977 self.typed_constant(
1978 &node.attrs,
1979 &node.ty,
1980 node.default.as_ref().map(|(_, value)| value),
1981 );
1982 }
1983 fn visit_expr_const(&mut self, node: &'ast syn::ExprConst) {
1984 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1985 self.const_depth += 1;
1986 self.visit_block(&node.block);
1987 self.const_depth -= 1;
1988 }
1989 }
1990
1991 fn visit_macro(&mut self, node: &'ast syn::Macro) {
1992 let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
1993 return;
1994 };
1995 if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
1996 return;
1997 }
1998 if name == "matches" {
1999 let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
2001 let expr: syn::Expr = input.parse()?;
2002 input.parse::<proc_macro2::TokenStream>()?;
2003 Ok(expr)
2004 });
2005 if let Ok(expr) = scrutinee {
2006 self.visit_expr(&expr);
2007 }
2008 return;
2009 }
2010 type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
2011 if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
2014 for arg in &args {
2015 self.visit_expr(arg);
2018 }
2019 }
2020 }
2021
2022 fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
2023 self.visit_expr(&node.expr);
2024 self.constant(&node.attrs, &node.len);
2025 }
2026
2027 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
2028 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2030 if node.content.is_none() {
2031 let path = node.attrs.iter().find_map(|attr| match &attr.meta {
2032 syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
2033 syn::Expr::Lit(syn::ExprLit {
2034 lit: syn::Lit::Str(s),
2035 ..
2036 }) => Some(s.value()),
2037 _ => None,
2038 },
2039 _ => None,
2040 });
2041 self.found.test_modules.push(TestModule {
2042 name: node.ident.to_string(),
2043 path,
2044 });
2045 }
2046 return;
2047 }
2048 visit::visit_item_mod(self, node);
2049 }
2050
2051 fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
2052 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2053 let constant = node.sig.constness.is_some() as usize;
2055 self.const_depth += constant;
2056 self.function_sites(&node.sig, &node.block);
2057 visit::visit_item_fn(self, node);
2058 self.const_depth -= constant;
2059 }
2060 }
2061
2062 fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
2063 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2064 let constant = node.sig.constness.is_some() as usize;
2066 self.const_depth += constant;
2067 self.function_sites(&node.sig, &node.block);
2068 visit::visit_impl_item_fn(self, node);
2069 self.const_depth -= constant;
2070 }
2071 }
2072
2073 fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
2074 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2075 let constant = node.sig.constness.is_some() as usize;
2076 self.const_depth += constant;
2077 if let Some(body) = &node.default {
2078 self.function_sites(&node.sig, body);
2079 }
2080 visit::visit_trait_item_fn(self, node);
2081 self.const_depth -= constant;
2082 }
2083 }
2084
2085 fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
2086 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2087 visit::visit_item_impl(self, node);
2088 }
2089 }
2090
2091 fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
2092 if node.constness.is_none() {
2093 visit::visit_expr_closure(self, node);
2094 }
2095 }
2096
2097 fn visit_block(&mut self, node: &'ast syn::Block) {
2098 for stmt in &node.stmts {
2099 if let syn::Stmt::Expr(expr, Some(semi)) = stmt
2100 && deletable(expr)
2101 && let (Some((start, _)), Some((_, end))) =
2102 (self.range(expr.span()), self.range(semi.span()))
2103 && in_order(start, end)
2104 {
2105 self.push(SiteKind::Stmt, start, end, expr.span());
2106 }
2107 }
2108 visit::visit_block(self, node);
2109 }
2110
2111 fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
2112 let name = node.method.to_string();
2113 if (name == "max" || name == "min")
2114 && node.args.len() == 1
2115 && node.turbofish.is_none()
2116 && node.attrs.is_empty()
2117 && let (
2118 Some((start, receiver_end)),
2119 Some((argument_start, argument_end)),
2120 Some((_, end)),
2121 ) = (
2122 self.range(node.receiver.span()),
2123 self.range(node.args[0].span()),
2124 self.range(node.paren_token.span.close()),
2125 )
2126 && in_order(receiver_end, argument_start)
2127 && in_order(argument_end, end)
2128 {
2129 let kind = SiteKind::MinMax {
2130 max: name == "max",
2131 receiver: self.source[start..receiver_end].to_string(),
2132 argument: self.source[argument_start..argument_end].to_string(),
2133 call: (receiver_end, argument_start),
2134 close: (argument_end, end),
2135 };
2136 self.push(kind, start, end, node.receiver.span());
2137 }
2138 visit::visit_expr_method_call(self, node);
2139 }
2140
2141 fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
2142 let mut over = &*node.expr;
2143 while let syn::Expr::Paren(syn::ExprParen { expr, .. })
2144 | syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
2145 {
2146 over = expr;
2147 }
2148 if let syn::Expr::Range(syn::ExprRange {
2149 start: Some(from), ..
2150 }) = over
2151 && let Some((start, _)) = self.range(from.span())
2152 {
2153 self.for_ranges.insert(start);
2154 }
2155 visit::visit_expr_for_loop(self, node);
2156 }
2157
2158 fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
2159 if let (Some(from), Some(to)) = (&node.start, &node.end)
2162 && node.attrs.is_empty()
2163 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2164 (self.range(from.span()), self.range(to.span()))
2165 && in_order(lhs_end, rhs_start)
2166 {
2167 let kind = SiteKind::Range {
2168 inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
2169 lhs: self.source[start..lhs_end].to_string(),
2170 rhs: self.source[rhs_start..end].to_string(),
2171 gap: (lhs_end, rhs_start),
2172 };
2173 let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
2180 self.const_depth += built as usize;
2181 self.push(kind, start, end, from.span());
2182 self.const_depth -= built as usize;
2183 }
2184 visit::visit_expr_range(self, node);
2185 }
2186
2187 fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
2188 let catches_all = |arm: &syn::Arm| {
2191 arm.guard.is_none()
2192 && match &arm.pat {
2193 syn::Pat::Wild(_) => true,
2194 syn::Pat::Ident(p) => {
2195 p.subpat.is_none()
2196 && p.ident
2197 .to_string()
2198 .starts_with(|c: char| c.is_lowercase() || c == '_')
2199 }
2200 _ => false,
2201 }
2202 };
2203 let mut removable = vec![];
2204 let has_wildcard = node
2205 .arms
2206 .iter()
2207 .any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
2208 let final_catches_all = node.arms.last().is_some_and(catches_all);
2209 for arm in &node.arms {
2210 if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
2211 continue;
2212 }
2213 let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
2215 let literal =
2216 has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
2217 if !probe && !literal {
2218 continue;
2219 }
2220 let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
2221 self.range(arm.pat.span()),
2222 self.range(arm.span()),
2223 self.range(arm.fat_arrow_token.span()),
2224 ) else {
2225 continue;
2226 };
2227 let guard = match &arm.guard {
2228 None => ArmGuard::None(arrow),
2229 Some((_, expr)) => match self.range(expr.span()) {
2230 Some((from, to)) => ArmGuard::Existing(from, to),
2231 None => continue,
2232 },
2233 };
2234 let pattern = match guard {
2235 ArmGuard::Existing(from, to) => format!(
2236 "{} if {}",
2237 &self.source[start..pat_end],
2238 &self.source[from..to]
2239 ),
2240 ArmGuard::None(_) => self.source[start..pat_end].to_string(),
2241 };
2242 let end = arm
2243 .comma
2244 .as_ref()
2245 .and_then(|comma| self.range(comma.span()))
2246 .map_or(remove_end, |(_, end)| end);
2247 let at = arm.pat.span().start();
2248 removable.push(start);
2249 let site = Site {
2250 id: 0,
2251 kind: SiteKind::Arm {
2252 pattern: pattern.clone(),
2253 guard,
2254 removal: (remove_start, end),
2255 },
2256 line: at.line,
2257 column: at.column + 1,
2258 start,
2259 end,
2260 text: format!("{pattern} => .."),
2261 };
2262 if probe {
2263 self.add(site);
2264 } else {
2265 self.add_rebuild(site);
2266 }
2267 }
2268 for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
2271 if let Some((_, guard)) = &arm.guard
2272 && !matches!(**guard, syn::Expr::Let(_))
2273 && !in_let_chain(guard)
2274 && let (Some((start, end)), Some((pattern, _))) =
2275 (self.range(guard.span()), self.range(arm.pat.span()))
2276 {
2277 let kind = SiteKind::Guard {
2278 can_be_false: !removable.contains(&pattern),
2279 };
2280 self.push(kind, start, end, guard.span());
2281 }
2282 }
2283 visit::visit_expr_match(self, node);
2284 }
2285
2286 fn visit_arm(&mut self, arm: &'ast syn::Arm) {
2287 if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
2288 visit::visit_arm(self, arm);
2289 }
2290 }
2291
2292 fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
2293 if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
2294 visit::visit_field_value(self, field);
2295 }
2296 }
2297
2298 fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2299 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2300 return;
2301 }
2302 let from_base = node.rest.as_deref().and_then(|base| {
2304 if !node.attrs.is_empty() || node.qself.is_some() {
2305 return None;
2306 }
2307 let (from, to) = self.range(base.span())?;
2308 let written = &self.source[from..to];
2309 match base {
2310 base if is_plain_place(base) => Some(format!("({written})")),
2311 syn::Expr::Call(call)
2312 if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
2313 {
2314 let (from, to) = self.range(node.path.span())?;
2315 Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
2316 }
2317 _ => None,
2318 }
2319 });
2320 if node.rest.is_some() {
2321 for pair in node.fields.pairs() {
2322 let field = pair.value();
2323 if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
2324 continue;
2325 }
2326 let name = match &field.member {
2327 syn::Member::Named(name) => name.to_string(),
2328 syn::Member::Unnamed(index) => index.index.to_string(),
2329 };
2330 let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
2331 self.range(field.member.span()),
2332 self.range(field.expr.span()),
2333 self.range(field.span()),
2334 ) else {
2335 continue;
2336 };
2337 let remove_end = pair
2338 .punct()
2339 .and_then(|comma| self.range(comma.span()))
2340 .map_or(end, |(_, end)| end);
2341 let from_base = from_base
2342 .as_ref()
2343 .filter(|_| field.attrs.is_empty())
2344 .map(|base| format!("{base}.{name}"));
2345 let probe = from_base.is_some();
2346 let kind = SiteKind::Field {
2347 from_base,
2348 name,
2349 shorthand: field.colon_token.is_none(),
2350 removal: (remove_start, remove_end),
2351 };
2352 let at = field.member.span().start();
2353 let site = Site {
2354 id: 0,
2355 kind,
2356 line: at.line,
2357 column: at.column + 1,
2358 start: if probe { value } else { remove_start },
2359 end,
2360 text: self.source[start..end].to_string(),
2361 };
2362 if probe {
2363 self.add(site);
2364 } else {
2365 self.add_rebuild(site);
2366 }
2367 }
2368 }
2369 visit::visit_expr_struct(self, node);
2370 }
2371
2372 fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
2373 if let syn::UnOp::Not(bang) = &node.op
2374 && node.attrs.is_empty()
2375 && let (Some((start, _)), Some((operand_start, end))) =
2376 (self.range(bang.span()), self.range(node.expr.span()))
2377 && in_order(start, operand_start)
2378 {
2379 let kind = SiteKind::Not {
2380 bang: (start, operand_start),
2381 operand: self.source[operand_start..end].to_string(),
2382 };
2383 self.push(kind, start, end, bang.span());
2384 }
2385 if let syn::UnOp::Neg(minus) = &node.op
2386 && node.attrs.is_empty()
2387 && let (Some((start, _)), Some((operand_start, end))) =
2388 (self.range(minus.span()), self.range(node.expr.span()))
2389 && in_order(start, operand_start)
2390 {
2391 let zero = match &*node.expr {
2392 syn::Expr::Lit(syn::ExprLit {
2393 lit: syn::Lit::Int(lit),
2394 ..
2395 }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
2396 _ => false,
2398 };
2399 if !zero {
2400 let kind = SiteKind::Neg {
2401 minus: (start, operand_start),
2402 operand: self.source[operand_start..end].to_string(),
2403 literal: matches!(*node.expr, syn::Expr::Lit(_)),
2404 };
2405 self.push(kind, start, end, minus.span());
2406 }
2407 }
2408 visit::visit_expr_unary(self, node);
2409 }
2410
2411 fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
2412 if let Some(op) = cmp_op(&node.op)
2413 && node.attrs.is_empty()
2414 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2415 (self.range(node.left.span()), self.range(node.right.span()))
2416 && in_order(lhs_end, rhs_start)
2417 {
2418 let literal = match (int_literal(&node.left), int_literal(&node.right)) {
2419 (None, Some(k)) => LiteralSide::Rhs(k),
2420 (Some(k), None) => LiteralSide::Lhs(k),
2421 _ => LiteralSide::None,
2422 };
2423 let kind = SiteKind::Cmp {
2424 op,
2425 lhs: self.source[start..lhs_end].to_string(),
2426 rhs: self.source[rhs_start..end].to_string(),
2427 literal,
2428 gap: (lhs_end, rhs_start),
2429 };
2430 self.push(kind, start, end, node.left.span());
2431 } else if node.attrs.is_empty()
2432 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2433 (self.range(node.left.span()), self.range(node.right.span()))
2434 && in_order(lhs_end, rhs_start)
2435 {
2436 let lhs = self.source[start..lhs_end].to_string();
2437 let rhs = self.source[rhs_start..end].to_string();
2438 let gap = (lhs_end, rhs_start);
2439 let logic = match &node.op {
2440 syn::BinOp::And(_) => Some(true),
2441 syn::BinOp::Or(_) => Some(false),
2442 _ => None,
2443 };
2444 if let Some(and) = logic {
2445 if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
2446 self.push(
2447 SiteKind::Logic { and, lhs, rhs, gap },
2448 start,
2449 end,
2450 node.left.span(),
2451 );
2452 }
2453 } else if let Some((op, assign)) = arith_op(&node.op) {
2454 let kind = SiteKind::Arith {
2455 op,
2456 assign,
2457 lhs,
2458 rhs,
2459 gap,
2460 };
2461 let literals = is_literal(&node.left) && is_literal(&node.right);
2464 if !literals && (!assign || is_plain_place(&node.left)) {
2465 self.push(kind, start, end, node.left.span());
2466 } else {
2467 let at = node.left.span().start();
2470 self.found.rebuild_sites.push(Site {
2471 id: NO_ID,
2472 kind,
2473 line: at.line,
2474 column: at.column + 1,
2475 start,
2476 end,
2477 text: self.source[start..end].to_string(),
2478 });
2479 }
2480 }
2481 }
2482 visit::visit_expr_binary(self, node);
2483 }
2484}
2485
2486#[derive(Debug, PartialEq)]
2489pub struct Rendered {
2490 pub text: String,
2491 segments: Vec<(usize, usize, usize)>,
2494 inserted: Vec<(usize, usize, u32)>,
2496}
2497
2498impl Rendered {
2499 pub fn copied(&self, from: usize, to: usize) -> Option<(usize, usize)> {
2502 self.segments
2503 .iter()
2504 .find(|(_, start, len)| *start <= from && to <= start + len)
2505 .map(|(out, start, _)| (out + from - start, out + to - start))
2506 }
2507
2508 pub fn inserted_by(&self, offset: usize) -> Option<u32> {
2512 let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
2513 let (out, len, site) = self.inserted[idx.checked_sub(1)?];
2514 (offset - out < len).then_some(site)
2515 }
2516
2517 pub fn to_original(&self, offset: usize) -> usize {
2518 let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
2519 let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
2520 return 0;
2521 };
2522 orig + (offset - out).min(len)
2524 }
2525}
2526
2527struct Edit {
2528 pos: usize,
2529 end: usize,
2530 phase: u8,
2532 order: i64,
2534 text: String,
2535 site: u32,
2537}
2538
2539pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
2541 let rt = format!("crate::{RUNTIME_MOD}");
2542 let mut edits = vec![];
2543 for site in sites.iter().filter(|s| enabled(s.id)) {
2544 let wraps = matches!(
2548 site.kind,
2549 SiteKind::Return { .. }
2550 | SiteKind::Body { .. }
2551 | SiteKind::Guard { .. }
2552 | SiteKind::Field { .. }
2553 );
2554 let len = 2 * (site.end - site.start) as i64 + wraps as i64;
2556 let (open, close) = match &site.kind {
2557 SiteKind::Cmp { op, gap, .. } => {
2558 let func = if op.is_ordering() { "ord" } else { "eq" };
2559 edits.push(Edit {
2560 pos: gap.0,
2561 end: gap.1,
2562 phase: 1,
2563 order: 0,
2564 text: "), &(".into(),
2565 site: site.id,
2566 });
2567 (
2568 "(match (&(".to_string(),
2569 format!(
2570 ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
2571 {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
2572 id = site.id,
2573 code = op.code(),
2574 ),
2575 )
2576 }
2577 SiteKind::Logic { and, gap, .. } => {
2582 let id = site.id;
2585 edits.push(Edit {
2586 pos: gap.0,
2587 end: gap.1,
2588 phase: 1,
2589 order: 0,
2590 text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
2591 site: site.id,
2592 });
2593 (
2594 format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
2597 "), __tmt_c => __tmt_c == 1u8 })".to_string(),
2598 )
2599 }
2600 SiteKind::Arith {
2601 op, assign, gap, ..
2602 } => {
2603 let (holder, lhs_open, lhs_close) = if *assign {
2605 ("Aa", "&mut (", ")")
2606 } else {
2607 ("Ar", "", "")
2608 };
2609 edits.push(Edit {
2610 pos: gap.0,
2611 end: gap.1,
2612 phase: 1,
2613 order: 0,
2614 text: format!("{lhs_close}, "),
2615 site: site.id,
2616 });
2617 (
2618 format!("(match ({lhs_open}"),
2619 format!(
2620 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
2621 (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
2622 any = op.fallback_trait(*assign),
2623 prim = op.prim_trait(*assign),
2624 method = op.method(*assign),
2625 id = site.id,
2626 ),
2627 )
2628 }
2629 SiteKind::Not { bang, .. } => {
2630 edits.push(Edit {
2632 pos: bang.0,
2633 end: bang.1,
2634 phase: 1,
2635 order: 0,
2636 text: String::new(),
2637 site: site.id,
2638 });
2639 (
2640 "(match (".to_string(),
2641 format!(
2642 ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
2643 (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
2644 site.id
2645 ),
2646 )
2647 }
2648 SiteKind::Return { option, .. } => match option {
2649 None => (
2650 " let __tmt_v: bool = {".to_string(),
2651 format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
2652 ),
2653 Some(ty) => (
2654 format!(" let __tmt_v: {ty} = {{"),
2655 format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
2656 ),
2657 },
2658 SiteKind::MinMax {
2659 max, call, close, ..
2660 } => {
2661 edits.push(Edit {
2665 pos: call.0,
2666 end: call.1,
2667 phase: 1,
2668 order: 0,
2669 text: "), ".into(),
2670 site: site.id,
2671 });
2672 let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
2676 edits.push(Edit {
2677 pos: close.0,
2678 end: close.1,
2679 phase: 1,
2680 order: 0,
2681 text: format!(
2682 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
2683 if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
2684 site.id
2685 ),
2686 site: site.id,
2687 });
2688 ("(match (&(".to_string(), String::new())
2689 }
2690 SiteKind::Range { inclusive, gap, .. } => {
2691 edits.push(Edit {
2692 pos: gap.0,
2693 end: gap.1,
2694 phase: 1,
2695 order: 0,
2696 text: ", ".into(),
2697 site: site.id,
2698 });
2699 let method = if *inclusive {
2700 "tmt_range_inclusive"
2701 } else {
2702 "tmt_range"
2703 };
2704 (
2705 "(match (".to_string(),
2706 format!(
2707 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
2708 (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
2709 site.id
2710 ),
2711 )
2712 }
2713 SiteKind::Arm { guard, .. } => {
2714 match guard {
2717 ArmGuard::None(arrow) => edits.push(Edit {
2718 pos: *arrow,
2719 end: *arrow,
2720 phase: 2,
2721 order: 0,
2722 text: format!("if {rt}::arm({}u32) ", site.id),
2723 site: site.id,
2724 }),
2725 ArmGuard::Existing(from, to) => {
2726 let wider = 2 * (to - from + 1) as i64;
2727 edits.push(Edit {
2728 pos: *from,
2729 end: *from,
2730 phase: 2,
2731 order: -wider,
2732 text: format!("{rt}::arm({}u32) && (", site.id),
2733 site: site.id,
2734 });
2735 edits.push(Edit {
2736 pos: *to,
2737 end: *to,
2738 phase: 0,
2739 order: wider,
2740 text: ")".into(),
2741 site: site.id,
2742 });
2743 }
2744 }
2745 (String::new(), String::new())
2746 }
2747 SiteKind::Stmt => (
2748 format!("if {rt}::live({}u32) {{ ", site.id),
2749 " }".to_string(),
2750 ),
2751 SiteKind::Neg {
2753 operand,
2754 literal: true,
2755 ..
2756 } => (
2757 format!("(if {rt}::live({}u32) {{ ", site.id),
2758 format!(" }} else {{ {operand} }})"),
2759 ),
2760 SiteKind::Neg { minus, .. } => {
2761 edits.push(Edit {
2762 pos: minus.0,
2763 end: minus.1,
2764 phase: 1,
2765 order: 0,
2766 text: String::new(),
2767 site: site.id,
2768 });
2769 (
2770 "(match (".to_string(),
2771 format!(
2772 ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
2773 site.id
2774 ),
2775 )
2776 }
2777 SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
2778 SiteKind::Field {
2779 name,
2780 shorthand,
2781 from_base: Some(from_base),
2782 ..
2783 } => (
2784 format!(
2785 "{}if {rt}::live({}u32) {{ ",
2786 if *shorthand {
2787 format!("{name}: ")
2788 } else {
2789 String::new()
2790 },
2791 site.id
2792 ),
2793 format!(" }} else {{ {from_base} }}"),
2794 ),
2795 SiteKind::Field {
2796 from_base: None, ..
2797 } => continue,
2798 SiteKind::Body { value, .. } => (
2799 format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
2800 String::new(),
2801 ),
2802 };
2803 edits.push(Edit {
2804 pos: site.start,
2805 end: site.start,
2806 phase: 2,
2807 order: -len,
2808 text: open,
2809 site: site.id,
2810 });
2811 edits.push(Edit {
2812 pos: site.end,
2813 end: site.end,
2814 phase: 0,
2815 order: len,
2816 text: close,
2817 site: site.id,
2818 });
2819 }
2820 edits.sort_by_key(|e| (e.pos, e.phase, e.order));
2821
2822 let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
2824 let mut text = String::with_capacity(capacity);
2825 let mut segments = vec![];
2826 let mut inserted = vec![];
2827 let mut cursor = 0;
2828 for edit in edits {
2829 if edit.pos >= cursor {
2832 segments.push((text.len(), cursor, edit.pos - cursor));
2833 text.push_str(&source[cursor..edit.pos]);
2834 }
2835 inserted.push((text.len(), edit.text.len(), edit.site));
2836 text.push_str(&edit.text);
2837 cursor = cursor.max(edit.end);
2838 }
2839 segments.push((text.len(), cursor, source.len() - cursor));
2840 text.push_str(&source[cursor..]);
2841 Rendered {
2842 text,
2843 segments,
2844 inserted,
2845 }
2846}
2847
2848pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
2851 let containing = || {
2854 sites.iter().filter(|s| {
2855 enabled(s.id)
2856 && s.start <= offset
2857 && offset <= s.end
2858 && !matches!(s.kind, SiteKind::Body { .. })
2859 })
2860 };
2861 let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
2862 return vec![];
2863 };
2864 containing()
2865 .filter(|s| s.end - s.start == smallest)
2866 .map(|s| s.id)
2867 .collect()
2868}
2869
2870#[cfg(test)]
2871mod tests {
2872 use super::*;
2873
2874 #[test]
2875 fn what_an_expression_can_be_is_read_from_its_last_operation() {
2876 use crate::plan::Reach;
2877 for (expr, expected) in [
2878 ("blocks * 8", Some(Reach::Multiples(8))),
2879 ("8 * blocks", Some(Reach::Multiples(8))),
2880 ("(blocks * (2))", Some(Reach::Multiples(2))),
2881 ("blocks << 3", Some(Reach::Multiples(8))),
2882 ("blocks << 9", Some(Reach::Multiples(512))),
2883 ("flags & 0xF0", Some(Reach::Bits(0xF0))),
2884 ("0b1010u8 & flags", Some(Reach::Bits(0b1010))),
2885 ("n % 10", Some(Reach::Below(10))),
2886 ("(a + b) % 7_u32", Some(Reach::Below(7))),
2887 ("cents * 10", None),
2889 ("blocks * 1", None),
2890 ("blocks * 0", None),
2891 ("a * b", None),
2892 ("3 << blocks", None),
2893 ("blocks << 0", None),
2894 ("blocks << 200", None),
2895 ("10 % n", None),
2896 ("n % 0", None),
2897 ("blocks * 8 + 1", None),
2898 ("(blocks * 8) as u8", None),
2899 ("-(blocks * 8)", None),
2900 ("blocks", None),
2901 ("flags | 0xF0", None),
2902 ("blocks / 8", None),
2903 ("x * 8.0", None),
2904 ("not rust (", None),
2905 ] {
2906 assert_eq!(reach(expr).map(|(reach, _)| reach), expected, "{expr}");
2907 assert_eq!(
2909 reach(expr).and_then(|(_, bits)| bits).is_some(),
2910 expr.contains("<<") && expected.is_some(),
2911 "{expr}"
2912 );
2913 }
2914 }
2915
2916 #[test]
2917 fn code_of_the_tests_is_told_from_the_rest() {
2918 let source = r#"
2919 pub fn open(n: u32) -> bool { n > 1 }
2920 #[test]
2921 fn at_the_top() { assert!(open(2)); }
2922 #[cfg(test)]
2923 mod tests { fn helper() -> u32 { 3 } }
2924 mod plain {
2925 pub fn inside(n: u32) -> bool { n > 4 }
2926 #[cfg(test)]
2927 fn only_tested() -> u32 { 5 }
2928 }
2929 struct S;
2930 impl S {
2931 fn method(&self) -> u32 { 6 }
2932 #[cfg(test)]
2933 fn test_method(&self) -> u32 { 7 }
2934 }
2935 #[cfg(not(test))]
2936 fn never_in_tests() -> u32 { 8 }
2937 "#;
2938 let file = parse_source(source).unwrap();
2939 let ranges = test_only_ranges(source, &file);
2940 let of_tests = |text: &str| {
2941 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
2942 ranges.iter().any(|(from, to)| *from <= at && at < *to)
2943 };
2944 for text in ["open(2)", "{ 3 }", "{ 5 }", "{ 7 }", "fn at_the_top"] {
2945 assert!(of_tests(text), "{text}");
2946 }
2947 for text in ["n > 1", "n > 4", "{ 6 }", "{ 8 }", "struct S", "mod plain"] {
2948 assert!(!of_tests(text), "{text}");
2949 }
2950 let whole = "#![cfg(test)]\nfn f() {}\n";
2951 let file = parse_source(whole).unwrap();
2952 assert_eq!(test_only_ranges(whole, &file), [(0, whole.len())]);
2953 }
2954
2955 #[test]
2956 fn comments_documentation_and_spacing_are_not_program_text() {
2957 let code = "/// Says.\n#[inline]\nfn f(a: u8) -> u8 {\n a + 1 // one more\n}\n";
2958 for same in [
2959 "#[inline] fn f(a:u8)->u8{a+1}",
2960 "/// Says something else.\n#[inline]\nfn f(a: u8) -> u8 { /* why */ a + 1 }",
2961 "#[doc = \"other\"] #[inline] fn f(a: u8) -> u8 { a + 1 }",
2962 ] {
2963 assert_eq!(same_tokens(code, same), Some(true), "{same}");
2964 }
2965 for other in [
2966 "#[inline] fn f(a: u8) -> u8 { a + 2 }",
2967 "fn f(a: u8) -> u8 { a + 1 }",
2968 "#[inline] fn f(a: u8) -> u8 { (a + 1) }",
2969 "#[inline] fn f(a: u8) -> u8 { a + 1 } fn g() {}",
2970 "#![inline] fn f(a: u8) -> u8 { a + 1 }",
2971 "#[inline] fn f(a: u8) -> u8 { [a + 1][0] }",
2972 ] {
2973 assert_eq!(same_tokens(code, other), Some(false), "{other}");
2974 }
2975 assert_eq!(
2976 same_tokens("#![doc = \"a\"] fn f() {}", "fn f() {}"),
2977 Some(true)
2978 );
2979 assert_eq!(same_tokens(code, "fn f( {"), None);
2980 assert_eq!(same_tokens("fn f( {", code), None);
2981 }
2982
2983 #[test]
2984 fn a_cfg_is_decided_only_as_far_as_the_features_decide_it() {
2985 let on: BTreeSet<String> = ["basic".to_string()].into();
2986 for (predicate, expected) in [
2987 (r#"feature = "basic""#, Some(true)),
2988 (r#"feature = "extra""#, Some(false)),
2989 (r#"not(feature = "extra")"#, Some(true)),
2990 (r#"not(feature = "basic")"#, Some(false)),
2991 ("test", None),
2992 (r#"target_os = "linux""#, None),
2993 ("not(test)", None),
2994 ("all()", Some(true)),
2995 ("any()", Some(false)),
2996 (r#"all(feature = "basic", feature = "extra")"#, Some(false)),
2997 (r#"all(test, feature = "extra")"#, Some(false)),
2998 (r#"all(feature = "extra", test)"#, Some(false)),
2999 (r#"all(test, feature = "basic")"#, None),
3000 (
3001 r#"all(feature = "basic", not(feature = "extra"))"#,
3002 Some(true),
3003 ),
3004 (r#"any(feature = "basic", feature = "extra")"#, Some(true)),
3005 (r#"any(test, feature = "basic")"#, Some(true)),
3006 (r#"any(feature = "basic", test)"#, Some(true)),
3007 (r#"any(test, feature = "extra")"#, None),
3008 (r#"any(feature = "extra", feature = "more")"#, Some(false)),
3009 (r#"not(any(test, feature = "basic"))"#, Some(false)),
3010 (r#"not(test, feature = "basic")"#, None),
3011 ("feature = 3", None),
3012 (r#"unknown(feature = "extra")"#, None),
3013 ("all(=)", None),
3014 ] {
3015 let meta: syn::Meta = syn::parse_str(predicate).unwrap();
3016 assert_eq!(cfg_value(&meta, &on), expected, "{predicate}");
3017 }
3018 }
3019
3020 #[test]
3021 fn code_under_a_feature_that_is_off_is_not_in_the_build() {
3022 let source = r#"
3023 #[cfg(feature = "extra")]
3024 pub fn item(n: u32) -> bool { n > 1 }
3025 #[cfg(feature = "basic")]
3026 pub fn kept(n: u32) -> bool { n > 2 }
3027 #[cfg(test)]
3028 fn only_tests(n: u32) -> bool { n > 3 }
3029 #[cfg(feature = "extra")]
3030 mod module { pub fn inside(n: u32) -> bool { n > 4 } }
3031 struct S;
3032 impl S {
3033 #[cfg(feature = "extra")]
3034 fn method(&self, n: u32) -> bool { n > 5 }
3035 fn open(&self, n: u32) -> bool { n > 6 }
3036 }
3037 trait T {
3038 #[cfg(feature = "extra")]
3039 fn provided(&self, n: u32) -> bool { n > 7 }
3040 }
3041 #[cfg(feature = "extra")]
3042 impl T for S {}
3043 fn body(n: u32) -> u32 {
3044 #[cfg(feature = "extra")]
3045 let n = n + 8;
3046 #[cfg(feature = "extra")]
3047 { return n + 9; }
3048 #[cfg(feature = "extra")]
3049 if n > 10 { return 0; }
3050 #[cfg(feature = "extra")]
3051 assert!(n > 11);
3052 match n {
3053 #[cfg(feature = "extra")]
3054 12 => 0,
3055 _ => n + 13,
3056 }
3057 }
3058 #[cfg(not(feature = "extra"))]
3059 mod kept_module {
3060 #[cfg(feature = "extra")]
3061 const OFF: u32 = 14 + 1;
3062 const ON: u32 = 15 + 1;
3063 }
3064 "#;
3065 let file = parse_source(source).unwrap();
3066 let on: BTreeSet<String> = ["basic".to_string()].into();
3067 let ranges = inactive_ranges(source, &file, &on);
3068 let left_out = |text: &str| {
3069 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
3070 ranges.iter().any(|(from, to)| *from <= at && at < *to)
3071 };
3072 for off in [
3073 "n > 1 ", "n > 4", "n > 5", "n > 7", "n + 8", "n + 9", "n > 10", "n > 11", "12 =>",
3074 "14 + 1",
3075 ] {
3076 assert!(left_out(off), "{off}");
3077 }
3078 for on in ["n > 2", "n > 3", "n > 6", "n + 13", "15 + 1", "struct S"] {
3079 assert!(!left_out(on), "{on}");
3080 }
3081 let both: BTreeSet<String> = ["basic".to_string(), "extra".to_string()].into();
3084 let with_extra = inactive_ranges(source, &file, &both);
3085 assert_eq!(with_extra.len(), 1, "{with_extra:?}");
3086 assert!(source[with_extra[0].0..with_extra[0].1].starts_with("#[cfg(not(feature"));
3087 let whole = "#![cfg(feature = \"extra\")]\nfn f() {}\n";
3088 let file = parse_source(whole).unwrap();
3089 assert_eq!(inactive_ranges(whole, &file, &on), [(0, whole.len())]);
3090 }
3091
3092 fn all(_: u32) -> bool {
3093 true
3094 }
3095
3096 fn found(src: &str, first_id: u32) -> Result<Discovery> {
3099 let mut all = discover(src, 0)?;
3100 all.sites
3101 .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
3102 for (index, site) in all.sites.iter_mut().enumerate() {
3103 site.id = first_id + index as u32;
3104 }
3105 Ok(all)
3106 }
3107
3108 #[test]
3109 fn finds_a_comparison_with_a_literal() {
3110 let src = "pub fn is_eligible(age: u32) -> bool {\n age >= 18\n}\n";
3111 let found = found(src, 5).unwrap();
3112 assert_eq!(found.sites.len(), 1);
3113 let site = &found.sites[0];
3114 assert_eq!(
3115 (site.id, site.line, site.column, site.text.as_str()),
3116 (5, 2, 5, "age >= 18")
3117 );
3118 let SiteKind::Cmp {
3119 op,
3120 lhs,
3121 rhs,
3122 literal,
3123 ..
3124 } = &site.kind
3125 else {
3126 panic!()
3127 };
3128 assert_eq!(
3129 (*op, lhs.as_str(), rhs.as_str(), *literal),
3130 (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
3131 );
3132 }
3133
3134 #[test]
3135 fn literal_sides() {
3136 let src =
3137 "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
3138 let literals: Vec<LiteralSide> = found(src, 0)
3139 .unwrap()
3140 .sites
3141 .iter()
3142 .filter_map(|s| match &s.kind {
3143 SiteKind::Cmp { literal, .. } => Some(*literal),
3144 SiteKind::Neg { .. } => None,
3145 _ => panic!(),
3146 })
3147 .collect();
3148 assert_eq!(
3149 literals,
3150 [
3151 LiteralSide::Lhs(-5),
3152 LiteralSide::Rhs(3),
3153 LiteralSide::None,
3154 LiteralSide::None,
3155 LiteralSide::None
3156 ]
3157 );
3158 }
3159
3160 #[test]
3161 fn renders_a_comparison_probe() {
3162 let src = "fn f(a: u8) -> bool { a >= 18 }";
3163 let sites = found(src, 3).unwrap().sites;
3164 let out = render(src, &sites, &all);
3165 assert_eq!(
3166 out.text,
3167 "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
3168 use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
3169 (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
3170 );
3171 assert_eq!(render(src, &sites, &|_| false).text, src);
3172 }
3173
3174 #[test]
3175 fn renders_statement_guards_and_nested_sites() {
3176 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}";
3177 let sites = found(src, 0).unwrap().sites;
3178 let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3179 assert_eq!(
3180 kinds,
3181 [
3182 "check((a < 3) == true)?;",
3183 "v.push(a);",
3184 "v.clear();",
3185 "(a < 3) == true",
3186 "a < 3"
3187 ]
3188 );
3189 let out = render(src, &sites, &all);
3190 assert_eq!(
3191 out.text.lines().count(),
3192 src.lines().count(),
3193 "line numbers are preserved"
3194 );
3195 assert!(
3196 out.text
3197 .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
3198 "{}",
3199 out.text
3200 );
3201 assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
3202 syn::parse_file(&out.text).expect("instrumented source parses");
3203
3204 let inner = render(src, &sites, &|id| id == 4);
3206 assert!(
3207 inner.text.contains("check(((match (&(a), &(3))"),
3208 "{}",
3209 inner.text
3210 );
3211 assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
3212 syn::parse_file(&inner.text).unwrap();
3213 }
3214
3215 #[test]
3216 fn skips_tests_const_contexts_and_macros() {
3217 let src = r#"
3218 const LIMIT: bool = 1 < 2;
3219 static S: bool = 3 > 2;
3220 const fn c(a: u8) -> bool { a < 1 }
3221 fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
3222 enum E { A = (5 > 4) as isize }
3223 struct T;
3224 impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
3225 #[cfg(test)]
3226 mod tests { fn t(a: u8) -> bool { a == 1 } }
3227 #[cfg(test)]
3228 mod more_tests;
3229 #[cfg(test)]
3230 #[doc = "not a path"]
3231 mod documented;
3232 #[cfg(test)]
3233 #[path = "support/helpers.rs"]
3234 mod helpers;
3235 #[cfg(all(test, feature = "x"))]
3236 fn helper(a: u8) -> bool { a != 1 }
3237 #[test]
3238 fn a_test() { let a = 1; if a == 2 { panic!() } }
3239 #[tokio::test]
3240 async fn async_test() { let a = 1; if a == 3 { panic!() } }
3241 #[cfg(not(test))]
3242 fn real(a: u8) -> bool { a == 100 }
3243 #[cfg(feature = "test-utils")]
3244 fn also_real(a: u8) -> bool { a == 101 }
3245 fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
3246 "#;
3247 let found = found(src, 0).unwrap();
3248 let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
3249 assert_eq!(
3250 texts,
3251 [
3252 "a == 100",
3253 "a == 101",
3254 "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
3255 "0..=9 => ..",
3256 "a == 102"
3257 ]
3258 );
3259 assert_eq!(
3260 found.test_modules,
3261 [
3262 TestModule {
3263 name: "more_tests".into(),
3264 path: None
3265 },
3266 TestModule {
3267 name: "documented".into(),
3268 path: None
3269 },
3270 TestModule {
3271 name: "helpers".into(),
3272 path: Some("support/helpers.rs".into())
3273 },
3274 ]
3275 );
3276 }
3277
3278 #[test]
3279 fn deletable_statements() {
3280 let src = r#"
3281 async fn f(s: &mut S) -> Result<(), E> {
3282 s.validate()?;
3283 s.total += 1;
3284 s.flag = true;
3285 helper(s);
3286 s.flush().await?;
3287 s.sync().await;
3288 let x = s.get();
3289 println!("{x}");
3290 if x > 0 { return Ok(()); }
3291 s.done()
3292 }
3293 "#;
3294 let texts: Vec<String> = found(src, 0)
3295 .unwrap()
3296 .sites
3297 .into_iter()
3298 .filter(|s| s.kind == SiteKind::Stmt)
3299 .map(|s| s.text)
3300 .collect();
3301 assert_eq!(
3302 texts,
3303 [
3304 "s.validate()?;",
3305 "s.total += 1;",
3306 "s.flag = true;",
3307 "helper(s);",
3308 "s.flush().await?;",
3309 "s.sync().await;"
3310 ]
3311 );
3312 }
3313
3314 #[test]
3315 fn maps_offsets_back_and_blames_the_innermost_site() {
3316 let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
3317 let sites = found(src, 0).unwrap().sites;
3318 let out = render(src, &sites, &all);
3319 for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
3321 let hits: Vec<usize> = out
3322 .text
3323 .char_indices()
3324 .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
3325 .map(|(o, _)| o)
3326 .collect();
3327 assert!(
3328 !hits.is_empty(),
3329 "original offset {orig} ({ch}) is unreachable"
3330 );
3331 }
3332 let probe = out.text.find("ord(1u32").unwrap();
3334 let orig = out.to_original(probe);
3335 assert_eq!(blame(&sites, &all, orig), [1]);
3336 assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
3338 assert_eq!(
3339 blame(&sites, &all, src.find("fn").unwrap()),
3340 Vec::<u32>::new()
3341 );
3342 assert_eq!(out.to_original(0), 0);
3343 assert_eq!(out.to_original(out.text.len()), src.len());
3344 }
3345
3346 #[test]
3347 fn blame_is_inclusive_at_both_ends() {
3348 let src = "fn f(a: u8) -> bool { a > 1 }";
3349 let sites = found(src, 0).unwrap().sites;
3350 let (start, end) = (sites[0].start, sites[0].end);
3351 assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
3352 assert_eq!(blame(&sites, &all, start), [0]);
3353 assert_eq!(blame(&sites, &all, end), [0]);
3354 assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
3355 let out = render(src, &sites, &all);
3357 assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
3358 assert_eq!(
3359 out.to_original(out.text.find("tmt_val()) } })").unwrap()),
3360 end
3361 );
3362 assert_eq!(
3363 out.to_original(out.text.find("), &(").unwrap() + 2),
3364 sites[0].start + 1
3365 );
3366 }
3367
3368 #[test]
3369 fn finds_sites_in_impls_and_array_elements() {
3370 let src = r#"
3371 struct T(u8);
3372 impl T { fn small(&self) -> bool { self.0 < 3 } }
3373 #[cfg(test)]
3374 impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
3375 trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
3376 fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
3377 fn closure(a: u8) -> bool { (|| a < 7)() }
3378 "#;
3379 let texts: Vec<String> = found(src, 0)
3380 .unwrap()
3381 .sites
3382 .into_iter()
3383 .map(|s| s.text)
3384 .collect();
3385 assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
3386 }
3387
3388 #[test]
3389 fn logic_and_arithmetic_sites() {
3390 let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
3391 let found = found(src, 0).unwrap().sites;
3392 let kinds: Vec<String> = found
3393 .iter()
3394 .map(|s| match &s.kind {
3395 SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
3396 SiteKind::Arith { op, lhs, rhs, .. } => {
3397 format!("arith {} [{lhs}] [{rhs}]", op.symbol())
3398 }
3399 SiteKind::Not { operand, .. } => format!("not [{operand}]"),
3400 other => format!("{other:?}"),
3401 })
3402 .collect();
3403 assert_eq!(
3404 kinds,
3405 [
3406 "logic and=false [a && b] [!a]",
3407 "logic and=true [a] [b]",
3408 "not [a]",
3409 "arith + [x] [y * 2]",
3410 "arith * [y] [2]",
3411 "arith - [x] [1 % y]",
3412 "arith % [1] [y]",
3413 ]
3414 );
3415 let out = render(src, &found, &all).text;
3416 syn::parse_file(&out).expect("instrumented source parses");
3417 assert!(
3418 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 })"),
3419 "{out}"
3420 );
3421 assert!(
3422 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) } })"),
3423 "{out}"
3424 );
3425 for op in ArithOp::ALL {
3427 assert_ne!(op.swapped(), op);
3428 for assign in [false, true] {
3429 let method = op.method(assign);
3430 let fallback = format!("{} {method} ", op.fallback_trait(assign));
3431 assert!(
3432 crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
3433 "{method}"
3434 );
3435 assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
3436 assert!(
3437 crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
3438 "{op:?}"
3439 );
3440 }
3441 }
3442 }
3443
3444 #[test]
3445 fn let_chains_and_literal_arithmetic_are_left_alone() {
3446 let src = r#"
3447 fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
3448 if let Some(x) = o && a && x > 1 { return 1; }
3449 let k = 60 * 60;
3450 (n & 3) | (n << 1) ^ k
3451 }
3452 "#;
3453 let texts: Vec<String> = found(src, 0)
3454 .unwrap()
3455 .sites
3456 .into_iter()
3457 .map(|s| s.text)
3458 .collect();
3459 assert_eq!(
3460 texts,
3461 [
3462 "x > 1",
3463 "(n & 3) | (n << 1) ^ k",
3464 "n & 3",
3465 "(n << 1) ^ k",
3466 "n << 1"
3467 ]
3468 );
3469 }
3470
3471 #[test]
3472 fn attributes_const_methods_and_let_on_the_right() {
3473 let src = r#"
3474 struct T(u8);
3475 impl T {
3476 const fn in_const(&self) -> bool { self.0 < 1 }
3477 #[test]
3478 fn test_method(&self) -> bool { self.0 < 2 }
3479 fn real(&self) -> bool { self.0 < 3 }
3480 }
3481 trait Tr {
3482 #[cfg(test)]
3483 fn only_in_tests(&self, a: u8) -> bool { a < 4 }
3484 }
3485 fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
3486 #[cfg(feature = "x")]
3487 s.guarded();
3488 #[allow(unused)]
3489 s.total += 1;
3490 #[allow(unused)]
3491 s.check()?;
3492 #[allow(unused)]
3493 s.sync().await;
3494 s.plain();
3495 if a && let Some(v) = o { s.use_it(v); }
3496 Ok(())
3497 }
3498 "#;
3499 let texts: Vec<String> = found(src, 0)
3500 .unwrap()
3501 .sites
3502 .into_iter()
3503 .map(|s| s.text)
3504 .collect();
3505 assert_eq!(
3508 texts,
3509 [
3510 "self.0 < 3",
3511 "#[allow(unused)]\n s.total += 1;",
3512 "s.plain();",
3513 "#[allow(unused)]\n s.total += 1",
3514 "s.use_it(v);"
3515 ]
3516 );
3517 let found = found(src, 0).unwrap().sites;
3518 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3519 }
3520
3521 #[test]
3522 fn compound_assignment_negation_and_bit_operators() {
3523 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 }";
3524 let sites = found(src, 0).unwrap().sites;
3525 let kinds: Vec<String> = sites
3526 .iter()
3527 .map(|s| match &s.kind {
3528 SiteKind::Arith {
3529 op,
3530 assign,
3531 lhs,
3532 rhs,
3533 ..
3534 } => format!(
3535 "{lhs} {}{} {rhs}",
3536 op.symbol(),
3537 if *assign { "=" } else { "" }
3538 ),
3539 SiteKind::Not { operand, .. } => format!("!{operand}"),
3540 SiteKind::Stmt => "stmt".to_string(),
3541 other => format!("{other:?}"),
3542 })
3543 .collect();
3544 assert_eq!(
3545 kinds,
3546 [
3547 "stmt",
3548 "stmt",
3549 "*total += n",
3550 "*total <<= 1",
3551 "!ok",
3552 "!n",
3553 "!m",
3554 "n & 7"
3555 ]
3556 );
3557 let out = render(src, &sites, &all).text;
3558 syn::parse_file(&out).expect("instrumented source parses");
3559 for expected in [
3560 "(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) } });",
3561 "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
3562 "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) } }) {",
3563 "(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) } })",
3564 ] {
3565 assert!(out.contains(expected), "missing {expected}\nin {out}");
3566 }
3567 let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
3569 let sites = found(nested, 0).unwrap().sites;
3570 let out = render(nested, &sites, &all).text;
3571 syn::parse_file(&out).expect("instrumented source parses");
3572 assert!(
3573 out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
3574 "{out}"
3575 );
3576 let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
3578 let sites = found(capture, 0).unwrap().sites;
3579 let out = render(capture, &sites, &all).text;
3580 syn::parse_file(&out).expect("instrumented source parses");
3581 for arm in out.split("__tmt_c => ").skip(1) {
3583 assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
3584 }
3585 for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
3586 assert!(
3587 arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
3588 "{arm}"
3589 );
3590 }
3591 }
3592
3593 #[test]
3594 fn compound_assignment_is_probed_only_on_plain_places() {
3595 let src = r#"
3596 fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
3597 let mut local = 0u32;
3598 local += 1;
3599 s.count += 1;
3600 s.inner.total -= 2;
3601 *p *= 3;
3602 (*p) += 4;
3603 v[i] += 5;
3604 v[next()] += 6;
3605 s.get_mut().x += 7;
3606 *s.slot() += 8;
3607 }
3608 "#;
3609 let probed: Vec<String> = found(src, 0)
3610 .unwrap()
3611 .sites
3612 .into_iter()
3613 .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
3614 .map(|s| s.text)
3615 .collect();
3616 assert_eq!(
3617 probed,
3618 [
3619 "local += 1",
3620 "s.count += 1",
3621 "s.inner.total -= 2",
3622 "*p *= 3",
3623 "(*p) += 4"
3624 ]
3625 );
3626 let deletable = found(src, 0)
3628 .unwrap()
3629 .sites
3630 .iter()
3631 .filter(|s| s.kind == SiteKind::Stmt)
3632 .count();
3633 assert_eq!(deletable, 9);
3634 }
3635
3636 #[test]
3637 fn bool_functions_are_return_sites() {
3638 let src = r#"
3639 pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
3640 fn count(a: u8) -> u8 { a }
3641 fn unit(a: u8) { let _ = a; }
3642 const fn in_const(a: u8) -> bool { a > 2 }
3643 #[test]
3644 fn a_test() -> bool { true }
3645 struct T;
3646 impl T { fn method(&self) -> bool { true } }
3647 trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
3648 fn boxed() -> Box<bool> { Box::new(true) }
3649 fn qualified() -> core::primitive::bool { true }
3650 "#;
3651 let sites = discover(src, 0).unwrap().sites;
3652 let returns: Vec<(&str, &str, usize)> = sites
3653 .iter()
3654 .filter_map(|s| match &s.kind {
3655 SiteKind::Return {
3656 name, option: None, ..
3657 } => Some((name.as_str(), s.text.as_str(), s.line)),
3658 _ => None,
3659 })
3660 .collect();
3661 assert_eq!(
3662 returns,
3663 [
3664 ("is_ok", "fn is_ok(a: u8) -> bool", 2),
3665 ("method", "fn method(&self) -> bool", 9),
3666 ("provided", "fn provided(&self) -> bool", 10),
3667 ]
3668 );
3669 let out = render(src, &sites, &all).text;
3670 syn::parse_file(&out).expect("instrumented source parses");
3671 assert!(
3672 out.contains(
3673 "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
3674 if !crate::__tmt_rt::live(1u32) { return true; } \
3675 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
3676 ),
3677 "{out}"
3678 );
3679 assert!(
3680 out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3681 "{out}"
3682 );
3683 assert_eq!(
3684 out.lines().count(),
3685 src.lines().count(),
3686 "line numbers are preserved"
3687 );
3688 let rendered = render(src, &sites, &all);
3690 let wrapper = rendered.text.find("ret(0u32").unwrap();
3691 assert_eq!(rendered.inserted_by(wrapper), Some(0));
3692 let replaced = rendered.text.find("return false; } let b").unwrap();
3695 assert_eq!(rendered.inserted_by(replaced), Some(2));
3696 assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
3697 }
3698
3699 #[test]
3700 fn ids_are_consecutive_across_every_kind_of_site() {
3701 let src = r#"
3702 fn a(x: u8) -> bool { x > 1 }
3703 fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
3704 fn c(s: &mut S) { s.n += 1; s.go(); }
3705 "#;
3706 let sites = discover(src, 10).unwrap().sites;
3707 let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
3708 assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
3709 let texts: Vec<&str> = sites
3710 .iter()
3711 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3712 .map(|s| s.text.as_str())
3713 .collect();
3714 assert_eq!(
3715 texts,
3716 [
3717 "fn a(x: u8) -> bool",
3718 "x > 1",
3719 "fn b(x: u8) -> bool",
3720 "!(x > 2) && !!flag(x)",
3721 "!(x > 2)",
3722 "x > 2",
3723 "!!flag(x)",
3724 "!flag(x)",
3725 "s.n += 1;",
3726 "s.go();",
3727 "s.n += 1",
3728 ]
3729 );
3730 syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
3731 }
3732
3733 #[test]
3734 fn only_calls_and_assignments_are_deletable() {
3735 let src = r#"
3736 async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
3737 s.field;
3738 v[0];
3739 (s.a, s.b);
3740 s.value?;
3741 s.future.await;
3742 s.x = 1;
3743 s.x -= 1;
3744 s.x == 1;
3745 s.call().await?;
3746 Ok(())
3747 }
3748 "#;
3749 let texts: Vec<String> = found(src, 0)
3750 .unwrap()
3751 .sites
3752 .into_iter()
3753 .filter(|s| s.kind == SiteKind::Stmt)
3754 .map(|s| s.text)
3755 .collect();
3756 assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
3757 }
3758
3759 #[test]
3760 fn ranges_match_arms_min_max_and_option_results() {
3761 let src = r#"
3762 fn find(v: &[u32], limit: u32) -> Option<u32> {
3763 for i in 0..v.len() {
3764 let capped = v[i].min(limit).max(1);
3765 match capped {
3766 0 => return None,
3767 n if n > 5 => return Some(n),
3768 1..=3 => continue,
3769 other => { let _ = other; }
3770 }
3771 }
3772 let _ = &v[1..=2];
3773 for _ in 1..=limit as usize {}
3774 let _ = 'a'..'z';
3775 let _ = v.iter().max();
3776 None
3777 }
3778 fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
3779 fn hidden() -> Option<impl Sized> { Some(1) }
3780 fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
3781 "#;
3782 let sites = discover(src, 0).unwrap().sites;
3783 let kinds: Vec<String> = sites
3784 .iter()
3785 .filter_map(|s| match &s.kind {
3786 SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
3787 SiteKind::Range {
3788 inclusive,
3789 lhs,
3790 rhs,
3791 ..
3792 } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
3793 SiteKind::Arm { pattern, guard, .. } => Some(format!(
3794 "arm {pattern} guarded={}",
3795 matches!(guard, ArmGuard::Existing(..))
3796 )),
3797 SiteKind::MinMax {
3798 max,
3799 receiver,
3800 argument,
3801 ..
3802 } => Some(format!("minmax {receiver} {argument} max={max}")),
3803 _ => None,
3804 })
3805 .collect();
3806 assert_eq!(
3807 kinds,
3808 [
3809 "range 0 v.len() inclusive=false",
3810 "minmax v[i].min(limit) 1 max=true",
3811 "minmax v[i] limit max=false",
3812 "arm 0 guarded=false",
3814 "arm n if n > 5 guarded=true",
3815 "arm 1..=3 guarded=false",
3816 "range 1 limit as usize inclusive=true",
3818 "return first Some(\"Option<u32>\")",
3819 ]
3820 );
3821 let out = render(src, &sites, &all).text;
3822 syn::parse_file(&out).expect("instrumented source parses");
3823 assert_eq!(out.lines().count(), src.lines().count());
3824 let option = sites
3825 .iter()
3826 .find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
3827 .unwrap();
3828 assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
3829 assert!(
3830 out.contains(&format!(
3831 "crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
3832 option.id
3833 )),
3834 "{out}"
3835 );
3836 assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
3837 assert!(
3838 out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
3839 "{out}"
3840 );
3841 assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
3842 assert!(
3843 out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
3844 "{out}"
3845 );
3846 assert!(
3849 out.contains("(match (&(v[i]), limit) {")
3850 && out.contains(
3851 "Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
3852 )
3853 && out.contains(
3854 ".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
3855 ),
3856 "{out}"
3857 );
3858 assert!(
3859 !out.contains(".min(limit)") && !out.contains(".max(1)"),
3860 "{out}"
3861 );
3862 assert!(
3863 out.contains("v.iter().max()"),
3864 "an iterator's max is another method: {out}"
3865 );
3866 }
3867
3868 #[test]
3869 fn macro_arguments() {
3870 let src = r#"
3871 fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
3872 assert!(a < 100);
3873 debug_assert!(a < 101, "message {}", a < 102);
3874 assert_eq!(a < 1, b < 2, "context {}", a + 3);
3875 let _ = format!("{} {name}", a < 4, name = b < 5);
3876 write!(out, "{}", a < 6).unwrap();
3877 if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
3878 custom!(a < 10);
3879 let _ = vec![a < 11; 2];
3880 vec![a + b, (a < 12) as u32]
3881 }
3882 "#;
3883 let texts: Vec<String> = found(src, 0)
3884 .unwrap()
3885 .sites
3886 .into_iter()
3887 .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
3888 .map(|s| s.text)
3889 .collect();
3890 assert_eq!(
3891 texts,
3892 [
3893 "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
3894 "a < 12"
3895 ]
3896 );
3897 let found = found(src, 0).unwrap().sites;
3898 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3899 }
3900
3901 #[test]
3902 fn non_ascii_source_keeps_byte_offsets() {
3903 let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
3904 let sites = found(src, 0).unwrap().sites;
3905 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3906 assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
3907 syn::parse_file(&render(src, &sites, &all).text).unwrap();
3908 }
3909
3910 #[test]
3911 fn unparseable_source_is_an_error() {
3912 assert!(discover("fn f( {", 0).is_err());
3913 }
3914 fn labelled(src: &str) -> Vec<String> {
3916 discover(src, 0)
3917 .unwrap()
3918 .sites
3919 .iter()
3920 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3921 .map(|s| {
3922 let kind = match &s.kind {
3923 SiteKind::Cmp { .. } => "cmp",
3924 SiteKind::Logic { .. } => "logic",
3925 SiteKind::Arith { .. } => "arith",
3926 SiteKind::Not { .. } => "not",
3927 SiteKind::Return { .. } => "return",
3928 SiteKind::MinMax { .. } => "minmax",
3929 SiteKind::Range { .. } => "range",
3930 SiteKind::Arm { .. } => "arm",
3931 SiteKind::Stmt => "stmt",
3932 SiteKind::Neg { .. } => "neg",
3933 SiteKind::Guard { .. } => "guard",
3934 SiteKind::Field { .. } => "field",
3935 SiteKind::Body { .. } => "body",
3936 };
3937 format!("{kind} {}", s.text)
3938 })
3939 .collect()
3940 }
3941
3942 #[test]
3943 fn byte_order_mark_and_interpreter_line_are_refused() {
3944 let body = "fn f(a: u8) -> bool { a > 1 }";
3945 assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
3946 assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
3947 assert_eq!(
3949 labelled(&format!("#![allow(dead_code)]\n{body}")),
3950 ["return fn f(a: u8) -> bool", "cmp a > 1"]
3951 );
3952 }
3953
3954 #[test]
3955 fn which_result_types_make_a_return_site() {
3956 let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
3957 fn b() -> Option { g() }\n\
3958 fn c() -> Vec<u8> { g() }\n\
3959 fn d() -> std::option::Option<u8> { g() }\n\
3960 fn e() -> <S>::bool { g() }\n\
3961 fn e2() -> <S as Tr>::bool { g() }\n\
3962 fn one(a: u8) -> bool { a > 1 }\n\
3963 fn two(a: u8) -> bool { let b = a; b > 1 }\n\
3964 fn early(a: u8) -> bool { return a > 1; }\n";
3965 let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
3966 .unwrap()
3967 .sites
3968 .into_iter()
3969 .filter_map(|s| match s.kind {
3970 SiteKind::Return {
3971 name,
3972 option,
3973 sole_expr,
3974 } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
3975 _ => None,
3976 })
3977 .collect();
3978 assert_eq!(
3979 returns,
3980 [
3981 (
3982 "d".to_string(),
3983 Some("std::option::Option<u8>".to_string()),
3984 Some("g()")
3985 ),
3986 ("one".to_string(), None, Some("a > 1")),
3988 ("two".to_string(), None, None),
3989 ]
3990 );
3991 }
3992
3993 #[test]
3994 fn places_chains_attributes_and_shadowed_macros() {
3995 assert_eq!(
3999 labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
4000 [
4001 "stmt #[allow(unused)] x += 1;",
4002 "stmt (x) += 2;",
4003 "arith (x) += 2"
4004 ]
4005 );
4006 assert_eq!(
4008 labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
4009 ["cmp a > 1", "stmt g(b);"]
4010 );
4011 assert_eq!(
4013 labelled(
4014 "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
4015 ),
4016 ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
4017 );
4018 assert_eq!(
4020 labelled(
4021 "macro_rules! vec { ($($t:tt)*) => {} }\n\
4022 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
4023 ),
4024 ["cmp a > 2"]
4025 );
4026 assert_eq!(
4027 labelled(
4028 "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
4029 ),
4030 ["return fn g(a: u8) -> bool", "cmp a > 2"]
4031 );
4032 }
4033
4034 #[test]
4035 fn min_max_and_ranges_that_are_left_alone() {
4036 assert_eq!(
4037 labelled(
4038 "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
4039 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
4040 ),
4041 ["minmax a.max(b)"]
4042 );
4043 let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
4045 for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
4046 assert_eq!(
4047 labelled(src),
4048 [
4049 "range a..10",
4050 "range 1..b",
4051 "range (a + 1)..(b * 2)",
4052 "arith a + 1",
4053 "arith b * 2",
4054 "neg -6"
4056 ]
4057 );
4058 let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
4059 assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
4061 assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
4062 assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
4063 }
4064
4065 #[test]
4066 fn which_arms_can_be_removed() {
4067 let src = "fn f(k: u8) -> u8 {\n\
4068 \x20 let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
4069 \x20 let b = match k { 1 => 1, NONE => 0 };\n\
4070 \x20 let c = match k { 1 => 1, n @ 0..=9 => n };\n\
4071 \x20 let d = match k {\n\
4072 \x20 1 => 1,\n\
4073 \x20 _ => 0,\n\
4074 \x20 };\n\
4075 \x20 a + b + c + d\n\
4076 }\n";
4077 let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
4078 .unwrap()
4079 .sites
4080 .into_iter()
4081 .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
4082 .map(|s| (s.id, s.line, s.column, s.text))
4083 .collect();
4084 assert_eq!(
4087 arms,
4088 [
4089 (9, 2, 23, "1 => ..".to_string()),
4091 (10, 2, 39, "2 => ..".to_string()),
4092 (11, 6, 9, "1 => ..".to_string()),
4093 ]
4094 );
4095 }
4096
4097 #[test]
4098 fn offsets_around_inserted_text() {
4099 let src = "fn f(a: u8) -> bool { a > 1 }";
4100 let sites = found(src, 0).unwrap().sites;
4101 let out = render(src, &sites, &all);
4102 let start = sites[0].start;
4103 let copied_a = out.text.find("a), &(").unwrap();
4106 assert_eq!(out.to_original(copied_a), start);
4107 assert_eq!(out.to_original(copied_a - 1), start);
4108 assert_eq!(out.to_original(copied_a + 1), start + 1);
4109 assert_eq!(out.to_original(out.text.len() + 10), src.len());
4111
4112 let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
4115 let sites = discover(src, 0).unwrap().sites;
4116 let out = render(src, &sites, &all);
4117 let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
4118 assert!(
4119 out.text[inner_probe..].starts_with("(match (b, 1)"),
4120 "{}",
4121 out.text
4122 );
4123 assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
4124 let arith = sites
4125 .iter()
4126 .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
4127 .unwrap();
4128 assert_eq!(
4129 blame(&sites, &all, out.to_original(inner_probe)),
4130 [arith.id]
4131 );
4132 assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
4134 assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
4135 let opening = "(match (b, ";
4137 let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
4138 assert!(out.text[inner_probe..].starts_with(opening));
4139 assert_eq!(out.inserted_by(first), Some(arith.id));
4140 assert_eq!(out.inserted_by(last), Some(arith.id));
4141 assert_eq!(out.inserted_by(last + 1), None);
4142 assert_eq!(out.inserted_by(0), None);
4143 }
4144 fn values(ty: &str) -> Vec<String> {
4145 let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
4146 .unwrap_or_else(|e| panic!("{ty}: {e}"));
4147 body_values(&function.sig.output)
4148 }
4149
4150 #[test]
4152 fn replacement_values_by_return_type() {
4153 let rows: &[(&str, &[&str])] = &[
4154 ("()", &["()"]),
4155 ("i8", &["0", "1", "-1"]),
4156 ("isize", &["0", "1", "-1"]),
4157 ("i128", &["0", "1", "-1"]),
4158 ("u8", &["0", "1"]),
4159 ("usize", &["0", "1"]),
4160 ("u128", &["0", "1"]),
4161 ("f32", &["0.0", "1.0", "-1.0"]),
4162 ("f64", &["0.0", "1.0", "-1.0"]),
4163 ("bool", &["true", "false"]),
4164 (
4165 "NonZeroI32",
4166 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4167 ),
4168 ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
4169 ("NonZero<u64>", &["1.try_into().unwrap()"]),
4170 (
4171 "NonZero<i64>",
4172 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4173 ),
4174 ("String", &["String::new()", "\"xyzzy\".into()"]),
4175 ("&str", &["\"\"", "\"xyzzy\""]),
4176 ("&'static str", &["\"\"", "\"xyzzy\""]),
4177 ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
4179 ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
4180 (
4181 "&mut bool",
4182 &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
4183 ),
4184 (
4185 "&[u8]",
4186 &[
4187 "Vec::leak(Vec::new())",
4188 "Vec::leak(vec![0])",
4189 "Vec::leak(vec![1])",
4190 ],
4191 ),
4192 (
4193 "&mut [bool]",
4194 &[
4195 "Vec::leak(Vec::new())",
4196 "Vec::leak(vec![true])",
4197 "Vec::leak(vec![false])",
4198 ],
4199 ),
4200 ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
4201 ("io::Result<()>", &["Ok(())"]),
4202 ("fmt::Result", &["Ok(Default::default())"]),
4204 ("Result", &["Ok(Default::default())"]),
4205 ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
4206 ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
4207 ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
4208 (
4209 "std::rc::Rc<u8>",
4210 &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
4211 ),
4212 ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
4213 ("RefCell<()>", &["RefCell::new(())"]),
4214 ("Mutex<()>", &["Mutex::new(())"]),
4215 ("Cell<()>", &["Cell::new(())"]),
4216 (
4217 "HashSet<u8>",
4218 &[
4219 "HashSet::new()",
4220 "HashSet::from_iter([0])",
4221 "HashSet::from_iter([1])",
4222 ],
4223 ),
4224 (
4225 "BTreeSet<()>",
4226 &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
4227 ),
4228 (
4229 "BinaryHeap<()>",
4230 &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
4231 ),
4232 (
4233 "LinkedList<()>",
4234 &["LinkedList::new()", "LinkedList::from_iter([()])"],
4235 ),
4236 (
4237 "VecDeque<()>",
4238 &["VecDeque::new()", "VecDeque::from_iter([()])"],
4239 ),
4240 (
4241 "HashMap<bool, u8>",
4242 &[
4243 "HashMap::new()",
4244 "HashMap::from_iter([(true, 0)])",
4245 "HashMap::from_iter([(true, 1)])",
4246 "HashMap::from_iter([(false, 0)])",
4247 "HashMap::from_iter([(false, 1)])",
4248 ],
4249 ),
4250 (
4251 "std::collections::BTreeMap<(), ()>",
4252 &[
4253 "std::collections::BTreeMap::new()",
4254 "std::collections::BTreeMap::from_iter([((), ())])",
4255 ],
4256 ),
4257 (
4258 "Cow<'a, str>",
4259 &[
4260 "Cow::Borrowed(\"\")",
4261 "Cow::Owned(\"\".to_owned())",
4262 "Cow::Borrowed(\"xyzzy\")",
4263 "Cow::Owned(\"xyzzy\".to_owned())",
4264 ],
4265 ),
4266 ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
4267 ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
4268 (
4269 "(u8, bool)",
4270 &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
4271 ),
4272 ("(bool,)", &["(true,)", "(false,)"]),
4273 ("HttpResponse", &["HttpResponse::Ok().finish()"]),
4274 (
4275 "actix_web::HttpResponse",
4276 &["actix_web::HttpResponse::Ok().finish()"],
4277 ),
4278 ("Config", &["Default::default()"]),
4279 ("Self", &["Default::default()"]),
4280 ("<T as Tr>::Out", &["Default::default()"]),
4281 ("<T as Tr>::String", &["Default::default()"]),
4283 ("<T>::bool", &["Default::default()"]),
4284 ("fn(u8) -> u8", &["Default::default()"]),
4285 ("*const u8", &["Default::default()"]),
4286 (
4288 "Result<Option<String>, E>",
4289 &[
4290 "Ok(None)",
4291 "Ok(Some(String::new()))",
4292 "Ok(Some(\"xyzzy\".into()))",
4293 ],
4294 ),
4295 ("(Vec<()>)", &["vec![]", "vec![()]"]),
4296 ("Option<Config>", &["None", "Some(Default::default())"]),
4297 ("!", &[]),
4299 ("impl Iterator<Item = u8>", &[]),
4300 ("Box<impl Fn()>", &[]),
4301 ("Option<!>", &["None"]),
4302 ];
4303 for (ty, expected) in rows {
4304 assert_eq!(values(ty), *expected, "{ty}");
4305 }
4306 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4308 assert_eq!(body_values(&unit.sig.output), ["()"]);
4309 }
4310
4311 #[test]
4312 fn which_functions_get_their_body_replaced() {
4313 let src = r#"
4314 fn plain(a: u8) -> u8 { a + 1 }
4315 fn already(a: u8) -> bool { let _ = a; true }
4316 fn sole() -> bool { true }
4317 fn spaced() -> (u8, bool) { ( 0 , true ) }
4318 unsafe fn raw(a: u8) -> u8 { a }
4319 fn empty() {}
4320 fn one_call(s: &mut S) { s.go(); }
4321 fn two_calls(s: &mut S) { s.go(); s.stop(); }
4322 fn typed(s: &mut S) -> u8 { s.exit(); }
4323 fn tight() -> bool {true}
4324 #[rustfmt::skip]
4325 fn formatted(a: u8) -> u8 { a + 6 }
4326 #[mutants::timeout(5)]
4327 fn slow(a: u8) -> u8 { a + 7 }
4328 impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
4329 trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
4330 fn one_let(a: u8) { let _ = a; }
4331 fn never() -> ! { loop {} }
4332 fn hidden() -> impl Sized { 1 }
4333 #[mutants::skip]
4334 fn marked(a: u8) -> u8 { a + 2 }
4335 #[cfg_attr(test, mutants::skip)]
4336 fn marked_in_tests(a: u8) -> u8 { a + 3 }
4337 #[mutants::skip]
4338 impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
4339 #[mutants::skip]
4340 mod generated { fn inner(a: u8) -> u8 { a + 5 } }
4341 trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
4342 async fn later() -> u8 { 9 }
4343 "#;
4344 let sites = discover(src, 0).unwrap().sites;
4345 let bodies: Vec<String> = sites
4346 .iter()
4347 .filter_map(|s| match &s.kind {
4348 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
4349 _ => None,
4350 })
4351 .collect();
4352 assert_eq!(
4353 bodies,
4354 [
4355 "plain 0",
4356 "plain 1",
4357 "already true",
4358 "already false",
4359 "sole false",
4361 "spaced (0, false)",
4362 "spaced (1, true)",
4363 "spaced (1, false)",
4364 "two_calls ()",
4366 "typed 0",
4368 "typed 1",
4369 "tight false",
4370 "formatted 0",
4372 "formatted 1",
4373 "slow 0",
4374 "slow 1",
4375 "one_let ()",
4376 "provided 0",
4377 "provided 1",
4378 "later 0",
4379 "later 1",
4380 ]
4381 );
4382 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
4384 for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
4385 assert!(!texts.contains(&skipped), "{skipped}");
4386 }
4387 for mutated in ["a + 1", "a + 6", "a + 7"] {
4388 assert!(texts.contains(&mutated), "{mutated}");
4389 }
4390 let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
4391 assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
4392
4393 let body = sites
4394 .iter()
4395 .find(|s| matches!(s.kind, SiteKind::Body { .. }))
4396 .unwrap();
4397 assert_eq!(
4398 (body.line, body.column, body.text.as_str()),
4399 (2, 13, "fn plain(a: u8) -> u8")
4400 );
4401 let out = render(src, &sites, &all).text;
4402 syn::parse_file(&out).expect("instrumented source parses");
4403 assert_eq!(out.lines().count(), src.lines().count());
4404 assert!(
4405 out.contains(
4406 "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
4407 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
4408 ),
4409 "{out}"
4410 );
4411 let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
4414 let sites = discover(tight, 0).unwrap().sites;
4415 let out = render(tight, &sites, &all).text;
4416 syn::parse_file(&out).expect("instrumented source parses");
4417 assert!(
4418 out.starts_with(
4419 "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
4420 if !crate::__tmt_rt::live(1u32) { return true; } \
4421 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
4422 ),
4423 "{out}"
4424 );
4425 assert!(
4426 out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
4427 "{out}"
4428 );
4429 }
4430
4431 #[test]
4432 fn minus_guards_and_fields() {
4433 let src = r#"
4434 fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
4435 let a = -x + -5 - -0 + (-0.0 * -y) as i32;
4436 let b = match k {
4437 Kind::A(n) if n > 1 => 1,
4438 Kind::A(n) if let Some(m) = half(n) => m,
4439 Kind::B if x > 0 && let Some(m) = half(x) => m,
4440 #[cfg(any())]
4441 Kind::B if x > 2 => 2,
4442 Kind::B => 3,
4443 };
4444 let c = match b { n if n > 3 => 1, _ => 0 };
4445 let first = Options { depth: a, name, ..base };
4446 let second = Options { depth: -b, ..Default::default() };
4447 let third = Wrap::<u8> { 0: c, ..Wrap::new() };
4448 let _ = Options { depth: 1, ..base.clone() };
4449 let _ = Options { depth: 2, ..make(3) };
4450 let _ = Options { depth: 6, ..(pick())() };
4451 let _ = -2.5 + y;
4452 let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
4453 let _ = Options { depth: 5, name: n, strict: false };
4454 first
4455 }
4456 "#;
4457 let sites = found(src, 0).unwrap().sites;
4458 let kinds: Vec<String> = sites
4459 .iter()
4460 .filter_map(|s| match &s.kind {
4461 SiteKind::Neg {
4462 operand, literal, ..
4463 } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
4464 SiteKind::Guard { can_be_false } => {
4465 Some(format!("guard {} | can_be_false={can_be_false}", s.text))
4466 }
4467 SiteKind::Field {
4468 name,
4469 shorthand,
4470 from_base: Some(from_base),
4471 ..
4472 } => Some(format!(
4473 "field {} | {name} | shorthand={shorthand} | {from_base}",
4474 s.text
4475 )),
4476 _ => None,
4477 })
4478 .collect();
4479 assert_eq!(
4480 kinds,
4481 [
4482 "neg -x | x | literal=false",
4483 "neg -5 | 5 | literal=true",
4484 "neg -0.0 | 0.0 | literal=true",
4486 "neg -y | y | literal=false",
4487 "guard n > 1 | can_be_false=true",
4489 "guard n > 3 | can_be_false=false",
4491 "field depth: a | depth | shorthand=false | (base).depth",
4492 "field name | name | shorthand=true | (base).name",
4493 "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
4494 "neg -b | b | literal=false",
4495 "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
4496 "neg -2.5 | 2.5 | literal=true",
4497 "field strict: true | strict | shorthand=false | (*other).strict",
4500 ]
4501 );
4502 let field = sites
4504 .iter()
4505 .find(|s| s.text == "depth: a")
4506 .expect("the field is a site");
4507 let line = src.lines().nth(field.line - 1).unwrap();
4508 assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
4509 assert_eq!(&src[field.start..field.end], "a");
4510 let out = render(src, &sites, &all).text;
4511 syn::parse_file(&out).expect("instrumented source parses");
4512 assert_eq!(out.lines().count(), src.lines().count());
4513 for expected in [
4514 "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
4516 "u32) { -__tmt_a } else { __tmt_a } })",
4518 "u32) { -5 } else { 5 })",
4519 "Kind::A(n) if crate::__tmt_rt::ret(",
4521 "u32, (match (&(n), &(1))",
4522 "n if crate::__tmt_rt::arm(",
4523 ") && (crate::__tmt_rt::ret(",
4524 "depth: if crate::__tmt_rt::live(",
4525 "{ a } else { (base).depth }",
4526 "name: if crate::__tmt_rt::live(",
4528 "{ name } else { (base).name }, ..base }",
4529 "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
4530 "0: if crate::__tmt_rt::live(",
4531 "Options { depth: 1, ..base.clone() }",
4532 "Options { depth: 2, ..make(3) }",
4533 "Options { depth: 6, ..(pick())() }",
4534 "Options { depth: 5, name: n, strict: false }",
4535 ] {
4536 assert!(out.contains(expected), "{expected}\n{out}");
4537 }
4538 assert!(
4539 !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
4540 "{out}"
4541 );
4542 }
4543 fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
4545 sites
4546 .iter()
4547 .flat_map(|site| {
4548 source_mutants(site).into_iter().map(|m| {
4549 let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
4550 syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
4551 format!("{} -> {}: {}", m.what, m.into, text.trim())
4552 })
4553 })
4554 .collect()
4555 }
4556
4557 #[test]
4558 fn what_cannot_be_probed_is_mutated_in_the_source() {
4559 let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
4562 fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
4563 fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
4564 impl S { const fn k(&self) -> u8 { -self.0 } }\n\
4565 trait T { const fn d(a: u8) -> u8 { a } }\n";
4566 let found = discover(src, 0).unwrap();
4567 assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
4568 let places: Vec<(usize, usize, &str)> = found
4569 .rebuild_sites
4570 .iter()
4571 .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
4572 .map(|s| (s.line, s.column, s.text.as_str()))
4573 .collect();
4574 assert_eq!(
4575 places,
4576 [
4577 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4578 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4579 (1, 36, "a < b"),
4580 (2, 28, "*m.entry(k).or_insert(0) += 1"),
4581 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4582 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4583 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4584 (3, 53, "0..n"),
4586 (4, 10, "const fn k(&self) -> u8"),
4587 (4, 10, "const fn k(&self) -> u8"),
4588 (4, 36, "-self.0"),
4589 (5, 11, "const fn d(a: u8) -> u8"),
4590 (5, 11, "const fn d(a: u8) -> u8"),
4591 ]
4592 );
4593 assert_eq!(
4594 found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
4595 (0..found.sites.len() as u32).collect::<Vec<_>>()
4596 );
4597 let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
4598 assert_eq!(
4599 numbered,
4600 [
4601 "fn f(m: &mut Map, k: u8)",
4602 "*m.entry(k).or_insert(0) += 1;",
4603 "m.total -= 1;",
4604 "m.total -= 1",
4605 ]
4606 );
4607 assert_eq!(
4608 mutated(src, &found.rebuild_sites)
4609 .iter()
4610 .map(|line| line.lines().next().unwrap().to_string())
4611 .take(5)
4612 .collect::<Vec<_>>(),
4613 [
4614 "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
4615 "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
4616 "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
4617 "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
4618 "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
4619 ]
4620 );
4621 let whats: Vec<String> = found
4622 .rebuild_sites
4623 .iter()
4624 .flat_map(|site| {
4625 source_mutants(site)
4626 .into_iter()
4627 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4628 })
4629 .skip(5)
4630 .collect();
4631 assert_eq!(
4632 whats,
4633 [
4634 "*m.entry(k).or_insert(0) += 1: += -> -=",
4635 "*m.entry(k).or_insert(0) += 1: += -> *=",
4636 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
4637 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
4638 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
4639 "0..n: .. -> ..=",
4640 "const fn k(&self) -> u8: body -> 0",
4641 "const fn k(&self) -> u8: body -> 1",
4642 "-self.0: - -> ",
4643 "const fn d(a: u8) -> u8: body -> 0",
4644 "const fn d(a: u8) -> u8: body -> 1",
4645 ]
4646 );
4647 }
4648
4649 #[test]
4650 fn fields_are_removed_from_arbitrary_struct_updates() {
4651 for base in ["base", "make(seed)", "builder.make(seed)"] {
4653 for field in ["value: 9", "value"] {
4654 for attribute in ["", "#[cfg(any())] "] {
4655 let original =
4656 format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
4657 let found = discover(&original, 0).unwrap();
4658 let fields: Vec<_> = found
4659 .sites
4660 .iter()
4661 .chain(&found.rebuild_sites)
4662 .flat_map(source_mutants)
4663 .filter(|mutant| mutant.what == "field" && mutant.into == "value")
4664 .collect();
4665 if attribute.is_empty() {
4666 assert_eq!(fields.len(), 1, "{original}");
4667 let m = &fields[0];
4668 let changed = format!(
4669 "{}{}{}",
4670 &original[..m.start],
4671 m.replacement,
4672 &original[m.end..]
4673 );
4674 assert_eq!(
4675 changed,
4676 format!("fn f() -> S {{ S {{ other: 2, ..{base} }} }}")
4677 );
4678 syn::parse_file(&changed).unwrap();
4679 } else {
4680 assert!(fields.is_empty(), "{original}");
4681 }
4682 }
4683 }
4684 }
4685 let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
4686 assert!(
4687 plain
4688 .sites
4689 .iter()
4690 .chain(&plain.rebuild_sites)
4691 .flat_map(source_mutants)
4692 .all(|m| m.what != "field")
4693 );
4694 }
4695
4696 #[test]
4697 fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
4698 for outer in ["Wrapper", "Option", "Result"] {
4700 for inner in ["bool", "impl Iterator<Item = u8>"] {
4701 for error in [false, true] {
4702 let error_values: &[&str] = if error { &["7"] } else { &[] };
4703 let extra = if outer == "Result" { ", u8" } else { "" };
4704 let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
4705 let found = discover_with_errors(&source, 0, error_values).unwrap();
4706 let values: Vec<&str> = found
4707 .sites
4708 .iter()
4709 .chain(&found.rebuild_sites)
4710 .filter_map(|site| match &site.kind {
4711 SiteKind::Body { value, .. } => Some(value.as_str()),
4712 _ => None,
4713 })
4714 .collect();
4715 let example = match (outer, inner) {
4716 ("Wrapper", "bool") => "Wrapper::from_iter([false])",
4717 ("Option", "bool") => "Some(false)",
4718 ("Result", "bool") => "Ok(false)",
4719 ("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
4720 ("Option", _) => "Some(::core::iter::once(1))",
4721 ("Result", _) => "Ok(::core::iter::once(1))",
4722 _ => unreachable!(),
4723 };
4724 assert!(values.contains(&example), "{source}: {values:?}");
4725 assert_eq!(
4726 values.contains(&"Err(7)"),
4727 outer == "Result" && error,
4728 "{source}"
4729 );
4730 if inner != "bool" {
4731 assert!(found.sites.is_empty(), "{source}");
4732 }
4733 }
4734 }
4735 }
4736 }
4737
4738 #[test]
4739 fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
4740 let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
4741 fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
4742 let found = discover(source, 0).unwrap();
4743 let removals: Vec<_> = found
4744 .sites
4745 .iter()
4746 .chain(&found.rebuild_sites)
4747 .flat_map(source_mutants)
4748 .filter(|mutant| mutant.replacement.is_empty())
4749 .map(|mutant| &source[mutant.start..mutant.end])
4750 .collect();
4751 assert!(removals.contains(&"v.clear();"), "{removals:?}");
4752 assert!(removals.contains(&"0 => 4,"), "{removals:?}");
4753 assert!(
4754 removals.contains(&"#[allow(unused)] 1 => 5,"),
4755 "{removals:?}"
4756 );
4757 }
4758
4759 #[test]
4760 fn source_mutants_of_every_kind() {
4761 let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
4762 let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
4763 O { on: x, a, ..base } }";
4764 let sites = found(src, 0).unwrap().sites;
4765 assert_eq!(mutated(src, &sites).len(), 18);
4767 let changes: Vec<String> = sites
4768 .iter()
4769 .flat_map(source_mutants)
4770 .map(|m| {
4771 format!(
4772 "{} -> {} | `{}` becomes `{}`",
4773 m.what,
4774 m.into,
4775 &src[m.start..m.end],
4776 m.replacement
4777 )
4778 })
4779 .collect();
4780 assert_eq!(
4781 changes,
4782 [
4783 "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
4785 "arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
4786 "guard -> true | `n >= 1` becomes `true`",
4787 ">= -> < | ` >= ` becomes ` < `",
4788 "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
4789 "! -> | `!` becomes ``",
4790 "!= -> == | ` != ` becomes ` == `",
4791 "<= -> > | ` <= ` becomes ` > `",
4792 "- -> | `-` becomes ``",
4793 "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
4794 "> -> == | ` > ` becomes ` == `",
4795 "> -> < | ` > ` becomes ` < `",
4796 "> -> >= | ` > ` becomes ` >= `",
4797 "% -> / | ` % ` becomes ` / `",
4798 "% -> + | `a % b` becomes `(a + b)`",
4799 "== -> != | ` == ` becomes ` != `",
4800 "field -> on | `on: x,` becomes ``",
4801 "field -> a | `a,` becomes ``",
4802 ]
4803 );
4804 let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
4806 let sites = discover(src, 0).unwrap().sites;
4807 for site in &sites {
4808 let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
4809 assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
4810 }
4811 let ends = |src: &str| -> Vec<String> {
4813 discover(src, 0)
4814 .unwrap()
4815 .sites
4816 .iter()
4817 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4818 .flat_map(source_mutants)
4819 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4820 .collect()
4821 };
4822 assert_eq!(
4823 ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
4824 ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
4825 );
4826 assert_eq!(
4827 ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
4828 ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
4829 );
4830 }
4831
4832 #[test]
4833 fn iterators_to_return_instead() {
4834 let values = |ty: &str| {
4835 let function: syn::ItemFn =
4836 syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
4837 iterator_values(&function.sig.output)
4838 };
4839 assert_eq!(
4840 values("impl Iterator<Item = bool>"),
4841 [
4842 "::core::iter::empty()",
4843 "::core::iter::once(true)",
4844 "::core::iter::once(false)"
4845 ]
4846 );
4847 assert_eq!(
4848 values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
4849 3
4850 );
4851 assert_eq!(
4853 values("impl Iterator<Extra = u8, Item = ()>"),
4854 ["::core::iter::empty()", "::core::iter::once(())"]
4855 );
4856 assert_eq!(
4858 values("impl Iterator<Item = impl Sized>"),
4859 ["::core::iter::empty()"]
4860 );
4861 for other in [
4862 "impl Sized",
4863 "impl Iterator",
4864 "impl IntoIterator<Item = u8>",
4865 "Box<dyn Iterator<Item = u8>>",
4866 "u8",
4867 "()",
4868 ] {
4869 assert!(values(other).is_empty(), "{other}");
4870 }
4871 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4872 assert!(iterator_values(&unit.sig.output).is_empty());
4873 }
4874
4875 fn built(src: &str) -> Vec<String> {
4877 let found = discover(src, 0).unwrap();
4878 found
4879 .rebuild_sites
4880 .iter()
4881 .flat_map(source_mutants)
4882 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4883 .collect()
4884 }
4885
4886 #[test]
4887 fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
4888 let bodies = |src: &str| -> Vec<(String, bool)> {
4889 discover(src, 0)
4890 .unwrap()
4891 .sites
4892 .iter()
4893 .filter_map(|site| match &site.kind {
4894 SiteKind::Body {
4895 value, sole_expr, ..
4896 } => Some((value.clone(), sole_expr.is_some())),
4897 _ => None,
4898 })
4899 .collect()
4900 };
4901 let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
4902 assert_eq!(values("fn t() -> bool { true }"), ["false"]);
4904 assert_eq!(values("fn n() -> u8 { 0 }"), ["1"]);
4905 assert_eq!(
4906 values("fn s() -> String { String :: new () }"),
4907 ["\"xyzzy\".into()"]
4908 );
4909 assert_eq!(
4911 values("fn s() -> &'static str { \" \" }"),
4912 ["\"\"", "\"xyzzy\""]
4913 );
4914 for (body, only_computes) in [
4917 ("n > 0", true),
4918 ("!(self.limit < n) && n as u8 != 3", true),
4919 ("(n, 1).0 > *&n", true),
4920 ("self.push(n) > 0", false),
4921 ("next() > 0", false),
4922 ("matches!(n, 1)", false),
4923 ("(if n > 1 { n } else { 0 }) > 0", false),
4924 ("list[n] > 0", false),
4925 ("check(n)? > 0", false),
4926 ("(self.count += n) == ()", false),
4927 ("(self.count = n) == ()", false),
4928 ] {
4929 let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
4930 let all = bodies(&src);
4931 assert_eq!(all.len(), 2, "{body}");
4932 assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
4933 }
4934 }
4935
4936 #[test]
4937 fn items_are_named_by_what_is_around_them() {
4938 let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
4939 mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
4940 impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
4941 impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
4942 trait Tr { fn provided(&self) {} fn required(&self); }\n\
4943 static S: u8 = 3;\nlet";
4944 assert!(named_items(src).is_empty());
4946 let src = src.strip_suffix("let").unwrap();
4947 let items = named_items(src);
4948 let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
4949 assert_eq!(
4950 names,
4951 [
4952 "top",
4953 "top::inner",
4954 "m::in_mod",
4955 "m::K",
4956 "Store::commit",
4957 "Store::LIMIT",
4958 "<fmt::Display for Id<T>>::fmt",
4959 "Tr::provided",
4960 "Tr::required",
4961 "S",
4962 ]
4963 );
4964 let at = |text: &str| src.find(text).unwrap();
4966 assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
4967 assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
4968 assert_eq!(enclosing_item(&items, at("fn top")), "top");
4969 assert_eq!(enclosing_item(&items, at("mod m")), "");
4970 assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
4971 assert_eq!(enclosing_item(&items, src.len()), "");
4972 let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
4974 assert_eq!(enclosing_item(&items, first - 1), "");
4975 assert_eq!(enclosing_item(&items, first), "m::in_mod");
4976 assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
4977 assert_eq!(enclosing_item(&items, after), "");
4978 let text = "ab\nçd e\n";
4980 assert_eq!(offset_of(text, 1, 1), Some(0));
4981 assert_eq!(offset_of(text, 1, 2), Some(1));
4982 assert_eq!(offset_of(text, 2, 1), Some(3));
4983 assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
4984 assert_eq!(offset_of(text, 2, 99), Some(text.len()));
4985 assert_eq!(offset_of(text, 0, 1), None);
4986 assert_eq!(offset_of(text, 1, 0), None);
4987 }
4988
4989 #[test]
4990 fn only_the_range_of_a_for_is_probed() {
4991 let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
4992 for _ in a..b {}\n\
4993 for _ in (a..=b) {}\n\
4994 for _ in (a..b).rev() {}\n\
4995 let kept = a..b;\n\
4996 let _ = &v[a as usize..b as usize];\n\
4997 for _ in kept.clone() {}\n\
4998 for _ in 0..3 {}\n\
4999 let _ = &v[0..3];\n\
5000 (a..=b).count() }";
5001 let all = discover(src, 0).unwrap();
5002 let ranges = |sites: &[Site]| -> Vec<usize> {
5003 sites
5004 .iter()
5005 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
5006 .map(|site| site.line)
5007 .collect()
5008 };
5009 assert_eq!(ranges(&all.sites), [2, 3]);
5011 assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
5014 let literal: Vec<(&str, String)> = all
5015 .rebuild_sites
5016 .iter()
5017 .filter(|site| site.line == 8 || site.line == 9)
5018 .flat_map(|site| {
5019 source_mutants(site)
5020 .into_iter()
5021 .map(move |mutant| (site.text.as_str(), mutant.replacement))
5022 })
5023 .collect();
5024 assert_eq!(
5025 literal,
5026 [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
5027 );
5028 }
5029
5030 #[test]
5031 fn what_marks_code_as_not_to_be_mutated() {
5032 let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
5033 #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
5034 #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
5035 #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
5036 #[mutants::skip] mod generated;\n\
5037 #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
5038 mod plain;\n\
5039 mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
5040 #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
5041 let all = discover(src, 0).unwrap();
5042 let texts: Vec<&str> = found_arith(&all.sites);
5043 assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
5044 assert_eq!(
5046 all.test_modules,
5047 [
5048 TestModule {
5049 name: "generated".to_string(),
5050 path: None
5051 },
5052 TestModule {
5053 name: "other".to_string(),
5054 path: Some("gen/other.rs".to_string())
5055 },
5056 ]
5057 );
5058 }
5059
5060 fn found_arith(sites: &[Site]) -> Vec<&str> {
5061 sites
5062 .iter()
5063 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
5064 .map(|site| site.text.as_str())
5065 .collect()
5066 }
5067
5068 #[test]
5069 fn a_replaced_operator_keeps_its_operands() {
5070 assert_eq!(
5073 built("const X: i32 = 8 - 2 * 3;"),
5074 [
5075 "const X: i32 = 8 + 2 * 3;",
5076 "const X: i32 = (8) / (2 * 3);",
5077 "const X: i32 = 8 - 2 / 3;",
5078 "const X: i32 = 8 - (2 + 3);",
5079 ]
5080 );
5081 assert_eq!(
5082 built("const B: bool = P || Q && R;"),
5083 [
5084 "const B: bool = (P) && (Q && R);",
5085 "const B: bool = P || (Q || R);",
5086 ]
5087 );
5088 assert_eq!(
5089 built("const M: u8 = A & B | C;"),
5090 [
5091 "const M: u8 = (A & B) & (C);",
5092 "const M: u8 = (A & B) ^ (C);",
5093 "const M: u8 = (A | B) | C;",
5094 "const M: u8 = (A ^ B) | C;",
5095 ]
5096 );
5097 assert_eq!(
5098 built("const S: u8 = 1 << 2 + 1;"),
5099 [
5100 "const S: u8 = 1 >> 2 + 1;",
5101 "const S: u8 = 1 << 2 - 1;",
5102 "const S: u8 = 1 << (2) * (1);",
5103 ]
5104 );
5105 assert_eq!(
5107 built("const C: bool = A + 1 < B;")[..3],
5108 [
5109 "const C: bool = A + 1 == B;",
5110 "const C: bool = A + 1 > B;",
5111 "const C: bool = A + 1 <= B;",
5112 ]
5113 );
5114 let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
5115 for expected in [
5116 "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
5117 "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
5118 "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
5119 ] {
5120 assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
5121 }
5122 }
5123
5124 #[test]
5125 fn excluded_parent_items_do_not_contribute_const_sites() {
5126 let source = r#"
5127 #[cfg(test)] enum TestEnum { A = 1 + 2 }
5128 #[mutants::skip] struct Skip { a: [u8; 2 + 3] }
5129 #[cfg(test)] type Alias = [u8; 3 + 4];
5130 #[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
5131 #[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
5132 struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
5133 fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
5134 const DATA: [u8; 7 + 8] = [0; 15];
5135 "#;
5136 let found = discover(source, 0).unwrap();
5137 let sites: Vec<_> = found
5138 .rebuild_sites
5139 .iter()
5140 .map(|site| site.text.as_str())
5141 .collect();
5142 assert_eq!(sites, ["7 + 8"]);
5143 }
5144
5145 #[test]
5146 fn compile_time_expressions_get_source_mutants_but_never_probes() {
5147 for (place, context) in [
5149 ("inline", "let _ = const { 6 * 7 };"),
5150 ("repeat", "let _ = [0u8; 6 * 7];"),
5151 ("type length", "let _: [u8; 6 * 7];"),
5152 ("discriminant", "enum Value { One = 6 * 7 }"),
5153 ("const argument", "let _: Items<{ 6 * 7 }>;"),
5154 ("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
5155 ] {
5156 for qualifier in ["", "const "] {
5157 for marker in ["", "#[mutants::skip] "] {
5158 let source =
5159 format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
5160 let found = discover(&source, 0).unwrap();
5161 let variants: Vec<_> = found
5162 .rebuild_sites
5163 .iter()
5164 .filter(|site| site.text == "6 * 7")
5165 .flat_map(source_mutants)
5166 .map(|mutant| mutant.into)
5167 .collect();
5168 let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
5169 assert_eq!(variants, expected, "{place}: {source}");
5170 assert!(
5171 found.sites.iter().all(|site| site.text != "6 * 7"),
5172 "{source}"
5173 );
5174 assert_eq!(
5175 found.sites.iter().any(|site| site.text == "x * 2"),
5176 marker.is_empty() && qualifier.is_empty(),
5177 "{source}"
5178 );
5179 }
5180 }
5181 }
5182 }
5183
5184 #[test]
5185 fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
5186 let source = r#"
5187 /// The mutants::skip attribute is documented here.
5188 #[cfg(any(test, feature = "production"))]
5189 fn public(x: u32) -> u32 { x + 1 }
5190
5191 #[cfg(all(test, feature = "production"))]
5192 fn for_tests(x: u32) -> u32 { x + 2 }
5193
5194 #[cfg_attr(any(), mutants::skip)]
5195 fn skipped(x: u32) -> u32 { x + 3 }
5196 "#;
5197 let found = discover(source, 0).unwrap();
5198 let arithmetic: Vec<_> = found
5199 .sites
5200 .iter()
5201 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
5202 .map(|site| site.text.as_str())
5203 .collect();
5204 assert_eq!(arithmetic, ["x + 1"]);
5205 }
5206
5207 #[test]
5208 fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
5209 let src = "const HALF: u64 = SPAN / 2;\n\
5210 static LIMIT: i32 = -(1 << 4);\n\
5211 impl S { const K: bool = A < B; }\n\
5212 trait T { const D: u8 = 3 + 4; const R: u8; }\n\
5213 #[cfg(test)]\n\
5214 const ONLY_IN_TESTS: u8 = 5 + 6;\n\
5215 #[mutants::skip]\n\
5216 const MARKED: u8 = 7 + 8;\n\
5217 #[cfg(test)]\n\
5218 static TEST_LIMIT: u8 = 9 + 1;\n\
5219 impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
5220 trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
5221 fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
5222 fn one(s: &mut S) { s.go(); }\n\
5223 fn two(s: &mut S) { s.go(); s.stop(); }\n\
5224 fn value(s: &mut S) -> u8 { s.get() }\n";
5225 let found = discover(src, 0).unwrap();
5226 let built: Vec<String> = found
5227 .rebuild_sites
5228 .iter()
5229 .flat_map(|site| {
5230 source_mutants(site)
5231 .into_iter()
5232 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
5233 })
5234 .collect();
5235 assert_eq!(
5236 built,
5237 [
5238 "SPAN / 2: / -> *",
5239 "SPAN / 2: / -> %",
5240 "-(1 << 4): - -> ",
5241 "1 << 4: << -> >>",
5242 "A < B: < -> ==",
5243 "A < B: < -> >",
5244 "A < B: < -> <=",
5245 "3 + 4: + -> -",
5246 "3 + 4: + -> *",
5247 "2 + 3: + -> -",
5248 "2 + 3: + -> *",
5249 "60 * 60: * -> /",
5251 "60 * 60: * -> +",
5252 ]
5253 );
5254 mutated(src, &found.rebuild_sites);
5255 let probed: Vec<&str> = found
5257 .sites
5258 .iter()
5259 .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
5260 .map(|s| s.text.as_str())
5261 .collect();
5262 assert_eq!(probed, ["x + 60 * 60"]);
5263 assert_eq!(found.single_statement_bodies, ["one"]);
5265 let bodies: Vec<String> = found
5266 .sites
5267 .iter()
5268 .filter_map(|s| match &s.kind {
5269 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
5270 _ => None,
5271 })
5272 .collect();
5273 assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
5274 }
5275 #[test]
5276 fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
5277 for context in [
5279 "fn f() { @let _ = [0u8; 6 * 7]; }",
5280 "fn f() { let _ = @const { 6 * 7 }; }",
5281 "struct Items<@const N: usize = { 6 * 7 }>;",
5282 "@enum E { A = 6 * 7 }",
5283 "enum E { @A = 6 * 7 }",
5284 "enum E { @A([u8; 6 * 7]) }",
5285 "@struct S { a: [u8; 6 * 7] }",
5286 "struct S { @a: [u8; 6 * 7] }",
5287 "@union U { a: [u8; 6 * 7] }",
5288 "@trait T { const D: [u8; 6 * 7]; }",
5289 "trait T { @type A = [u8; 6 * 7]; }",
5290 "@type A = [u8; 6 * 7];",
5291 "impl T for S { @type A = [u8; 6 * 7]; }",
5292 ] {
5293 for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
5294 let source = context.replace('@', attribute);
5295 let found = discover(&source, 0).unwrap();
5296 let expected: &[&str] = if attribute.is_empty() {
5297 &["6 * 7"]
5298 } else {
5299 &[]
5300 };
5301 assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
5302 assert!(found_arith(&found.sites).is_empty(), "{source}");
5303 }
5304 }
5305 for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
5307 let source =
5308 format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
5309 let found = discover(&source, 0).unwrap();
5310 assert!(found.sites.is_empty(), "{source}");
5311 assert!(found.rebuild_sites.is_empty(), "{source}");
5312 }
5313 }
5314
5315 #[test]
5316 fn compile_time_expressions_are_found_inside_types() {
5317 let built = |source: &str| -> Vec<String> {
5318 let found = discover(source, 0).unwrap();
5319 assert!(found_arith(&found.sites).is_empty(), "{source}");
5320 found_arith(&found.rebuild_sites)
5321 .into_iter()
5322 .map(str::to_string)
5323 .collect()
5324 };
5325 assert_eq!(
5327 built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
5328 ["1 + 2", "3 + 4"]
5329 );
5330 assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
5332 assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
5335 }
5336
5337 #[test]
5338 fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
5339 let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
5340 #[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
5341 #[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
5342 #[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
5343 #[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
5344 #[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
5345 let found = discover(src, 0).unwrap();
5346 assert_eq!(
5347 found_arith(&found.sites),
5348 ["a + 1", "a + 2", "a + 5", "a + 6"]
5349 );
5350 }
5351
5352 #[test]
5353 fn which_arms_are_probed_built_or_left_alone() {
5354 let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
5355 \x20 let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
5356 \x20 let q = match k { Kind::A => 1, Kind::B => 2 };\n\
5357 \x20 let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
5358 \x20 p + q + r\n\
5359 }\n";
5360 let found = discover(src, 0).unwrap();
5361 let arms = |sites: &[Site]| -> Vec<String> {
5362 sites
5363 .iter()
5364 .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
5365 .map(|site| site.text.clone())
5366 .collect()
5367 };
5368 assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
5370 assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
5374 let in_arms: Vec<&str> = found_arith(&found.sites)
5376 .into_iter()
5377 .filter(|text| text.starts_with("a + "))
5378 .collect();
5379 assert_eq!(in_arms, ["a + 3", "a + 4"]);
5380 }
5381
5382 #[test]
5383 fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
5384 let src = "fn f(a: u8, base: S) {\n\
5385 \x20 let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
5386 \x20 g(#[mutants::skip] S { v: a + 4, ..base });\n\
5387 \x20 g(#[cfg(test)] S { v: a + 5, ..base });\n\
5388 \x20 g(#[allow(unused)] S { v: a + 6, ..base });\n\
5389 \x20 g(<S as Tr>::Out { v: a + 7, ..base });\n\
5390 }\n";
5391 let found = discover(src, 0).unwrap();
5392 let fields = |sites: &[Site]| -> Vec<String> {
5393 sites
5394 .iter()
5395 .filter_map(|site| match &site.kind {
5396 SiteKind::Field { from_base, .. } => Some(format!(
5397 "{} | {}",
5398 site.text,
5399 from_base.as_deref().unwrap_or("-")
5400 )),
5401 _ => None,
5402 })
5403 .collect()
5404 };
5405 assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
5407 assert_eq!(
5410 fields(&found.rebuild_sites),
5411 ["v: a + 6 | -", "v: a + 7 | -"]
5412 );
5413 assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
5414 }
5415
5416 #[test]
5417 fn body_values_that_are_only_built() {
5418 let bodies = |sites: &[Site]| -> Vec<String> {
5419 sites
5420 .iter()
5421 .filter_map(|site| match &site.kind {
5422 SiteKind::Body { value, .. } => Some(value.clone()),
5423 _ => None,
5424 })
5425 .collect()
5426 };
5427 let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
5430 assert_eq!(bodies(&found.sites), ["Default::default()"]);
5431 assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
5432 assert_eq!(
5433 bodies(&found.rebuild_sites),
5434 [
5435 "Wrapper::from_iter([true])",
5436 "Wrapper::new(true)",
5437 "Wrapper::from(true)",
5438 "Wrapper::from_iter([false])",
5439 "Wrapper::new(false)",
5440 "Wrapper::from(false)",
5441 ]
5442 );
5443 assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
5445 let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
5448 let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
5449 assert!(bodies(&found.sites).is_empty());
5450 assert_eq!(
5451 bodies(&found.rebuild_sites),
5452 [
5453 "::core::iter::empty()",
5454 "::core::iter::once(::core::iter::empty())",
5455 "::core::iter::once(::core::iter::once(0))",
5456 "::core::iter::once(::core::iter::once(1))",
5457 ]
5458 );
5459 let function: syn::ItemFn =
5460 syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
5461 assert_eq!(
5462 iterator_values(&function.sig.output),
5463 ["::core::iter::empty()"]
5464 );
5465 }
5466}