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> {
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 match binary.op {
1750 syn::BinOp::Mul(_) => left
1751 .or(right)
1752 .filter(|k| power_of_two(*k))
1753 .map(Reach::Multiples),
1754 syn::BinOp::Shl(_) => right
1755 .filter(|bits| (1..=100).contains(bits))
1756 .map(|bits| Reach::Multiples(1 << bits)),
1757 syn::BinOp::BitAnd(_) => left.or(right).filter(|mask| *mask >= 0).map(Reach::Bits),
1758 syn::BinOp::Rem(_) => right.filter(|limit| *limit >= 1).map(Reach::Below),
1759 _ => None,
1760 }
1761}
1762
1763pub(crate) fn test_only_ranges(source: &str, file: &syn::File) -> Vec<(usize, usize)> {
1766 if is_test_only(&file.attrs) {
1767 return vec![(0, source.len())];
1768 }
1769 let mut found = vec![];
1770 for item in &file.items {
1771 test_only_items(source, item, &mut found);
1772 }
1773 found
1774}
1775
1776fn test_only_items(source: &str, item: &syn::Item, found: &mut Vec<(usize, usize)>) {
1777 let mut note = |attrs: &[syn::Attribute], span: Span| {
1778 let test_only = is_test_only(attrs);
1779 let range = span.byte_range();
1780 if test_only && source.get(range.clone()).is_some() {
1781 found.push((range.start, range.end));
1782 }
1783 test_only
1784 };
1785 if note(item_attrs(item), item.span()) {
1786 return;
1787 }
1788 match item {
1789 syn::Item::Mod(module) => {
1790 for inner in module.content.iter().flat_map(|(_, items)| items) {
1791 test_only_items(source, inner, found);
1792 }
1793 }
1794 syn::Item::Impl(block) => {
1795 for inner in &block.items {
1796 if let syn::ImplItem::Fn(function) = inner {
1797 note(&function.attrs, inner.span());
1798 }
1799 }
1800 }
1801 _ => {}
1802 }
1803}
1804
1805pub(crate) fn same_tokens(a: &str, b: &str) -> Option<bool> {
1808 fn tokens(stream: TokenStream, out: &mut Vec<String>) {
1809 let mut trees = stream.into_iter().peekable();
1810 while let Some(tree) = trees.next() {
1811 match tree {
1812 TokenTree::Punct(hash) if hash.as_char() == '#' => {
1814 let bang =
1815 matches!(trees.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '!')
1816 .then(|| trees.next());
1817 let is_doc = matches!(trees.peek(), Some(TokenTree::Group(group))
1818 if group.delimiter() == proc_macro2::Delimiter::Bracket
1819 && matches!(group.stream().into_iter().next(),
1820 Some(TokenTree::Ident(name)) if name == "doc"));
1821 if is_doc {
1822 trees.next();
1823 continue;
1824 }
1825 out.push("#".to_string());
1826 if bang.is_some() {
1827 out.push("!".to_string());
1828 }
1829 }
1830 TokenTree::Group(group) => {
1831 out.push(format!("{:?}(", group.delimiter()));
1832 tokens(group.stream(), out);
1833 out.push(")".to_string());
1834 }
1835 other => out.push(other.to_string()),
1836 }
1837 }
1838 }
1839 let lex = |text: &str| -> Option<Vec<String>> {
1840 let mut out = vec![];
1841 tokens(text.parse::<TokenStream>().ok()?, &mut out);
1842 Some(out)
1843 };
1844 Some(lex(a)? == lex(b)?)
1845}
1846
1847fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
1848 match item {
1849 syn::Item::Const(item) => &item.attrs,
1850 syn::Item::Enum(item) => &item.attrs,
1851 syn::Item::ExternCrate(item) => &item.attrs,
1852 syn::Item::Fn(item) => &item.attrs,
1853 syn::Item::ForeignMod(item) => &item.attrs,
1854 syn::Item::Impl(item) => &item.attrs,
1855 syn::Item::Macro(item) => &item.attrs,
1856 syn::Item::Mod(item) => &item.attrs,
1857 syn::Item::Static(item) => &item.attrs,
1858 syn::Item::Struct(item) => &item.attrs,
1859 syn::Item::Trait(item) => &item.attrs,
1860 syn::Item::TraitAlias(item) => &item.attrs,
1861 syn::Item::Type(item) => &item.attrs,
1862 syn::Item::Union(item) => &item.attrs,
1863 syn::Item::Use(item) => &item.attrs,
1864 _ => &[],
1865 }
1866}
1867
1868pub(crate) fn is_test_only(attrs: &[syn::Attribute]) -> bool {
1870 attrs.iter().any(|attr| {
1871 let path = attr.path();
1872 if path.segments.last().is_some_and(|s| s.ident == "test") {
1873 return true;
1874 }
1875 path.is_ident("cfg")
1876 && attr
1877 .parse_args::<syn::Meta>()
1878 .is_ok_and(|meta| !cfg_possible_without_test(&meta, true))
1879 })
1880}
1881
1882impl<'ast> Visit<'ast> for Finder<'_> {
1883 fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
1884 fn visit_local(&mut self, node: &'ast syn::Local) {
1885 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1886 visit::visit_local(self, node);
1887 }
1888 }
1889 fn visit_pat(&mut self, node: &'ast syn::Pat) {
1890 if let syn::Pat::Type(binding) = node {
1891 self.visit_type(&binding.ty);
1892 }
1893 }
1894 fn visit_type_macro(&mut self, _: &'ast syn::TypeMacro) {}
1895 fn visit_type_array(&mut self, node: &'ast syn::TypeArray) {
1896 self.visit_type(&node.elem);
1897 self.constant(&[], &node.len);
1898 }
1899 fn visit_const_param(&mut self, node: &'ast syn::ConstParam) {
1900 self.visit_type(&node.ty);
1901 if let Some(default) = &node.default {
1902 self.constant(&node.attrs, default);
1903 }
1904 }
1905 fn visit_generic_argument(&mut self, node: &'ast syn::GenericArgument) {
1906 match node {
1907 syn::GenericArgument::Const(value) => self.constant(&[], value),
1908 _ => visit::visit_generic_argument(self, node),
1909 }
1910 }
1911 fn visit_variant(&mut self, node: &'ast syn::Variant) {
1912 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1913 self.visit_fields(&node.fields);
1914 if let Some((_, value)) = &node.discriminant {
1915 self.constant(&[], value);
1916 }
1917 }
1918 }
1919 fn visit_file(&mut self, node: &'ast syn::File) {
1920 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1921 visit::visit_file(self, node);
1922 }
1923 }
1924 fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
1925 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1926 visit::visit_item_enum(self, node);
1927 }
1928 }
1929 fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
1930 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1931 visit::visit_item_struct(self, node);
1932 }
1933 }
1934 fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
1935 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1936 visit::visit_item_union(self, node);
1937 }
1938 }
1939 fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
1940 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1941 visit::visit_item_trait(self, node);
1942 }
1943 }
1944 fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
1945 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1946 visit::visit_item_type(self, node);
1947 }
1948 }
1949 fn visit_field(&mut self, node: &'ast syn::Field) {
1950 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1951 visit::visit_field(self, node);
1952 }
1953 }
1954 fn visit_impl_item_type(&mut self, node: &'ast syn::ImplItemType) {
1955 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1956 visit::visit_impl_item_type(self, node);
1957 }
1958 }
1959 fn visit_trait_item_type(&mut self, node: &'ast syn::TraitItemType) {
1960 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1961 visit::visit_trait_item_type(self, node);
1962 }
1963 }
1964 fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
1965 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1966 }
1967 fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
1968 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1969 }
1970 fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
1971 self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1972 }
1973 fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
1974 self.typed_constant(
1975 &node.attrs,
1976 &node.ty,
1977 node.default.as_ref().map(|(_, value)| value),
1978 );
1979 }
1980 fn visit_expr_const(&mut self, node: &'ast syn::ExprConst) {
1981 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1982 self.const_depth += 1;
1983 self.visit_block(&node.block);
1984 self.const_depth -= 1;
1985 }
1986 }
1987
1988 fn visit_macro(&mut self, node: &'ast syn::Macro) {
1989 let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
1990 return;
1991 };
1992 if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
1993 return;
1994 }
1995 if name == "matches" {
1996 let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
1998 let expr: syn::Expr = input.parse()?;
1999 input.parse::<proc_macro2::TokenStream>()?;
2000 Ok(expr)
2001 });
2002 if let Ok(expr) = scrutinee {
2003 self.visit_expr(&expr);
2004 }
2005 return;
2006 }
2007 type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
2008 if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
2011 for arg in &args {
2012 self.visit_expr(arg);
2015 }
2016 }
2017 }
2018
2019 fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
2020 self.visit_expr(&node.expr);
2021 self.constant(&node.attrs, &node.len);
2022 }
2023
2024 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
2025 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2027 if node.content.is_none() {
2028 let path = node.attrs.iter().find_map(|attr| match &attr.meta {
2029 syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
2030 syn::Expr::Lit(syn::ExprLit {
2031 lit: syn::Lit::Str(s),
2032 ..
2033 }) => Some(s.value()),
2034 _ => None,
2035 },
2036 _ => None,
2037 });
2038 self.found.test_modules.push(TestModule {
2039 name: node.ident.to_string(),
2040 path,
2041 });
2042 }
2043 return;
2044 }
2045 visit::visit_item_mod(self, node);
2046 }
2047
2048 fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
2049 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2050 let constant = node.sig.constness.is_some() as usize;
2052 self.const_depth += constant;
2053 self.function_sites(&node.sig, &node.block);
2054 visit::visit_item_fn(self, node);
2055 self.const_depth -= constant;
2056 }
2057 }
2058
2059 fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
2060 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2061 let constant = node.sig.constness.is_some() as usize;
2063 self.const_depth += constant;
2064 self.function_sites(&node.sig, &node.block);
2065 visit::visit_impl_item_fn(self, node);
2066 self.const_depth -= constant;
2067 }
2068 }
2069
2070 fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
2071 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2072 let constant = node.sig.constness.is_some() as usize;
2073 self.const_depth += constant;
2074 if let Some(body) = &node.default {
2075 self.function_sites(&node.sig, body);
2076 }
2077 visit::visit_trait_item_fn(self, node);
2078 self.const_depth -= constant;
2079 }
2080 }
2081
2082 fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
2083 if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
2084 visit::visit_item_impl(self, node);
2085 }
2086 }
2087
2088 fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
2089 if node.constness.is_none() {
2090 visit::visit_expr_closure(self, node);
2091 }
2092 }
2093
2094 fn visit_block(&mut self, node: &'ast syn::Block) {
2095 for stmt in &node.stmts {
2096 if let syn::Stmt::Expr(expr, Some(semi)) = stmt
2097 && deletable(expr)
2098 && let (Some((start, _)), Some((_, end))) =
2099 (self.range(expr.span()), self.range(semi.span()))
2100 && in_order(start, end)
2101 {
2102 self.push(SiteKind::Stmt, start, end, expr.span());
2103 }
2104 }
2105 visit::visit_block(self, node);
2106 }
2107
2108 fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
2109 let name = node.method.to_string();
2110 if (name == "max" || name == "min")
2111 && node.args.len() == 1
2112 && node.turbofish.is_none()
2113 && node.attrs.is_empty()
2114 && let (
2115 Some((start, receiver_end)),
2116 Some((argument_start, argument_end)),
2117 Some((_, end)),
2118 ) = (
2119 self.range(node.receiver.span()),
2120 self.range(node.args[0].span()),
2121 self.range(node.paren_token.span.close()),
2122 )
2123 && in_order(receiver_end, argument_start)
2124 && in_order(argument_end, end)
2125 {
2126 let kind = SiteKind::MinMax {
2127 max: name == "max",
2128 receiver: self.source[start..receiver_end].to_string(),
2129 argument: self.source[argument_start..argument_end].to_string(),
2130 call: (receiver_end, argument_start),
2131 close: (argument_end, end),
2132 };
2133 self.push(kind, start, end, node.receiver.span());
2134 }
2135 visit::visit_expr_method_call(self, node);
2136 }
2137
2138 fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
2139 let mut over = &*node.expr;
2140 while let syn::Expr::Paren(syn::ExprParen { expr, .. })
2141 | syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
2142 {
2143 over = expr;
2144 }
2145 if let syn::Expr::Range(syn::ExprRange {
2146 start: Some(from), ..
2147 }) = over
2148 && let Some((start, _)) = self.range(from.span())
2149 {
2150 self.for_ranges.insert(start);
2151 }
2152 visit::visit_expr_for_loop(self, node);
2153 }
2154
2155 fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
2156 if let (Some(from), Some(to)) = (&node.start, &node.end)
2159 && node.attrs.is_empty()
2160 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2161 (self.range(from.span()), self.range(to.span()))
2162 && in_order(lhs_end, rhs_start)
2163 {
2164 let kind = SiteKind::Range {
2165 inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
2166 lhs: self.source[start..lhs_end].to_string(),
2167 rhs: self.source[rhs_start..end].to_string(),
2168 gap: (lhs_end, rhs_start),
2169 };
2170 let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
2177 self.const_depth += built as usize;
2178 self.push(kind, start, end, from.span());
2179 self.const_depth -= built as usize;
2180 }
2181 visit::visit_expr_range(self, node);
2182 }
2183
2184 fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
2185 let catches_all = |arm: &syn::Arm| {
2188 arm.guard.is_none()
2189 && match &arm.pat {
2190 syn::Pat::Wild(_) => true,
2191 syn::Pat::Ident(p) => {
2192 p.subpat.is_none()
2193 && p.ident
2194 .to_string()
2195 .starts_with(|c: char| c.is_lowercase() || c == '_')
2196 }
2197 _ => false,
2198 }
2199 };
2200 let mut removable = vec![];
2201 let has_wildcard = node
2202 .arms
2203 .iter()
2204 .any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
2205 let final_catches_all = node.arms.last().is_some_and(catches_all);
2206 for arm in &node.arms {
2207 if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
2208 continue;
2209 }
2210 let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
2212 let literal =
2213 has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
2214 if !probe && !literal {
2215 continue;
2216 }
2217 let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
2218 self.range(arm.pat.span()),
2219 self.range(arm.span()),
2220 self.range(arm.fat_arrow_token.span()),
2221 ) else {
2222 continue;
2223 };
2224 let guard = match &arm.guard {
2225 None => ArmGuard::None(arrow),
2226 Some((_, expr)) => match self.range(expr.span()) {
2227 Some((from, to)) => ArmGuard::Existing(from, to),
2228 None => continue,
2229 },
2230 };
2231 let pattern = match guard {
2232 ArmGuard::Existing(from, to) => format!(
2233 "{} if {}",
2234 &self.source[start..pat_end],
2235 &self.source[from..to]
2236 ),
2237 ArmGuard::None(_) => self.source[start..pat_end].to_string(),
2238 };
2239 let end = arm
2240 .comma
2241 .as_ref()
2242 .and_then(|comma| self.range(comma.span()))
2243 .map_or(remove_end, |(_, end)| end);
2244 let at = arm.pat.span().start();
2245 removable.push(start);
2246 let site = Site {
2247 id: 0,
2248 kind: SiteKind::Arm {
2249 pattern: pattern.clone(),
2250 guard,
2251 removal: (remove_start, end),
2252 },
2253 line: at.line,
2254 column: at.column + 1,
2255 start,
2256 end,
2257 text: format!("{pattern} => .."),
2258 };
2259 if probe {
2260 self.add(site);
2261 } else {
2262 self.add_rebuild(site);
2263 }
2264 }
2265 for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
2268 if let Some((_, guard)) = &arm.guard
2269 && !matches!(**guard, syn::Expr::Let(_))
2270 && !in_let_chain(guard)
2271 && let (Some((start, end)), Some((pattern, _))) =
2272 (self.range(guard.span()), self.range(arm.pat.span()))
2273 {
2274 let kind = SiteKind::Guard {
2275 can_be_false: !removable.contains(&pattern),
2276 };
2277 self.push(kind, start, end, guard.span());
2278 }
2279 }
2280 visit::visit_expr_match(self, node);
2281 }
2282
2283 fn visit_arm(&mut self, arm: &'ast syn::Arm) {
2284 if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
2285 visit::visit_arm(self, arm);
2286 }
2287 }
2288
2289 fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
2290 if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
2291 visit::visit_field_value(self, field);
2292 }
2293 }
2294
2295 fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2296 if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2297 return;
2298 }
2299 let from_base = node.rest.as_deref().and_then(|base| {
2301 if !node.attrs.is_empty() || node.qself.is_some() {
2302 return None;
2303 }
2304 let (from, to) = self.range(base.span())?;
2305 let written = &self.source[from..to];
2306 match base {
2307 base if is_plain_place(base) => Some(format!("({written})")),
2308 syn::Expr::Call(call)
2309 if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
2310 {
2311 let (from, to) = self.range(node.path.span())?;
2312 Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
2313 }
2314 _ => None,
2315 }
2316 });
2317 if node.rest.is_some() {
2318 for pair in node.fields.pairs() {
2319 let field = pair.value();
2320 if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
2321 continue;
2322 }
2323 let name = match &field.member {
2324 syn::Member::Named(name) => name.to_string(),
2325 syn::Member::Unnamed(index) => index.index.to_string(),
2326 };
2327 let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
2328 self.range(field.member.span()),
2329 self.range(field.expr.span()),
2330 self.range(field.span()),
2331 ) else {
2332 continue;
2333 };
2334 let remove_end = pair
2335 .punct()
2336 .and_then(|comma| self.range(comma.span()))
2337 .map_or(end, |(_, end)| end);
2338 let from_base = from_base
2339 .as_ref()
2340 .filter(|_| field.attrs.is_empty())
2341 .map(|base| format!("{base}.{name}"));
2342 let probe = from_base.is_some();
2343 let kind = SiteKind::Field {
2344 from_base,
2345 name,
2346 shorthand: field.colon_token.is_none(),
2347 removal: (remove_start, remove_end),
2348 };
2349 let at = field.member.span().start();
2350 let site = Site {
2351 id: 0,
2352 kind,
2353 line: at.line,
2354 column: at.column + 1,
2355 start: if probe { value } else { remove_start },
2356 end,
2357 text: self.source[start..end].to_string(),
2358 };
2359 if probe {
2360 self.add(site);
2361 } else {
2362 self.add_rebuild(site);
2363 }
2364 }
2365 }
2366 visit::visit_expr_struct(self, node);
2367 }
2368
2369 fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
2370 if let syn::UnOp::Not(bang) = &node.op
2371 && node.attrs.is_empty()
2372 && let (Some((start, _)), Some((operand_start, end))) =
2373 (self.range(bang.span()), self.range(node.expr.span()))
2374 && in_order(start, operand_start)
2375 {
2376 let kind = SiteKind::Not {
2377 bang: (start, operand_start),
2378 operand: self.source[operand_start..end].to_string(),
2379 };
2380 self.push(kind, start, end, bang.span());
2381 }
2382 if let syn::UnOp::Neg(minus) = &node.op
2383 && node.attrs.is_empty()
2384 && let (Some((start, _)), Some((operand_start, end))) =
2385 (self.range(minus.span()), self.range(node.expr.span()))
2386 && in_order(start, operand_start)
2387 {
2388 let zero = match &*node.expr {
2389 syn::Expr::Lit(syn::ExprLit {
2390 lit: syn::Lit::Int(lit),
2391 ..
2392 }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
2393 _ => false,
2395 };
2396 if !zero {
2397 let kind = SiteKind::Neg {
2398 minus: (start, operand_start),
2399 operand: self.source[operand_start..end].to_string(),
2400 literal: matches!(*node.expr, syn::Expr::Lit(_)),
2401 };
2402 self.push(kind, start, end, minus.span());
2403 }
2404 }
2405 visit::visit_expr_unary(self, node);
2406 }
2407
2408 fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
2409 if let Some(op) = cmp_op(&node.op)
2410 && node.attrs.is_empty()
2411 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2412 (self.range(node.left.span()), self.range(node.right.span()))
2413 && in_order(lhs_end, rhs_start)
2414 {
2415 let literal = match (int_literal(&node.left), int_literal(&node.right)) {
2416 (None, Some(k)) => LiteralSide::Rhs(k),
2417 (Some(k), None) => LiteralSide::Lhs(k),
2418 _ => LiteralSide::None,
2419 };
2420 let kind = SiteKind::Cmp {
2421 op,
2422 lhs: self.source[start..lhs_end].to_string(),
2423 rhs: self.source[rhs_start..end].to_string(),
2424 literal,
2425 gap: (lhs_end, rhs_start),
2426 };
2427 self.push(kind, start, end, node.left.span());
2428 } else if node.attrs.is_empty()
2429 && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2430 (self.range(node.left.span()), self.range(node.right.span()))
2431 && in_order(lhs_end, rhs_start)
2432 {
2433 let lhs = self.source[start..lhs_end].to_string();
2434 let rhs = self.source[rhs_start..end].to_string();
2435 let gap = (lhs_end, rhs_start);
2436 let logic = match &node.op {
2437 syn::BinOp::And(_) => Some(true),
2438 syn::BinOp::Or(_) => Some(false),
2439 _ => None,
2440 };
2441 if let Some(and) = logic {
2442 if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
2443 self.push(
2444 SiteKind::Logic { and, lhs, rhs, gap },
2445 start,
2446 end,
2447 node.left.span(),
2448 );
2449 }
2450 } else if let Some((op, assign)) = arith_op(&node.op) {
2451 let kind = SiteKind::Arith {
2452 op,
2453 assign,
2454 lhs,
2455 rhs,
2456 gap,
2457 };
2458 let literals = is_literal(&node.left) && is_literal(&node.right);
2461 if !literals && (!assign || is_plain_place(&node.left)) {
2462 self.push(kind, start, end, node.left.span());
2463 } else {
2464 let at = node.left.span().start();
2467 self.found.rebuild_sites.push(Site {
2468 id: NO_ID,
2469 kind,
2470 line: at.line,
2471 column: at.column + 1,
2472 start,
2473 end,
2474 text: self.source[start..end].to_string(),
2475 });
2476 }
2477 }
2478 }
2479 visit::visit_expr_binary(self, node);
2480 }
2481}
2482
2483#[derive(Debug, PartialEq)]
2486pub struct Rendered {
2487 pub text: String,
2488 segments: Vec<(usize, usize, usize)>,
2491 inserted: Vec<(usize, usize, u32)>,
2493}
2494
2495impl Rendered {
2496 pub fn copied(&self, from: usize, to: usize) -> Option<(usize, usize)> {
2499 self.segments
2500 .iter()
2501 .find(|(_, start, len)| *start <= from && to <= start + len)
2502 .map(|(out, start, _)| (out + from - start, out + to - start))
2503 }
2504
2505 pub fn inserted_by(&self, offset: usize) -> Option<u32> {
2509 let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
2510 let (out, len, site) = self.inserted[idx.checked_sub(1)?];
2511 (offset - out < len).then_some(site)
2512 }
2513
2514 pub fn to_original(&self, offset: usize) -> usize {
2515 let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
2516 let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
2517 return 0;
2518 };
2519 orig + (offset - out).min(len)
2521 }
2522}
2523
2524struct Edit {
2525 pos: usize,
2526 end: usize,
2527 phase: u8,
2529 order: i64,
2531 text: String,
2532 site: u32,
2534}
2535
2536pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
2538 let rt = format!("crate::{RUNTIME_MOD}");
2539 let mut edits = vec![];
2540 for site in sites.iter().filter(|s| enabled(s.id)) {
2541 let wraps = matches!(
2545 site.kind,
2546 SiteKind::Return { .. }
2547 | SiteKind::Body { .. }
2548 | SiteKind::Guard { .. }
2549 | SiteKind::Field { .. }
2550 );
2551 let len = 2 * (site.end - site.start) as i64 + wraps as i64;
2553 let (open, close) = match &site.kind {
2554 SiteKind::Cmp { op, gap, .. } => {
2555 let func = if op.is_ordering() { "ord" } else { "eq" };
2556 edits.push(Edit {
2557 pos: gap.0,
2558 end: gap.1,
2559 phase: 1,
2560 order: 0,
2561 text: "), &(".into(),
2562 site: site.id,
2563 });
2564 (
2565 "(match (&(".to_string(),
2566 format!(
2567 ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
2568 {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
2569 id = site.id,
2570 code = op.code(),
2571 ),
2572 )
2573 }
2574 SiteKind::Logic { and, gap, .. } => {
2579 let id = site.id;
2582 edits.push(Edit {
2583 pos: gap.0,
2584 end: gap.1,
2585 phase: 1,
2586 order: 0,
2587 text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
2588 site: site.id,
2589 });
2590 (
2591 format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
2594 "), __tmt_c => __tmt_c == 1u8 })".to_string(),
2595 )
2596 }
2597 SiteKind::Arith {
2598 op, assign, gap, ..
2599 } => {
2600 let (holder, lhs_open, lhs_close) = if *assign {
2602 ("Aa", "&mut (", ")")
2603 } else {
2604 ("Ar", "", "")
2605 };
2606 edits.push(Edit {
2607 pos: gap.0,
2608 end: gap.1,
2609 phase: 1,
2610 order: 0,
2611 text: format!("{lhs_close}, "),
2612 site: site.id,
2613 });
2614 (
2615 format!("(match ({lhs_open}"),
2616 format!(
2617 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
2618 (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
2619 any = op.fallback_trait(*assign),
2620 prim = op.prim_trait(*assign),
2621 method = op.method(*assign),
2622 id = site.id,
2623 ),
2624 )
2625 }
2626 SiteKind::Not { bang, .. } => {
2627 edits.push(Edit {
2629 pos: bang.0,
2630 end: bang.1,
2631 phase: 1,
2632 order: 0,
2633 text: String::new(),
2634 site: site.id,
2635 });
2636 (
2637 "(match (".to_string(),
2638 format!(
2639 ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
2640 (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
2641 site.id
2642 ),
2643 )
2644 }
2645 SiteKind::Return { option, .. } => match option {
2646 None => (
2647 " let __tmt_v: bool = {".to_string(),
2648 format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
2649 ),
2650 Some(ty) => (
2651 format!(" let __tmt_v: {ty} = {{"),
2652 format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
2653 ),
2654 },
2655 SiteKind::MinMax {
2656 max, call, close, ..
2657 } => {
2658 edits.push(Edit {
2662 pos: call.0,
2663 end: call.1,
2664 phase: 1,
2665 order: 0,
2666 text: "), ".into(),
2667 site: site.id,
2668 });
2669 let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
2673 edits.push(Edit {
2674 pos: close.0,
2675 end: close.1,
2676 phase: 1,
2677 order: 0,
2678 text: format!(
2679 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
2680 if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
2681 site.id
2682 ),
2683 site: site.id,
2684 });
2685 ("(match (&(".to_string(), String::new())
2686 }
2687 SiteKind::Range { inclusive, gap, .. } => {
2688 edits.push(Edit {
2689 pos: gap.0,
2690 end: gap.1,
2691 phase: 1,
2692 order: 0,
2693 text: ", ".into(),
2694 site: site.id,
2695 });
2696 let method = if *inclusive {
2697 "tmt_range_inclusive"
2698 } else {
2699 "tmt_range"
2700 };
2701 (
2702 "(match (".to_string(),
2703 format!(
2704 ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
2705 (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
2706 site.id
2707 ),
2708 )
2709 }
2710 SiteKind::Arm { guard, .. } => {
2711 match guard {
2714 ArmGuard::None(arrow) => edits.push(Edit {
2715 pos: *arrow,
2716 end: *arrow,
2717 phase: 2,
2718 order: 0,
2719 text: format!("if {rt}::arm({}u32) ", site.id),
2720 site: site.id,
2721 }),
2722 ArmGuard::Existing(from, to) => {
2723 let wider = 2 * (to - from + 1) as i64;
2724 edits.push(Edit {
2725 pos: *from,
2726 end: *from,
2727 phase: 2,
2728 order: -wider,
2729 text: format!("{rt}::arm({}u32) && (", site.id),
2730 site: site.id,
2731 });
2732 edits.push(Edit {
2733 pos: *to,
2734 end: *to,
2735 phase: 0,
2736 order: wider,
2737 text: ")".into(),
2738 site: site.id,
2739 });
2740 }
2741 }
2742 (String::new(), String::new())
2743 }
2744 SiteKind::Stmt => (
2745 format!("if {rt}::live({}u32) {{ ", site.id),
2746 " }".to_string(),
2747 ),
2748 SiteKind::Neg {
2750 operand,
2751 literal: true,
2752 ..
2753 } => (
2754 format!("(if {rt}::live({}u32) {{ ", site.id),
2755 format!(" }} else {{ {operand} }})"),
2756 ),
2757 SiteKind::Neg { minus, .. } => {
2758 edits.push(Edit {
2759 pos: minus.0,
2760 end: minus.1,
2761 phase: 1,
2762 order: 0,
2763 text: String::new(),
2764 site: site.id,
2765 });
2766 (
2767 "(match (".to_string(),
2768 format!(
2769 ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
2770 site.id
2771 ),
2772 )
2773 }
2774 SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
2775 SiteKind::Field {
2776 name,
2777 shorthand,
2778 from_base: Some(from_base),
2779 ..
2780 } => (
2781 format!(
2782 "{}if {rt}::live({}u32) {{ ",
2783 if *shorthand {
2784 format!("{name}: ")
2785 } else {
2786 String::new()
2787 },
2788 site.id
2789 ),
2790 format!(" }} else {{ {from_base} }}"),
2791 ),
2792 SiteKind::Field {
2793 from_base: None, ..
2794 } => continue,
2795 SiteKind::Body { value, .. } => (
2796 format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
2797 String::new(),
2798 ),
2799 };
2800 edits.push(Edit {
2801 pos: site.start,
2802 end: site.start,
2803 phase: 2,
2804 order: -len,
2805 text: open,
2806 site: site.id,
2807 });
2808 edits.push(Edit {
2809 pos: site.end,
2810 end: site.end,
2811 phase: 0,
2812 order: len,
2813 text: close,
2814 site: site.id,
2815 });
2816 }
2817 edits.sort_by_key(|e| (e.pos, e.phase, e.order));
2818
2819 let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
2821 let mut text = String::with_capacity(capacity);
2822 let mut segments = vec![];
2823 let mut inserted = vec![];
2824 let mut cursor = 0;
2825 for edit in edits {
2826 if edit.pos >= cursor {
2829 segments.push((text.len(), cursor, edit.pos - cursor));
2830 text.push_str(&source[cursor..edit.pos]);
2831 }
2832 inserted.push((text.len(), edit.text.len(), edit.site));
2833 text.push_str(&edit.text);
2834 cursor = cursor.max(edit.end);
2835 }
2836 segments.push((text.len(), cursor, source.len() - cursor));
2837 text.push_str(&source[cursor..]);
2838 Rendered {
2839 text,
2840 segments,
2841 inserted,
2842 }
2843}
2844
2845pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
2848 let containing = || {
2851 sites.iter().filter(|s| {
2852 enabled(s.id)
2853 && s.start <= offset
2854 && offset <= s.end
2855 && !matches!(s.kind, SiteKind::Body { .. })
2856 })
2857 };
2858 let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
2859 return vec![];
2860 };
2861 containing()
2862 .filter(|s| s.end - s.start == smallest)
2863 .map(|s| s.id)
2864 .collect()
2865}
2866
2867#[cfg(test)]
2868mod tests {
2869 use super::*;
2870
2871 #[test]
2872 fn what_an_expression_can_be_is_read_from_its_last_operation() {
2873 use crate::plan::Reach;
2874 for (expr, expected) in [
2875 ("blocks * 8", Some(Reach::Multiples(8))),
2876 ("8 * blocks", Some(Reach::Multiples(8))),
2877 ("(blocks * (2))", Some(Reach::Multiples(2))),
2878 ("blocks << 3", Some(Reach::Multiples(8))),
2879 ("flags & 0xF0", Some(Reach::Bits(0xF0))),
2880 ("0b1010u8 & flags", Some(Reach::Bits(0b1010))),
2881 ("n % 10", Some(Reach::Below(10))),
2882 ("(a + b) % 7_u32", Some(Reach::Below(7))),
2883 ("cents * 10", None),
2885 ("blocks * 1", None),
2886 ("blocks * 0", None),
2887 ("a * b", None),
2888 ("3 << blocks", None),
2889 ("blocks << 0", None),
2890 ("blocks << 200", None),
2891 ("10 % n", None),
2892 ("n % 0", None),
2893 ("blocks * 8 + 1", None),
2894 ("(blocks * 8) as u8", None),
2895 ("-(blocks * 8)", None),
2896 ("blocks", None),
2897 ("flags | 0xF0", None),
2898 ("blocks / 8", None),
2899 ("x * 8.0", None),
2900 ("not rust (", None),
2901 ] {
2902 assert_eq!(reach(expr), expected, "{expr}");
2903 }
2904 }
2905
2906 #[test]
2907 fn code_of_the_tests_is_told_from_the_rest() {
2908 let source = r#"
2909 pub fn open(n: u32) -> bool { n > 1 }
2910 #[test]
2911 fn at_the_top() { assert!(open(2)); }
2912 #[cfg(test)]
2913 mod tests { fn helper() -> u32 { 3 } }
2914 mod plain {
2915 pub fn inside(n: u32) -> bool { n > 4 }
2916 #[cfg(test)]
2917 fn only_tested() -> u32 { 5 }
2918 }
2919 struct S;
2920 impl S {
2921 fn method(&self) -> u32 { 6 }
2922 #[cfg(test)]
2923 fn test_method(&self) -> u32 { 7 }
2924 }
2925 #[cfg(not(test))]
2926 fn never_in_tests() -> u32 { 8 }
2927 "#;
2928 let file = parse_source(source).unwrap();
2929 let ranges = test_only_ranges(source, &file);
2930 let of_tests = |text: &str| {
2931 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
2932 ranges.iter().any(|(from, to)| *from <= at && at < *to)
2933 };
2934 for text in ["open(2)", "{ 3 }", "{ 5 }", "{ 7 }", "fn at_the_top"] {
2935 assert!(of_tests(text), "{text}");
2936 }
2937 for text in ["n > 1", "n > 4", "{ 6 }", "{ 8 }", "struct S", "mod plain"] {
2938 assert!(!of_tests(text), "{text}");
2939 }
2940 let whole = "#![cfg(test)]\nfn f() {}\n";
2941 let file = parse_source(whole).unwrap();
2942 assert_eq!(test_only_ranges(whole, &file), [(0, whole.len())]);
2943 }
2944
2945 #[test]
2946 fn comments_documentation_and_spacing_are_not_program_text() {
2947 let code = "/// Says.\n#[inline]\nfn f(a: u8) -> u8 {\n a + 1 // one more\n}\n";
2948 for same in [
2949 "#[inline] fn f(a:u8)->u8{a+1}",
2950 "/// Says something else.\n#[inline]\nfn f(a: u8) -> u8 { /* why */ a + 1 }",
2951 "#[doc = \"other\"] #[inline] fn f(a: u8) -> u8 { a + 1 }",
2952 ] {
2953 assert_eq!(same_tokens(code, same), Some(true), "{same}");
2954 }
2955 for other in [
2956 "#[inline] fn f(a: u8) -> u8 { a + 2 }",
2957 "fn f(a: u8) -> u8 { a + 1 }",
2958 "#[inline] fn f(a: u8) -> u8 { (a + 1) }",
2959 "#[inline] fn f(a: u8) -> u8 { a + 1 } fn g() {}",
2960 "#![inline] fn f(a: u8) -> u8 { a + 1 }",
2961 "#[inline] fn f(a: u8) -> u8 { [a + 1][0] }",
2962 ] {
2963 assert_eq!(same_tokens(code, other), Some(false), "{other}");
2964 }
2965 assert_eq!(
2966 same_tokens("#![doc = \"a\"] fn f() {}", "fn f() {}"),
2967 Some(true)
2968 );
2969 assert_eq!(same_tokens(code, "fn f( {"), None);
2970 assert_eq!(same_tokens("fn f( {", code), None);
2971 }
2972
2973 #[test]
2974 fn a_cfg_is_decided_only_as_far_as_the_features_decide_it() {
2975 let on: BTreeSet<String> = ["basic".to_string()].into();
2976 for (predicate, expected) in [
2977 (r#"feature = "basic""#, Some(true)),
2978 (r#"feature = "extra""#, Some(false)),
2979 (r#"not(feature = "extra")"#, Some(true)),
2980 (r#"not(feature = "basic")"#, Some(false)),
2981 ("test", None),
2982 (r#"target_os = "linux""#, None),
2983 ("not(test)", None),
2984 ("all()", Some(true)),
2985 ("any()", Some(false)),
2986 (r#"all(feature = "basic", feature = "extra")"#, Some(false)),
2987 (r#"all(test, feature = "extra")"#, Some(false)),
2988 (r#"all(feature = "extra", test)"#, Some(false)),
2989 (r#"all(test, feature = "basic")"#, None),
2990 (
2991 r#"all(feature = "basic", not(feature = "extra"))"#,
2992 Some(true),
2993 ),
2994 (r#"any(feature = "basic", feature = "extra")"#, Some(true)),
2995 (r#"any(test, feature = "basic")"#, Some(true)),
2996 (r#"any(feature = "basic", test)"#, Some(true)),
2997 (r#"any(test, feature = "extra")"#, None),
2998 (r#"any(feature = "extra", feature = "more")"#, Some(false)),
2999 (r#"not(any(test, feature = "basic"))"#, Some(false)),
3000 (r#"not(test, feature = "basic")"#, None),
3001 ("feature = 3", None),
3002 (r#"unknown(feature = "extra")"#, None),
3003 ("all(=)", None),
3004 ] {
3005 let meta: syn::Meta = syn::parse_str(predicate).unwrap();
3006 assert_eq!(cfg_value(&meta, &on), expected, "{predicate}");
3007 }
3008 }
3009
3010 #[test]
3011 fn code_under_a_feature_that_is_off_is_not_in_the_build() {
3012 let source = r#"
3013 #[cfg(feature = "extra")]
3014 pub fn item(n: u32) -> bool { n > 1 }
3015 #[cfg(feature = "basic")]
3016 pub fn kept(n: u32) -> bool { n > 2 }
3017 #[cfg(test)]
3018 fn only_tests(n: u32) -> bool { n > 3 }
3019 #[cfg(feature = "extra")]
3020 mod module { pub fn inside(n: u32) -> bool { n > 4 } }
3021 struct S;
3022 impl S {
3023 #[cfg(feature = "extra")]
3024 fn method(&self, n: u32) -> bool { n > 5 }
3025 fn open(&self, n: u32) -> bool { n > 6 }
3026 }
3027 trait T {
3028 #[cfg(feature = "extra")]
3029 fn provided(&self, n: u32) -> bool { n > 7 }
3030 }
3031 #[cfg(feature = "extra")]
3032 impl T for S {}
3033 fn body(n: u32) -> u32 {
3034 #[cfg(feature = "extra")]
3035 let n = n + 8;
3036 #[cfg(feature = "extra")]
3037 { return n + 9; }
3038 #[cfg(feature = "extra")]
3039 if n > 10 { return 0; }
3040 #[cfg(feature = "extra")]
3041 assert!(n > 11);
3042 match n {
3043 #[cfg(feature = "extra")]
3044 12 => 0,
3045 _ => n + 13,
3046 }
3047 }
3048 #[cfg(not(feature = "extra"))]
3049 mod kept_module {
3050 #[cfg(feature = "extra")]
3051 const OFF: u32 = 14 + 1;
3052 const ON: u32 = 15 + 1;
3053 }
3054 "#;
3055 let file = parse_source(source).unwrap();
3056 let on: BTreeSet<String> = ["basic".to_string()].into();
3057 let ranges = inactive_ranges(source, &file, &on);
3058 let left_out = |text: &str| {
3059 let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
3060 ranges.iter().any(|(from, to)| *from <= at && at < *to)
3061 };
3062 for off in [
3063 "n > 1 ", "n > 4", "n > 5", "n > 7", "n + 8", "n + 9", "n > 10", "n > 11", "12 =>",
3064 "14 + 1",
3065 ] {
3066 assert!(left_out(off), "{off}");
3067 }
3068 for on in ["n > 2", "n > 3", "n > 6", "n + 13", "15 + 1", "struct S"] {
3069 assert!(!left_out(on), "{on}");
3070 }
3071 let both: BTreeSet<String> = ["basic".to_string(), "extra".to_string()].into();
3074 let with_extra = inactive_ranges(source, &file, &both);
3075 assert_eq!(with_extra.len(), 1, "{with_extra:?}");
3076 assert!(source[with_extra[0].0..with_extra[0].1].starts_with("#[cfg(not(feature"));
3077 let whole = "#![cfg(feature = \"extra\")]\nfn f() {}\n";
3078 let file = parse_source(whole).unwrap();
3079 assert_eq!(inactive_ranges(whole, &file, &on), [(0, whole.len())]);
3080 }
3081
3082 fn all(_: u32) -> bool {
3083 true
3084 }
3085
3086 fn found(src: &str, first_id: u32) -> Result<Discovery> {
3089 let mut all = discover(src, 0)?;
3090 all.sites
3091 .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
3092 for (index, site) in all.sites.iter_mut().enumerate() {
3093 site.id = first_id + index as u32;
3094 }
3095 Ok(all)
3096 }
3097
3098 #[test]
3099 fn finds_a_comparison_with_a_literal() {
3100 let src = "pub fn is_eligible(age: u32) -> bool {\n age >= 18\n}\n";
3101 let found = found(src, 5).unwrap();
3102 assert_eq!(found.sites.len(), 1);
3103 let site = &found.sites[0];
3104 assert_eq!(
3105 (site.id, site.line, site.column, site.text.as_str()),
3106 (5, 2, 5, "age >= 18")
3107 );
3108 let SiteKind::Cmp {
3109 op,
3110 lhs,
3111 rhs,
3112 literal,
3113 ..
3114 } = &site.kind
3115 else {
3116 panic!()
3117 };
3118 assert_eq!(
3119 (*op, lhs.as_str(), rhs.as_str(), *literal),
3120 (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
3121 );
3122 }
3123
3124 #[test]
3125 fn literal_sides() {
3126 let src =
3127 "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
3128 let literals: Vec<LiteralSide> = found(src, 0)
3129 .unwrap()
3130 .sites
3131 .iter()
3132 .filter_map(|s| match &s.kind {
3133 SiteKind::Cmp { literal, .. } => Some(*literal),
3134 SiteKind::Neg { .. } => None,
3135 _ => panic!(),
3136 })
3137 .collect();
3138 assert_eq!(
3139 literals,
3140 [
3141 LiteralSide::Lhs(-5),
3142 LiteralSide::Rhs(3),
3143 LiteralSide::None,
3144 LiteralSide::None,
3145 LiteralSide::None
3146 ]
3147 );
3148 }
3149
3150 #[test]
3151 fn renders_a_comparison_probe() {
3152 let src = "fn f(a: u8) -> bool { a >= 18 }";
3153 let sites = found(src, 3).unwrap().sites;
3154 let out = render(src, &sites, &all);
3155 assert_eq!(
3156 out.text,
3157 "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
3158 use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
3159 (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
3160 );
3161 assert_eq!(render(src, &sites, &|_| false).text, src);
3162 }
3163
3164 #[test]
3165 fn renders_statement_guards_and_nested_sites() {
3166 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}";
3167 let sites = found(src, 0).unwrap().sites;
3168 let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3169 assert_eq!(
3170 kinds,
3171 [
3172 "check((a < 3) == true)?;",
3173 "v.push(a);",
3174 "v.clear();",
3175 "(a < 3) == true",
3176 "a < 3"
3177 ]
3178 );
3179 let out = render(src, &sites, &all);
3180 assert_eq!(
3181 out.text.lines().count(),
3182 src.lines().count(),
3183 "line numbers are preserved"
3184 );
3185 assert!(
3186 out.text
3187 .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
3188 "{}",
3189 out.text
3190 );
3191 assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
3192 syn::parse_file(&out.text).expect("instrumented source parses");
3193
3194 let inner = render(src, &sites, &|id| id == 4);
3196 assert!(
3197 inner.text.contains("check(((match (&(a), &(3))"),
3198 "{}",
3199 inner.text
3200 );
3201 assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
3202 syn::parse_file(&inner.text).unwrap();
3203 }
3204
3205 #[test]
3206 fn skips_tests_const_contexts_and_macros() {
3207 let src = r#"
3208 const LIMIT: bool = 1 < 2;
3209 static S: bool = 3 > 2;
3210 const fn c(a: u8) -> bool { a < 1 }
3211 fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
3212 enum E { A = (5 > 4) as isize }
3213 struct T;
3214 impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
3215 #[cfg(test)]
3216 mod tests { fn t(a: u8) -> bool { a == 1 } }
3217 #[cfg(test)]
3218 mod more_tests;
3219 #[cfg(test)]
3220 #[doc = "not a path"]
3221 mod documented;
3222 #[cfg(test)]
3223 #[path = "support/helpers.rs"]
3224 mod helpers;
3225 #[cfg(all(test, feature = "x"))]
3226 fn helper(a: u8) -> bool { a != 1 }
3227 #[test]
3228 fn a_test() { let a = 1; if a == 2 { panic!() } }
3229 #[tokio::test]
3230 async fn async_test() { let a = 1; if a == 3 { panic!() } }
3231 #[cfg(not(test))]
3232 fn real(a: u8) -> bool { a == 100 }
3233 #[cfg(feature = "test-utils")]
3234 fn also_real(a: u8) -> bool { a == 101 }
3235 fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
3236 "#;
3237 let found = found(src, 0).unwrap();
3238 let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
3239 assert_eq!(
3240 texts,
3241 [
3242 "a == 100",
3243 "a == 101",
3244 "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
3245 "0..=9 => ..",
3246 "a == 102"
3247 ]
3248 );
3249 assert_eq!(
3250 found.test_modules,
3251 [
3252 TestModule {
3253 name: "more_tests".into(),
3254 path: None
3255 },
3256 TestModule {
3257 name: "documented".into(),
3258 path: None
3259 },
3260 TestModule {
3261 name: "helpers".into(),
3262 path: Some("support/helpers.rs".into())
3263 },
3264 ]
3265 );
3266 }
3267
3268 #[test]
3269 fn deletable_statements() {
3270 let src = r#"
3271 async fn f(s: &mut S) -> Result<(), E> {
3272 s.validate()?;
3273 s.total += 1;
3274 s.flag = true;
3275 helper(s);
3276 s.flush().await?;
3277 s.sync().await;
3278 let x = s.get();
3279 println!("{x}");
3280 if x > 0 { return Ok(()); }
3281 s.done()
3282 }
3283 "#;
3284 let texts: Vec<String> = found(src, 0)
3285 .unwrap()
3286 .sites
3287 .into_iter()
3288 .filter(|s| s.kind == SiteKind::Stmt)
3289 .map(|s| s.text)
3290 .collect();
3291 assert_eq!(
3292 texts,
3293 [
3294 "s.validate()?;",
3295 "s.total += 1;",
3296 "s.flag = true;",
3297 "helper(s);",
3298 "s.flush().await?;",
3299 "s.sync().await;"
3300 ]
3301 );
3302 }
3303
3304 #[test]
3305 fn maps_offsets_back_and_blames_the_innermost_site() {
3306 let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
3307 let sites = found(src, 0).unwrap().sites;
3308 let out = render(src, &sites, &all);
3309 for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
3311 let hits: Vec<usize> = out
3312 .text
3313 .char_indices()
3314 .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
3315 .map(|(o, _)| o)
3316 .collect();
3317 assert!(
3318 !hits.is_empty(),
3319 "original offset {orig} ({ch}) is unreachable"
3320 );
3321 }
3322 let probe = out.text.find("ord(1u32").unwrap();
3324 let orig = out.to_original(probe);
3325 assert_eq!(blame(&sites, &all, orig), [1]);
3326 assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
3328 assert_eq!(
3329 blame(&sites, &all, src.find("fn").unwrap()),
3330 Vec::<u32>::new()
3331 );
3332 assert_eq!(out.to_original(0), 0);
3333 assert_eq!(out.to_original(out.text.len()), src.len());
3334 }
3335
3336 #[test]
3337 fn blame_is_inclusive_at_both_ends() {
3338 let src = "fn f(a: u8) -> bool { a > 1 }";
3339 let sites = found(src, 0).unwrap().sites;
3340 let (start, end) = (sites[0].start, sites[0].end);
3341 assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
3342 assert_eq!(blame(&sites, &all, start), [0]);
3343 assert_eq!(blame(&sites, &all, end), [0]);
3344 assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
3345 let out = render(src, &sites, &all);
3347 assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
3348 assert_eq!(
3349 out.to_original(out.text.find("tmt_val()) } })").unwrap()),
3350 end
3351 );
3352 assert_eq!(
3353 out.to_original(out.text.find("), &(").unwrap() + 2),
3354 sites[0].start + 1
3355 );
3356 }
3357
3358 #[test]
3359 fn finds_sites_in_impls_and_array_elements() {
3360 let src = r#"
3361 struct T(u8);
3362 impl T { fn small(&self) -> bool { self.0 < 3 } }
3363 #[cfg(test)]
3364 impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
3365 trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
3366 fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
3367 fn closure(a: u8) -> bool { (|| a < 7)() }
3368 "#;
3369 let texts: Vec<String> = found(src, 0)
3370 .unwrap()
3371 .sites
3372 .into_iter()
3373 .map(|s| s.text)
3374 .collect();
3375 assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
3376 }
3377
3378 #[test]
3379 fn logic_and_arithmetic_sites() {
3380 let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
3381 let found = found(src, 0).unwrap().sites;
3382 let kinds: Vec<String> = found
3383 .iter()
3384 .map(|s| match &s.kind {
3385 SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
3386 SiteKind::Arith { op, lhs, rhs, .. } => {
3387 format!("arith {} [{lhs}] [{rhs}]", op.symbol())
3388 }
3389 SiteKind::Not { operand, .. } => format!("not [{operand}]"),
3390 other => format!("{other:?}"),
3391 })
3392 .collect();
3393 assert_eq!(
3394 kinds,
3395 [
3396 "logic and=false [a && b] [!a]",
3397 "logic and=true [a] [b]",
3398 "not [a]",
3399 "arith + [x] [y * 2]",
3400 "arith * [y] [2]",
3401 "arith - [x] [1 % y]",
3402 "arith % [1] [y]",
3403 ]
3404 );
3405 let out = render(src, &found, &all).text;
3406 syn::parse_file(&out).expect("instrumented source parses");
3407 assert!(
3408 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 })"),
3409 "{out}"
3410 );
3411 assert!(
3412 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) } })"),
3413 "{out}"
3414 );
3415 for op in ArithOp::ALL {
3417 assert_ne!(op.swapped(), op);
3418 for assign in [false, true] {
3419 let method = op.method(assign);
3420 let fallback = format!("{} {method} ", op.fallback_trait(assign));
3421 assert!(
3422 crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
3423 "{method}"
3424 );
3425 assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
3426 assert!(
3427 crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
3428 "{op:?}"
3429 );
3430 }
3431 }
3432 }
3433
3434 #[test]
3435 fn let_chains_and_literal_arithmetic_are_left_alone() {
3436 let src = r#"
3437 fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
3438 if let Some(x) = o && a && x > 1 { return 1; }
3439 let k = 60 * 60;
3440 (n & 3) | (n << 1) ^ k
3441 }
3442 "#;
3443 let texts: Vec<String> = found(src, 0)
3444 .unwrap()
3445 .sites
3446 .into_iter()
3447 .map(|s| s.text)
3448 .collect();
3449 assert_eq!(
3450 texts,
3451 [
3452 "x > 1",
3453 "(n & 3) | (n << 1) ^ k",
3454 "n & 3",
3455 "(n << 1) ^ k",
3456 "n << 1"
3457 ]
3458 );
3459 }
3460
3461 #[test]
3462 fn attributes_const_methods_and_let_on_the_right() {
3463 let src = r#"
3464 struct T(u8);
3465 impl T {
3466 const fn in_const(&self) -> bool { self.0 < 1 }
3467 #[test]
3468 fn test_method(&self) -> bool { self.0 < 2 }
3469 fn real(&self) -> bool { self.0 < 3 }
3470 }
3471 trait Tr {
3472 #[cfg(test)]
3473 fn only_in_tests(&self, a: u8) -> bool { a < 4 }
3474 }
3475 fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
3476 #[cfg(feature = "x")]
3477 s.guarded();
3478 #[allow(unused)]
3479 s.total += 1;
3480 #[allow(unused)]
3481 s.check()?;
3482 #[allow(unused)]
3483 s.sync().await;
3484 s.plain();
3485 if a && let Some(v) = o { s.use_it(v); }
3486 Ok(())
3487 }
3488 "#;
3489 let texts: Vec<String> = found(src, 0)
3490 .unwrap()
3491 .sites
3492 .into_iter()
3493 .map(|s| s.text)
3494 .collect();
3495 assert_eq!(
3498 texts,
3499 [
3500 "self.0 < 3",
3501 "#[allow(unused)]\n s.total += 1;",
3502 "s.plain();",
3503 "#[allow(unused)]\n s.total += 1",
3504 "s.use_it(v);"
3505 ]
3506 );
3507 let found = found(src, 0).unwrap().sites;
3508 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3509 }
3510
3511 #[test]
3512 fn compound_assignment_negation_and_bit_operators() {
3513 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 }";
3514 let sites = found(src, 0).unwrap().sites;
3515 let kinds: Vec<String> = sites
3516 .iter()
3517 .map(|s| match &s.kind {
3518 SiteKind::Arith {
3519 op,
3520 assign,
3521 lhs,
3522 rhs,
3523 ..
3524 } => format!(
3525 "{lhs} {}{} {rhs}",
3526 op.symbol(),
3527 if *assign { "=" } else { "" }
3528 ),
3529 SiteKind::Not { operand, .. } => format!("!{operand}"),
3530 SiteKind::Stmt => "stmt".to_string(),
3531 other => format!("{other:?}"),
3532 })
3533 .collect();
3534 assert_eq!(
3535 kinds,
3536 [
3537 "stmt",
3538 "stmt",
3539 "*total += n",
3540 "*total <<= 1",
3541 "!ok",
3542 "!n",
3543 "!m",
3544 "n & 7"
3545 ]
3546 );
3547 let out = render(src, &sites, &all).text;
3548 syn::parse_file(&out).expect("instrumented source parses");
3549 for expected in [
3550 "(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) } });",
3551 "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
3552 "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) } }) {",
3553 "(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) } })",
3554 ] {
3555 assert!(out.contains(expected), "missing {expected}\nin {out}");
3556 }
3557 let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
3559 let sites = found(nested, 0).unwrap().sites;
3560 let out = render(nested, &sites, &all).text;
3561 syn::parse_file(&out).expect("instrumented source parses");
3562 assert!(
3563 out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
3564 "{out}"
3565 );
3566 let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
3568 let sites = found(capture, 0).unwrap().sites;
3569 let out = render(capture, &sites, &all).text;
3570 syn::parse_file(&out).expect("instrumented source parses");
3571 for arm in out.split("__tmt_c => ").skip(1) {
3573 assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
3574 }
3575 for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
3576 assert!(
3577 arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
3578 "{arm}"
3579 );
3580 }
3581 }
3582
3583 #[test]
3584 fn compound_assignment_is_probed_only_on_plain_places() {
3585 let src = r#"
3586 fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
3587 let mut local = 0u32;
3588 local += 1;
3589 s.count += 1;
3590 s.inner.total -= 2;
3591 *p *= 3;
3592 (*p) += 4;
3593 v[i] += 5;
3594 v[next()] += 6;
3595 s.get_mut().x += 7;
3596 *s.slot() += 8;
3597 }
3598 "#;
3599 let probed: Vec<String> = found(src, 0)
3600 .unwrap()
3601 .sites
3602 .into_iter()
3603 .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
3604 .map(|s| s.text)
3605 .collect();
3606 assert_eq!(
3607 probed,
3608 [
3609 "local += 1",
3610 "s.count += 1",
3611 "s.inner.total -= 2",
3612 "*p *= 3",
3613 "(*p) += 4"
3614 ]
3615 );
3616 let deletable = found(src, 0)
3618 .unwrap()
3619 .sites
3620 .iter()
3621 .filter(|s| s.kind == SiteKind::Stmt)
3622 .count();
3623 assert_eq!(deletable, 9);
3624 }
3625
3626 #[test]
3627 fn bool_functions_are_return_sites() {
3628 let src = r#"
3629 pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
3630 fn count(a: u8) -> u8 { a }
3631 fn unit(a: u8) { let _ = a; }
3632 const fn in_const(a: u8) -> bool { a > 2 }
3633 #[test]
3634 fn a_test() -> bool { true }
3635 struct T;
3636 impl T { fn method(&self) -> bool { true } }
3637 trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
3638 fn boxed() -> Box<bool> { Box::new(true) }
3639 fn qualified() -> core::primitive::bool { true }
3640 "#;
3641 let sites = discover(src, 0).unwrap().sites;
3642 let returns: Vec<(&str, &str, usize)> = sites
3643 .iter()
3644 .filter_map(|s| match &s.kind {
3645 SiteKind::Return {
3646 name, option: None, ..
3647 } => Some((name.as_str(), s.text.as_str(), s.line)),
3648 _ => None,
3649 })
3650 .collect();
3651 assert_eq!(
3652 returns,
3653 [
3654 ("is_ok", "fn is_ok(a: u8) -> bool", 2),
3655 ("method", "fn method(&self) -> bool", 9),
3656 ("provided", "fn provided(&self) -> bool", 10),
3657 ]
3658 );
3659 let out = render(src, &sites, &all).text;
3660 syn::parse_file(&out).expect("instrumented source parses");
3661 assert!(
3662 out.contains(
3663 "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
3664 if !crate::__tmt_rt::live(1u32) { return true; } \
3665 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
3666 ),
3667 "{out}"
3668 );
3669 assert!(
3670 out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3671 "{out}"
3672 );
3673 assert_eq!(
3674 out.lines().count(),
3675 src.lines().count(),
3676 "line numbers are preserved"
3677 );
3678 let rendered = render(src, &sites, &all);
3680 let wrapper = rendered.text.find("ret(0u32").unwrap();
3681 assert_eq!(rendered.inserted_by(wrapper), Some(0));
3682 let replaced = rendered.text.find("return false; } let b").unwrap();
3685 assert_eq!(rendered.inserted_by(replaced), Some(2));
3686 assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
3687 }
3688
3689 #[test]
3690 fn ids_are_consecutive_across_every_kind_of_site() {
3691 let src = r#"
3692 fn a(x: u8) -> bool { x > 1 }
3693 fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
3694 fn c(s: &mut S) { s.n += 1; s.go(); }
3695 "#;
3696 let sites = discover(src, 10).unwrap().sites;
3697 let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
3698 assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
3699 let texts: Vec<&str> = sites
3700 .iter()
3701 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3702 .map(|s| s.text.as_str())
3703 .collect();
3704 assert_eq!(
3705 texts,
3706 [
3707 "fn a(x: u8) -> bool",
3708 "x > 1",
3709 "fn b(x: u8) -> bool",
3710 "!(x > 2) && !!flag(x)",
3711 "!(x > 2)",
3712 "x > 2",
3713 "!!flag(x)",
3714 "!flag(x)",
3715 "s.n += 1;",
3716 "s.go();",
3717 "s.n += 1",
3718 ]
3719 );
3720 syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
3721 }
3722
3723 #[test]
3724 fn only_calls_and_assignments_are_deletable() {
3725 let src = r#"
3726 async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
3727 s.field;
3728 v[0];
3729 (s.a, s.b);
3730 s.value?;
3731 s.future.await;
3732 s.x = 1;
3733 s.x -= 1;
3734 s.x == 1;
3735 s.call().await?;
3736 Ok(())
3737 }
3738 "#;
3739 let texts: Vec<String> = found(src, 0)
3740 .unwrap()
3741 .sites
3742 .into_iter()
3743 .filter(|s| s.kind == SiteKind::Stmt)
3744 .map(|s| s.text)
3745 .collect();
3746 assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
3747 }
3748
3749 #[test]
3750 fn ranges_match_arms_min_max_and_option_results() {
3751 let src = r#"
3752 fn find(v: &[u32], limit: u32) -> Option<u32> {
3753 for i in 0..v.len() {
3754 let capped = v[i].min(limit).max(1);
3755 match capped {
3756 0 => return None,
3757 n if n > 5 => return Some(n),
3758 1..=3 => continue,
3759 other => { let _ = other; }
3760 }
3761 }
3762 let _ = &v[1..=2];
3763 for _ in 1..=limit as usize {}
3764 let _ = 'a'..'z';
3765 let _ = v.iter().max();
3766 None
3767 }
3768 fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
3769 fn hidden() -> Option<impl Sized> { Some(1) }
3770 fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
3771 "#;
3772 let sites = discover(src, 0).unwrap().sites;
3773 let kinds: Vec<String> = sites
3774 .iter()
3775 .filter_map(|s| match &s.kind {
3776 SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
3777 SiteKind::Range {
3778 inclusive,
3779 lhs,
3780 rhs,
3781 ..
3782 } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
3783 SiteKind::Arm { pattern, guard, .. } => Some(format!(
3784 "arm {pattern} guarded={}",
3785 matches!(guard, ArmGuard::Existing(..))
3786 )),
3787 SiteKind::MinMax {
3788 max,
3789 receiver,
3790 argument,
3791 ..
3792 } => Some(format!("minmax {receiver} {argument} max={max}")),
3793 _ => None,
3794 })
3795 .collect();
3796 assert_eq!(
3797 kinds,
3798 [
3799 "range 0 v.len() inclusive=false",
3800 "minmax v[i].min(limit) 1 max=true",
3801 "minmax v[i] limit max=false",
3802 "arm 0 guarded=false",
3804 "arm n if n > 5 guarded=true",
3805 "arm 1..=3 guarded=false",
3806 "range 1 limit as usize inclusive=true",
3808 "return first Some(\"Option<u32>\")",
3809 ]
3810 );
3811 let out = render(src, &sites, &all).text;
3812 syn::parse_file(&out).expect("instrumented source parses");
3813 assert_eq!(out.lines().count(), src.lines().count());
3814 let option = sites
3815 .iter()
3816 .find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
3817 .unwrap();
3818 assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
3819 assert!(
3820 out.contains(&format!(
3821 "crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
3822 option.id
3823 )),
3824 "{out}"
3825 );
3826 assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
3827 assert!(
3828 out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
3829 "{out}"
3830 );
3831 assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
3832 assert!(
3833 out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
3834 "{out}"
3835 );
3836 assert!(
3839 out.contains("(match (&(v[i]), limit) {")
3840 && out.contains(
3841 "Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
3842 )
3843 && out.contains(
3844 ".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
3845 ),
3846 "{out}"
3847 );
3848 assert!(
3849 !out.contains(".min(limit)") && !out.contains(".max(1)"),
3850 "{out}"
3851 );
3852 assert!(
3853 out.contains("v.iter().max()"),
3854 "an iterator's max is another method: {out}"
3855 );
3856 }
3857
3858 #[test]
3859 fn macro_arguments() {
3860 let src = r#"
3861 fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
3862 assert!(a < 100);
3863 debug_assert!(a < 101, "message {}", a < 102);
3864 assert_eq!(a < 1, b < 2, "context {}", a + 3);
3865 let _ = format!("{} {name}", a < 4, name = b < 5);
3866 write!(out, "{}", a < 6).unwrap();
3867 if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
3868 custom!(a < 10);
3869 let _ = vec![a < 11; 2];
3870 vec![a + b, (a < 12) as u32]
3871 }
3872 "#;
3873 let texts: Vec<String> = found(src, 0)
3874 .unwrap()
3875 .sites
3876 .into_iter()
3877 .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
3878 .map(|s| s.text)
3879 .collect();
3880 assert_eq!(
3881 texts,
3882 [
3883 "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
3884 "a < 12"
3885 ]
3886 );
3887 let found = found(src, 0).unwrap().sites;
3888 syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3889 }
3890
3891 #[test]
3892 fn non_ascii_source_keeps_byte_offsets() {
3893 let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
3894 let sites = found(src, 0).unwrap().sites;
3895 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3896 assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
3897 syn::parse_file(&render(src, &sites, &all).text).unwrap();
3898 }
3899
3900 #[test]
3901 fn unparseable_source_is_an_error() {
3902 assert!(discover("fn f( {", 0).is_err());
3903 }
3904 fn labelled(src: &str) -> Vec<String> {
3906 discover(src, 0)
3907 .unwrap()
3908 .sites
3909 .iter()
3910 .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3911 .map(|s| {
3912 let kind = match &s.kind {
3913 SiteKind::Cmp { .. } => "cmp",
3914 SiteKind::Logic { .. } => "logic",
3915 SiteKind::Arith { .. } => "arith",
3916 SiteKind::Not { .. } => "not",
3917 SiteKind::Return { .. } => "return",
3918 SiteKind::MinMax { .. } => "minmax",
3919 SiteKind::Range { .. } => "range",
3920 SiteKind::Arm { .. } => "arm",
3921 SiteKind::Stmt => "stmt",
3922 SiteKind::Neg { .. } => "neg",
3923 SiteKind::Guard { .. } => "guard",
3924 SiteKind::Field { .. } => "field",
3925 SiteKind::Body { .. } => "body",
3926 };
3927 format!("{kind} {}", s.text)
3928 })
3929 .collect()
3930 }
3931
3932 #[test]
3933 fn byte_order_mark_and_interpreter_line_are_refused() {
3934 let body = "fn f(a: u8) -> bool { a > 1 }";
3935 assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
3936 assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
3937 assert_eq!(
3939 labelled(&format!("#![allow(dead_code)]\n{body}")),
3940 ["return fn f(a: u8) -> bool", "cmp a > 1"]
3941 );
3942 }
3943
3944 #[test]
3945 fn which_result_types_make_a_return_site() {
3946 let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
3947 fn b() -> Option { g() }\n\
3948 fn c() -> Vec<u8> { g() }\n\
3949 fn d() -> std::option::Option<u8> { g() }\n\
3950 fn e() -> <S>::bool { g() }\n\
3951 fn e2() -> <S as Tr>::bool { g() }\n\
3952 fn one(a: u8) -> bool { a > 1 }\n\
3953 fn two(a: u8) -> bool { let b = a; b > 1 }\n\
3954 fn early(a: u8) -> bool { return a > 1; }\n";
3955 let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
3956 .unwrap()
3957 .sites
3958 .into_iter()
3959 .filter_map(|s| match s.kind {
3960 SiteKind::Return {
3961 name,
3962 option,
3963 sole_expr,
3964 } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
3965 _ => None,
3966 })
3967 .collect();
3968 assert_eq!(
3969 returns,
3970 [
3971 (
3972 "d".to_string(),
3973 Some("std::option::Option<u8>".to_string()),
3974 Some("g()")
3975 ),
3976 ("one".to_string(), None, Some("a > 1")),
3978 ("two".to_string(), None, None),
3979 ]
3980 );
3981 }
3982
3983 #[test]
3984 fn places_chains_attributes_and_shadowed_macros() {
3985 assert_eq!(
3989 labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
3990 [
3991 "stmt #[allow(unused)] x += 1;",
3992 "stmt (x) += 2;",
3993 "arith (x) += 2"
3994 ]
3995 );
3996 assert_eq!(
3998 labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
3999 ["cmp a > 1", "stmt g(b);"]
4000 );
4001 assert_eq!(
4003 labelled(
4004 "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
4005 ),
4006 ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
4007 );
4008 assert_eq!(
4010 labelled(
4011 "macro_rules! vec { ($($t:tt)*) => {} }\n\
4012 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
4013 ),
4014 ["cmp a > 2"]
4015 );
4016 assert_eq!(
4017 labelled(
4018 "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
4019 ),
4020 ["return fn g(a: u8) -> bool", "cmp a > 2"]
4021 );
4022 }
4023
4024 #[test]
4025 fn min_max_and_ranges_that_are_left_alone() {
4026 assert_eq!(
4027 labelled(
4028 "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
4029 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
4030 ),
4031 ["minmax a.max(b)"]
4032 );
4033 let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
4035 for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
4036 assert_eq!(
4037 labelled(src),
4038 [
4039 "range a..10",
4040 "range 1..b",
4041 "range (a + 1)..(b * 2)",
4042 "arith a + 1",
4043 "arith b * 2",
4044 "neg -6"
4046 ]
4047 );
4048 let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
4049 assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
4051 assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
4052 assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
4053 }
4054
4055 #[test]
4056 fn which_arms_can_be_removed() {
4057 let src = "fn f(k: u8) -> u8 {\n\
4058 \x20 let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
4059 \x20 let b = match k { 1 => 1, NONE => 0 };\n\
4060 \x20 let c = match k { 1 => 1, n @ 0..=9 => n };\n\
4061 \x20 let d = match k {\n\
4062 \x20 1 => 1,\n\
4063 \x20 _ => 0,\n\
4064 \x20 };\n\
4065 \x20 a + b + c + d\n\
4066 }\n";
4067 let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
4068 .unwrap()
4069 .sites
4070 .into_iter()
4071 .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
4072 .map(|s| (s.id, s.line, s.column, s.text))
4073 .collect();
4074 assert_eq!(
4077 arms,
4078 [
4079 (9, 2, 23, "1 => ..".to_string()),
4081 (10, 2, 39, "2 => ..".to_string()),
4082 (11, 6, 9, "1 => ..".to_string()),
4083 ]
4084 );
4085 }
4086
4087 #[test]
4088 fn offsets_around_inserted_text() {
4089 let src = "fn f(a: u8) -> bool { a > 1 }";
4090 let sites = found(src, 0).unwrap().sites;
4091 let out = render(src, &sites, &all);
4092 let start = sites[0].start;
4093 let copied_a = out.text.find("a), &(").unwrap();
4096 assert_eq!(out.to_original(copied_a), start);
4097 assert_eq!(out.to_original(copied_a - 1), start);
4098 assert_eq!(out.to_original(copied_a + 1), start + 1);
4099 assert_eq!(out.to_original(out.text.len() + 10), src.len());
4101
4102 let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
4105 let sites = discover(src, 0).unwrap().sites;
4106 let out = render(src, &sites, &all);
4107 let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
4108 assert!(
4109 out.text[inner_probe..].starts_with("(match (b, 1)"),
4110 "{}",
4111 out.text
4112 );
4113 assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
4114 let arith = sites
4115 .iter()
4116 .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
4117 .unwrap();
4118 assert_eq!(
4119 blame(&sites, &all, out.to_original(inner_probe)),
4120 [arith.id]
4121 );
4122 assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
4124 assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
4125 let opening = "(match (b, ";
4127 let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
4128 assert!(out.text[inner_probe..].starts_with(opening));
4129 assert_eq!(out.inserted_by(first), Some(arith.id));
4130 assert_eq!(out.inserted_by(last), Some(arith.id));
4131 assert_eq!(out.inserted_by(last + 1), None);
4132 assert_eq!(out.inserted_by(0), None);
4133 }
4134 fn values(ty: &str) -> Vec<String> {
4135 let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
4136 .unwrap_or_else(|e| panic!("{ty}: {e}"));
4137 body_values(&function.sig.output)
4138 }
4139
4140 #[test]
4142 fn replacement_values_by_return_type() {
4143 let rows: &[(&str, &[&str])] = &[
4144 ("()", &["()"]),
4145 ("i8", &["0", "1", "-1"]),
4146 ("isize", &["0", "1", "-1"]),
4147 ("i128", &["0", "1", "-1"]),
4148 ("u8", &["0", "1"]),
4149 ("usize", &["0", "1"]),
4150 ("u128", &["0", "1"]),
4151 ("f32", &["0.0", "1.0", "-1.0"]),
4152 ("f64", &["0.0", "1.0", "-1.0"]),
4153 ("bool", &["true", "false"]),
4154 (
4155 "NonZeroI32",
4156 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4157 ),
4158 ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
4159 ("NonZero<u64>", &["1.try_into().unwrap()"]),
4160 (
4161 "NonZero<i64>",
4162 &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
4163 ),
4164 ("String", &["String::new()", "\"xyzzy\".into()"]),
4165 ("&str", &["\"\"", "\"xyzzy\""]),
4166 ("&'static str", &["\"\"", "\"xyzzy\""]),
4167 ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
4169 ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
4170 (
4171 "&mut bool",
4172 &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
4173 ),
4174 (
4175 "&[u8]",
4176 &[
4177 "Vec::leak(Vec::new())",
4178 "Vec::leak(vec![0])",
4179 "Vec::leak(vec![1])",
4180 ],
4181 ),
4182 (
4183 "&mut [bool]",
4184 &[
4185 "Vec::leak(Vec::new())",
4186 "Vec::leak(vec![true])",
4187 "Vec::leak(vec![false])",
4188 ],
4189 ),
4190 ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
4191 ("io::Result<()>", &["Ok(())"]),
4192 ("fmt::Result", &["Ok(Default::default())"]),
4194 ("Result", &["Ok(Default::default())"]),
4195 ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
4196 ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
4197 ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
4198 (
4199 "std::rc::Rc<u8>",
4200 &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
4201 ),
4202 ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
4203 ("RefCell<()>", &["RefCell::new(())"]),
4204 ("Mutex<()>", &["Mutex::new(())"]),
4205 ("Cell<()>", &["Cell::new(())"]),
4206 (
4207 "HashSet<u8>",
4208 &[
4209 "HashSet::new()",
4210 "HashSet::from_iter([0])",
4211 "HashSet::from_iter([1])",
4212 ],
4213 ),
4214 (
4215 "BTreeSet<()>",
4216 &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
4217 ),
4218 (
4219 "BinaryHeap<()>",
4220 &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
4221 ),
4222 (
4223 "LinkedList<()>",
4224 &["LinkedList::new()", "LinkedList::from_iter([()])"],
4225 ),
4226 (
4227 "VecDeque<()>",
4228 &["VecDeque::new()", "VecDeque::from_iter([()])"],
4229 ),
4230 (
4231 "HashMap<bool, u8>",
4232 &[
4233 "HashMap::new()",
4234 "HashMap::from_iter([(true, 0)])",
4235 "HashMap::from_iter([(true, 1)])",
4236 "HashMap::from_iter([(false, 0)])",
4237 "HashMap::from_iter([(false, 1)])",
4238 ],
4239 ),
4240 (
4241 "std::collections::BTreeMap<(), ()>",
4242 &[
4243 "std::collections::BTreeMap::new()",
4244 "std::collections::BTreeMap::from_iter([((), ())])",
4245 ],
4246 ),
4247 (
4248 "Cow<'a, str>",
4249 &[
4250 "Cow::Borrowed(\"\")",
4251 "Cow::Owned(\"\".to_owned())",
4252 "Cow::Borrowed(\"xyzzy\")",
4253 "Cow::Owned(\"xyzzy\".to_owned())",
4254 ],
4255 ),
4256 ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
4257 ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
4258 (
4259 "(u8, bool)",
4260 &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
4261 ),
4262 ("(bool,)", &["(true,)", "(false,)"]),
4263 ("HttpResponse", &["HttpResponse::Ok().finish()"]),
4264 (
4265 "actix_web::HttpResponse",
4266 &["actix_web::HttpResponse::Ok().finish()"],
4267 ),
4268 ("Config", &["Default::default()"]),
4269 ("Self", &["Default::default()"]),
4270 ("<T as Tr>::Out", &["Default::default()"]),
4271 ("<T as Tr>::String", &["Default::default()"]),
4273 ("<T>::bool", &["Default::default()"]),
4274 ("fn(u8) -> u8", &["Default::default()"]),
4275 ("*const u8", &["Default::default()"]),
4276 (
4278 "Result<Option<String>, E>",
4279 &[
4280 "Ok(None)",
4281 "Ok(Some(String::new()))",
4282 "Ok(Some(\"xyzzy\".into()))",
4283 ],
4284 ),
4285 ("(Vec<()>)", &["vec![]", "vec![()]"]),
4286 ("Option<Config>", &["None", "Some(Default::default())"]),
4287 ("!", &[]),
4289 ("impl Iterator<Item = u8>", &[]),
4290 ("Box<impl Fn()>", &[]),
4291 ("Option<!>", &["None"]),
4292 ];
4293 for (ty, expected) in rows {
4294 assert_eq!(values(ty), *expected, "{ty}");
4295 }
4296 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4298 assert_eq!(body_values(&unit.sig.output), ["()"]);
4299 }
4300
4301 #[test]
4302 fn which_functions_get_their_body_replaced() {
4303 let src = r#"
4304 fn plain(a: u8) -> u8 { a + 1 }
4305 fn already(a: u8) -> bool { let _ = a; true }
4306 fn sole() -> bool { true }
4307 fn spaced() -> (u8, bool) { ( 0 , true ) }
4308 unsafe fn raw(a: u8) -> u8 { a }
4309 fn empty() {}
4310 fn one_call(s: &mut S) { s.go(); }
4311 fn two_calls(s: &mut S) { s.go(); s.stop(); }
4312 fn typed(s: &mut S) -> u8 { s.exit(); }
4313 fn tight() -> bool {true}
4314 #[rustfmt::skip]
4315 fn formatted(a: u8) -> u8 { a + 6 }
4316 #[mutants::timeout(5)]
4317 fn slow(a: u8) -> u8 { a + 7 }
4318 impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
4319 trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
4320 fn one_let(a: u8) { let _ = a; }
4321 fn never() -> ! { loop {} }
4322 fn hidden() -> impl Sized { 1 }
4323 #[mutants::skip]
4324 fn marked(a: u8) -> u8 { a + 2 }
4325 #[cfg_attr(test, mutants::skip)]
4326 fn marked_in_tests(a: u8) -> u8 { a + 3 }
4327 #[mutants::skip]
4328 impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
4329 #[mutants::skip]
4330 mod generated { fn inner(a: u8) -> u8 { a + 5 } }
4331 trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
4332 async fn later() -> u8 { 9 }
4333 "#;
4334 let sites = discover(src, 0).unwrap().sites;
4335 let bodies: Vec<String> = sites
4336 .iter()
4337 .filter_map(|s| match &s.kind {
4338 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
4339 _ => None,
4340 })
4341 .collect();
4342 assert_eq!(
4343 bodies,
4344 [
4345 "plain 0",
4346 "plain 1",
4347 "already true",
4348 "already false",
4349 "sole false",
4351 "spaced (0, false)",
4352 "spaced (1, true)",
4353 "spaced (1, false)",
4354 "two_calls ()",
4356 "typed 0",
4358 "typed 1",
4359 "tight false",
4360 "formatted 0",
4362 "formatted 1",
4363 "slow 0",
4364 "slow 1",
4365 "one_let ()",
4366 "provided 0",
4367 "provided 1",
4368 "later 0",
4369 "later 1",
4370 ]
4371 );
4372 let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
4374 for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
4375 assert!(!texts.contains(&skipped), "{skipped}");
4376 }
4377 for mutated in ["a + 1", "a + 6", "a + 7"] {
4378 assert!(texts.contains(&mutated), "{mutated}");
4379 }
4380 let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
4381 assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
4382
4383 let body = sites
4384 .iter()
4385 .find(|s| matches!(s.kind, SiteKind::Body { .. }))
4386 .unwrap();
4387 assert_eq!(
4388 (body.line, body.column, body.text.as_str()),
4389 (2, 13, "fn plain(a: u8) -> u8")
4390 );
4391 let out = render(src, &sites, &all).text;
4392 syn::parse_file(&out).expect("instrumented source parses");
4393 assert_eq!(out.lines().count(), src.lines().count());
4394 assert!(
4395 out.contains(
4396 "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
4397 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
4398 ),
4399 "{out}"
4400 );
4401 let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
4404 let sites = discover(tight, 0).unwrap().sites;
4405 let out = render(tight, &sites, &all).text;
4406 syn::parse_file(&out).expect("instrumented source parses");
4407 assert!(
4408 out.starts_with(
4409 "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
4410 if !crate::__tmt_rt::live(1u32) { return true; } \
4411 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
4412 ),
4413 "{out}"
4414 );
4415 assert!(
4416 out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
4417 "{out}"
4418 );
4419 }
4420
4421 #[test]
4422 fn minus_guards_and_fields() {
4423 let src = r#"
4424 fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
4425 let a = -x + -5 - -0 + (-0.0 * -y) as i32;
4426 let b = match k {
4427 Kind::A(n) if n > 1 => 1,
4428 Kind::A(n) if let Some(m) = half(n) => m,
4429 Kind::B if x > 0 && let Some(m) = half(x) => m,
4430 #[cfg(any())]
4431 Kind::B if x > 2 => 2,
4432 Kind::B => 3,
4433 };
4434 let c = match b { n if n > 3 => 1, _ => 0 };
4435 let first = Options { depth: a, name, ..base };
4436 let second = Options { depth: -b, ..Default::default() };
4437 let third = Wrap::<u8> { 0: c, ..Wrap::new() };
4438 let _ = Options { depth: 1, ..base.clone() };
4439 let _ = Options { depth: 2, ..make(3) };
4440 let _ = Options { depth: 6, ..(pick())() };
4441 let _ = -2.5 + y;
4442 let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
4443 let _ = Options { depth: 5, name: n, strict: false };
4444 first
4445 }
4446 "#;
4447 let sites = found(src, 0).unwrap().sites;
4448 let kinds: Vec<String> = sites
4449 .iter()
4450 .filter_map(|s| match &s.kind {
4451 SiteKind::Neg {
4452 operand, literal, ..
4453 } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
4454 SiteKind::Guard { can_be_false } => {
4455 Some(format!("guard {} | can_be_false={can_be_false}", s.text))
4456 }
4457 SiteKind::Field {
4458 name,
4459 shorthand,
4460 from_base: Some(from_base),
4461 ..
4462 } => Some(format!(
4463 "field {} | {name} | shorthand={shorthand} | {from_base}",
4464 s.text
4465 )),
4466 _ => None,
4467 })
4468 .collect();
4469 assert_eq!(
4470 kinds,
4471 [
4472 "neg -x | x | literal=false",
4473 "neg -5 | 5 | literal=true",
4474 "neg -0.0 | 0.0 | literal=true",
4476 "neg -y | y | literal=false",
4477 "guard n > 1 | can_be_false=true",
4479 "guard n > 3 | can_be_false=false",
4481 "field depth: a | depth | shorthand=false | (base).depth",
4482 "field name | name | shorthand=true | (base).name",
4483 "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
4484 "neg -b | b | literal=false",
4485 "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
4486 "neg -2.5 | 2.5 | literal=true",
4487 "field strict: true | strict | shorthand=false | (*other).strict",
4490 ]
4491 );
4492 let field = sites
4494 .iter()
4495 .find(|s| s.text == "depth: a")
4496 .expect("the field is a site");
4497 let line = src.lines().nth(field.line - 1).unwrap();
4498 assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
4499 assert_eq!(&src[field.start..field.end], "a");
4500 let out = render(src, &sites, &all).text;
4501 syn::parse_file(&out).expect("instrumented source parses");
4502 assert_eq!(out.lines().count(), src.lines().count());
4503 for expected in [
4504 "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
4506 "u32) { -__tmt_a } else { __tmt_a } })",
4508 "u32) { -5 } else { 5 })",
4509 "Kind::A(n) if crate::__tmt_rt::ret(",
4511 "u32, (match (&(n), &(1))",
4512 "n if crate::__tmt_rt::arm(",
4513 ") && (crate::__tmt_rt::ret(",
4514 "depth: if crate::__tmt_rt::live(",
4515 "{ a } else { (base).depth }",
4516 "name: if crate::__tmt_rt::live(",
4518 "{ name } else { (base).name }, ..base }",
4519 "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
4520 "0: if crate::__tmt_rt::live(",
4521 "Options { depth: 1, ..base.clone() }",
4522 "Options { depth: 2, ..make(3) }",
4523 "Options { depth: 6, ..(pick())() }",
4524 "Options { depth: 5, name: n, strict: false }",
4525 ] {
4526 assert!(out.contains(expected), "{expected}\n{out}");
4527 }
4528 assert!(
4529 !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
4530 "{out}"
4531 );
4532 }
4533 fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
4535 sites
4536 .iter()
4537 .flat_map(|site| {
4538 source_mutants(site).into_iter().map(|m| {
4539 let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
4540 syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
4541 format!("{} -> {}: {}", m.what, m.into, text.trim())
4542 })
4543 })
4544 .collect()
4545 }
4546
4547 #[test]
4548 fn what_cannot_be_probed_is_mutated_in_the_source() {
4549 let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
4552 fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
4553 fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
4554 impl S { const fn k(&self) -> u8 { -self.0 } }\n\
4555 trait T { const fn d(a: u8) -> u8 { a } }\n";
4556 let found = discover(src, 0).unwrap();
4557 assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
4558 let places: Vec<(usize, usize, &str)> = found
4559 .rebuild_sites
4560 .iter()
4561 .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
4562 .map(|s| (s.line, s.column, s.text.as_str()))
4563 .collect();
4564 assert_eq!(
4565 places,
4566 [
4567 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4568 (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4569 (1, 36, "a < b"),
4570 (2, 28, "*m.entry(k).or_insert(0) += 1"),
4571 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4572 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4573 (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4574 (3, 53, "0..n"),
4576 (4, 10, "const fn k(&self) -> u8"),
4577 (4, 10, "const fn k(&self) -> u8"),
4578 (4, 36, "-self.0"),
4579 (5, 11, "const fn d(a: u8) -> u8"),
4580 (5, 11, "const fn d(a: u8) -> u8"),
4581 ]
4582 );
4583 assert_eq!(
4584 found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
4585 (0..found.sites.len() as u32).collect::<Vec<_>>()
4586 );
4587 let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
4588 assert_eq!(
4589 numbered,
4590 [
4591 "fn f(m: &mut Map, k: u8)",
4592 "*m.entry(k).or_insert(0) += 1;",
4593 "m.total -= 1;",
4594 "m.total -= 1",
4595 ]
4596 );
4597 assert_eq!(
4598 mutated(src, &found.rebuild_sites)
4599 .iter()
4600 .map(|line| line.lines().next().unwrap().to_string())
4601 .take(5)
4602 .collect::<Vec<_>>(),
4603 [
4604 "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
4605 "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
4606 "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
4607 "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
4608 "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
4609 ]
4610 );
4611 let whats: Vec<String> = found
4612 .rebuild_sites
4613 .iter()
4614 .flat_map(|site| {
4615 source_mutants(site)
4616 .into_iter()
4617 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4618 })
4619 .skip(5)
4620 .collect();
4621 assert_eq!(
4622 whats,
4623 [
4624 "*m.entry(k).or_insert(0) += 1: += -> -=",
4625 "*m.entry(k).or_insert(0) += 1: += -> *=",
4626 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
4627 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
4628 "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
4629 "0..n: .. -> ..=",
4630 "const fn k(&self) -> u8: body -> 0",
4631 "const fn k(&self) -> u8: body -> 1",
4632 "-self.0: - -> ",
4633 "const fn d(a: u8) -> u8: body -> 0",
4634 "const fn d(a: u8) -> u8: body -> 1",
4635 ]
4636 );
4637 }
4638
4639 #[test]
4640 fn fields_are_removed_from_arbitrary_struct_updates() {
4641 for base in ["base", "make(seed)", "builder.make(seed)"] {
4643 for field in ["value: 9", "value"] {
4644 for attribute in ["", "#[cfg(any())] "] {
4645 let original =
4646 format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
4647 let found = discover(&original, 0).unwrap();
4648 let fields: Vec<_> = found
4649 .sites
4650 .iter()
4651 .chain(&found.rebuild_sites)
4652 .flat_map(source_mutants)
4653 .filter(|mutant| mutant.what == "field" && mutant.into == "value")
4654 .collect();
4655 if attribute.is_empty() {
4656 assert_eq!(fields.len(), 1, "{original}");
4657 let m = &fields[0];
4658 let changed = format!(
4659 "{}{}{}",
4660 &original[..m.start],
4661 m.replacement,
4662 &original[m.end..]
4663 );
4664 assert_eq!(
4665 changed,
4666 format!("fn f() -> S {{ S {{ other: 2, ..{base} }} }}")
4667 );
4668 syn::parse_file(&changed).unwrap();
4669 } else {
4670 assert!(fields.is_empty(), "{original}");
4671 }
4672 }
4673 }
4674 }
4675 let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
4676 assert!(
4677 plain
4678 .sites
4679 .iter()
4680 .chain(&plain.rebuild_sites)
4681 .flat_map(source_mutants)
4682 .all(|m| m.what != "field")
4683 );
4684 }
4685
4686 #[test]
4687 fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
4688 for outer in ["Wrapper", "Option", "Result"] {
4690 for inner in ["bool", "impl Iterator<Item = u8>"] {
4691 for error in [false, true] {
4692 let error_values: &[&str] = if error { &["7"] } else { &[] };
4693 let extra = if outer == "Result" { ", u8" } else { "" };
4694 let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
4695 let found = discover_with_errors(&source, 0, error_values).unwrap();
4696 let values: Vec<&str> = found
4697 .sites
4698 .iter()
4699 .chain(&found.rebuild_sites)
4700 .filter_map(|site| match &site.kind {
4701 SiteKind::Body { value, .. } => Some(value.as_str()),
4702 _ => None,
4703 })
4704 .collect();
4705 let example = match (outer, inner) {
4706 ("Wrapper", "bool") => "Wrapper::from_iter([false])",
4707 ("Option", "bool") => "Some(false)",
4708 ("Result", "bool") => "Ok(false)",
4709 ("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
4710 ("Option", _) => "Some(::core::iter::once(1))",
4711 ("Result", _) => "Ok(::core::iter::once(1))",
4712 _ => unreachable!(),
4713 };
4714 assert!(values.contains(&example), "{source}: {values:?}");
4715 assert_eq!(
4716 values.contains(&"Err(7)"),
4717 outer == "Result" && error,
4718 "{source}"
4719 );
4720 if inner != "bool" {
4721 assert!(found.sites.is_empty(), "{source}");
4722 }
4723 }
4724 }
4725 }
4726 }
4727
4728 #[test]
4729 fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
4730 let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
4731 fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
4732 let found = discover(source, 0).unwrap();
4733 let removals: Vec<_> = found
4734 .sites
4735 .iter()
4736 .chain(&found.rebuild_sites)
4737 .flat_map(source_mutants)
4738 .filter(|mutant| mutant.replacement.is_empty())
4739 .map(|mutant| &source[mutant.start..mutant.end])
4740 .collect();
4741 assert!(removals.contains(&"v.clear();"), "{removals:?}");
4742 assert!(removals.contains(&"0 => 4,"), "{removals:?}");
4743 assert!(
4744 removals.contains(&"#[allow(unused)] 1 => 5,"),
4745 "{removals:?}"
4746 );
4747 }
4748
4749 #[test]
4750 fn source_mutants_of_every_kind() {
4751 let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
4752 let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
4753 O { on: x, a, ..base } }";
4754 let sites = found(src, 0).unwrap().sites;
4755 assert_eq!(mutated(src, &sites).len(), 18);
4757 let changes: Vec<String> = sites
4758 .iter()
4759 .flat_map(source_mutants)
4760 .map(|m| {
4761 format!(
4762 "{} -> {} | `{}` becomes `{}`",
4763 m.what,
4764 m.into,
4765 &src[m.start..m.end],
4766 m.replacement
4767 )
4768 })
4769 .collect();
4770 assert_eq!(
4771 changes,
4772 [
4773 "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
4775 "arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
4776 "guard -> true | `n >= 1` becomes `true`",
4777 ">= -> < | ` >= ` becomes ` < `",
4778 "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
4779 "! -> | `!` becomes ``",
4780 "!= -> == | ` != ` becomes ` == `",
4781 "<= -> > | ` <= ` becomes ` > `",
4782 "- -> | `-` becomes ``",
4783 "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
4784 "> -> == | ` > ` becomes ` == `",
4785 "> -> < | ` > ` becomes ` < `",
4786 "> -> >= | ` > ` becomes ` >= `",
4787 "% -> / | ` % ` becomes ` / `",
4788 "% -> + | `a % b` becomes `(a + b)`",
4789 "== -> != | ` == ` becomes ` != `",
4790 "field -> on | `on: x,` becomes ``",
4791 "field -> a | `a,` becomes ``",
4792 ]
4793 );
4794 let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
4796 let sites = discover(src, 0).unwrap().sites;
4797 for site in &sites {
4798 let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
4799 assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
4800 }
4801 let ends = |src: &str| -> Vec<String> {
4803 discover(src, 0)
4804 .unwrap()
4805 .sites
4806 .iter()
4807 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4808 .flat_map(source_mutants)
4809 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4810 .collect()
4811 };
4812 assert_eq!(
4813 ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
4814 ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
4815 );
4816 assert_eq!(
4817 ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
4818 ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
4819 );
4820 }
4821
4822 #[test]
4823 fn iterators_to_return_instead() {
4824 let values = |ty: &str| {
4825 let function: syn::ItemFn =
4826 syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
4827 iterator_values(&function.sig.output)
4828 };
4829 assert_eq!(
4830 values("impl Iterator<Item = bool>"),
4831 [
4832 "::core::iter::empty()",
4833 "::core::iter::once(true)",
4834 "::core::iter::once(false)"
4835 ]
4836 );
4837 assert_eq!(
4838 values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
4839 3
4840 );
4841 assert_eq!(
4843 values("impl Iterator<Extra = u8, Item = ()>"),
4844 ["::core::iter::empty()", "::core::iter::once(())"]
4845 );
4846 assert_eq!(
4848 values("impl Iterator<Item = impl Sized>"),
4849 ["::core::iter::empty()"]
4850 );
4851 for other in [
4852 "impl Sized",
4853 "impl Iterator",
4854 "impl IntoIterator<Item = u8>",
4855 "Box<dyn Iterator<Item = u8>>",
4856 "u8",
4857 "()",
4858 ] {
4859 assert!(values(other).is_empty(), "{other}");
4860 }
4861 let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4862 assert!(iterator_values(&unit.sig.output).is_empty());
4863 }
4864
4865 fn built(src: &str) -> Vec<String> {
4867 let found = discover(src, 0).unwrap();
4868 found
4869 .rebuild_sites
4870 .iter()
4871 .flat_map(source_mutants)
4872 .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4873 .collect()
4874 }
4875
4876 #[test]
4877 fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
4878 let bodies = |src: &str| -> Vec<(String, bool)> {
4879 discover(src, 0)
4880 .unwrap()
4881 .sites
4882 .iter()
4883 .filter_map(|site| match &site.kind {
4884 SiteKind::Body {
4885 value, sole_expr, ..
4886 } => Some((value.clone(), sole_expr.is_some())),
4887 _ => None,
4888 })
4889 .collect()
4890 };
4891 let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
4892 assert_eq!(values("fn t() -> bool { true }"), ["false"]);
4894 assert_eq!(values("fn n() -> u8 { 0 }"), ["1"]);
4895 assert_eq!(
4896 values("fn s() -> String { String :: new () }"),
4897 ["\"xyzzy\".into()"]
4898 );
4899 assert_eq!(
4901 values("fn s() -> &'static str { \" \" }"),
4902 ["\"\"", "\"xyzzy\""]
4903 );
4904 for (body, only_computes) in [
4907 ("n > 0", true),
4908 ("!(self.limit < n) && n as u8 != 3", true),
4909 ("(n, 1).0 > *&n", true),
4910 ("self.push(n) > 0", false),
4911 ("next() > 0", false),
4912 ("matches!(n, 1)", false),
4913 ("(if n > 1 { n } else { 0 }) > 0", false),
4914 ("list[n] > 0", false),
4915 ("check(n)? > 0", false),
4916 ("(self.count += n) == ()", false),
4917 ("(self.count = n) == ()", false),
4918 ] {
4919 let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
4920 let all = bodies(&src);
4921 assert_eq!(all.len(), 2, "{body}");
4922 assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
4923 }
4924 }
4925
4926 #[test]
4927 fn items_are_named_by_what_is_around_them() {
4928 let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
4929 mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
4930 impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
4931 impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
4932 trait Tr { fn provided(&self) {} fn required(&self); }\n\
4933 static S: u8 = 3;\nlet";
4934 assert!(named_items(src).is_empty());
4936 let src = src.strip_suffix("let").unwrap();
4937 let items = named_items(src);
4938 let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
4939 assert_eq!(
4940 names,
4941 [
4942 "top",
4943 "top::inner",
4944 "m::in_mod",
4945 "m::K",
4946 "Store::commit",
4947 "Store::LIMIT",
4948 "<fmt::Display for Id<T>>::fmt",
4949 "Tr::provided",
4950 "Tr::required",
4951 "S",
4952 ]
4953 );
4954 let at = |text: &str| src.find(text).unwrap();
4956 assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
4957 assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
4958 assert_eq!(enclosing_item(&items, at("fn top")), "top");
4959 assert_eq!(enclosing_item(&items, at("mod m")), "");
4960 assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
4961 assert_eq!(enclosing_item(&items, src.len()), "");
4962 let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
4964 assert_eq!(enclosing_item(&items, first - 1), "");
4965 assert_eq!(enclosing_item(&items, first), "m::in_mod");
4966 assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
4967 assert_eq!(enclosing_item(&items, after), "");
4968 let text = "ab\nçd e\n";
4970 assert_eq!(offset_of(text, 1, 1), Some(0));
4971 assert_eq!(offset_of(text, 1, 2), Some(1));
4972 assert_eq!(offset_of(text, 2, 1), Some(3));
4973 assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
4974 assert_eq!(offset_of(text, 2, 99), Some(text.len()));
4975 assert_eq!(offset_of(text, 0, 1), None);
4976 assert_eq!(offset_of(text, 1, 0), None);
4977 }
4978
4979 #[test]
4980 fn only_the_range_of_a_for_is_probed() {
4981 let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
4982 for _ in a..b {}\n\
4983 for _ in (a..=b) {}\n\
4984 for _ in (a..b).rev() {}\n\
4985 let kept = a..b;\n\
4986 let _ = &v[a as usize..b as usize];\n\
4987 for _ in kept.clone() {}\n\
4988 for _ in 0..3 {}\n\
4989 let _ = &v[0..3];\n\
4990 (a..=b).count() }";
4991 let all = discover(src, 0).unwrap();
4992 let ranges = |sites: &[Site]| -> Vec<usize> {
4993 sites
4994 .iter()
4995 .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4996 .map(|site| site.line)
4997 .collect()
4998 };
4999 assert_eq!(ranges(&all.sites), [2, 3]);
5001 assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
5004 let literal: Vec<(&str, String)> = all
5005 .rebuild_sites
5006 .iter()
5007 .filter(|site| site.line == 8 || site.line == 9)
5008 .flat_map(|site| {
5009 source_mutants(site)
5010 .into_iter()
5011 .map(move |mutant| (site.text.as_str(), mutant.replacement))
5012 })
5013 .collect();
5014 assert_eq!(
5015 literal,
5016 [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
5017 );
5018 }
5019
5020 #[test]
5021 fn what_marks_code_as_not_to_be_mutated() {
5022 let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
5023 #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
5024 #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
5025 #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
5026 #[mutants::skip] mod generated;\n\
5027 #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
5028 mod plain;\n\
5029 mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
5030 #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
5031 let all = discover(src, 0).unwrap();
5032 let texts: Vec<&str> = found_arith(&all.sites);
5033 assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
5034 assert_eq!(
5036 all.test_modules,
5037 [
5038 TestModule {
5039 name: "generated".to_string(),
5040 path: None
5041 },
5042 TestModule {
5043 name: "other".to_string(),
5044 path: Some("gen/other.rs".to_string())
5045 },
5046 ]
5047 );
5048 }
5049
5050 fn found_arith(sites: &[Site]) -> Vec<&str> {
5051 sites
5052 .iter()
5053 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
5054 .map(|site| site.text.as_str())
5055 .collect()
5056 }
5057
5058 #[test]
5059 fn a_replaced_operator_keeps_its_operands() {
5060 assert_eq!(
5063 built("const X: i32 = 8 - 2 * 3;"),
5064 [
5065 "const X: i32 = 8 + 2 * 3;",
5066 "const X: i32 = (8) / (2 * 3);",
5067 "const X: i32 = 8 - 2 / 3;",
5068 "const X: i32 = 8 - (2 + 3);",
5069 ]
5070 );
5071 assert_eq!(
5072 built("const B: bool = P || Q && R;"),
5073 [
5074 "const B: bool = (P) && (Q && R);",
5075 "const B: bool = P || (Q || R);",
5076 ]
5077 );
5078 assert_eq!(
5079 built("const M: u8 = A & B | C;"),
5080 [
5081 "const M: u8 = (A & B) & (C);",
5082 "const M: u8 = (A & B) ^ (C);",
5083 "const M: u8 = (A | B) | C;",
5084 "const M: u8 = (A ^ B) | C;",
5085 ]
5086 );
5087 assert_eq!(
5088 built("const S: u8 = 1 << 2 + 1;"),
5089 [
5090 "const S: u8 = 1 >> 2 + 1;",
5091 "const S: u8 = 1 << 2 - 1;",
5092 "const S: u8 = 1 << (2) * (1);",
5093 ]
5094 );
5095 assert_eq!(
5097 built("const C: bool = A + 1 < B;")[..3],
5098 [
5099 "const C: bool = A + 1 == B;",
5100 "const C: bool = A + 1 > B;",
5101 "const C: bool = A + 1 <= B;",
5102 ]
5103 );
5104 let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
5105 for expected in [
5106 "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
5107 "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
5108 "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
5109 ] {
5110 assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
5111 }
5112 }
5113
5114 #[test]
5115 fn excluded_parent_items_do_not_contribute_const_sites() {
5116 let source = r#"
5117 #[cfg(test)] enum TestEnum { A = 1 + 2 }
5118 #[mutants::skip] struct Skip { a: [u8; 2 + 3] }
5119 #[cfg(test)] type Alias = [u8; 3 + 4];
5120 #[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
5121 #[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
5122 struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
5123 fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
5124 const DATA: [u8; 7 + 8] = [0; 15];
5125 "#;
5126 let found = discover(source, 0).unwrap();
5127 let sites: Vec<_> = found
5128 .rebuild_sites
5129 .iter()
5130 .map(|site| site.text.as_str())
5131 .collect();
5132 assert_eq!(sites, ["7 + 8"]);
5133 }
5134
5135 #[test]
5136 fn compile_time_expressions_get_source_mutants_but_never_probes() {
5137 for (place, context) in [
5139 ("inline", "let _ = const { 6 * 7 };"),
5140 ("repeat", "let _ = [0u8; 6 * 7];"),
5141 ("type length", "let _: [u8; 6 * 7];"),
5142 ("discriminant", "enum Value { One = 6 * 7 }"),
5143 ("const argument", "let _: Items<{ 6 * 7 }>;"),
5144 ("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
5145 ] {
5146 for qualifier in ["", "const "] {
5147 for marker in ["", "#[mutants::skip] "] {
5148 let source =
5149 format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
5150 let found = discover(&source, 0).unwrap();
5151 let variants: Vec<_> = found
5152 .rebuild_sites
5153 .iter()
5154 .filter(|site| site.text == "6 * 7")
5155 .flat_map(source_mutants)
5156 .map(|mutant| mutant.into)
5157 .collect();
5158 let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
5159 assert_eq!(variants, expected, "{place}: {source}");
5160 assert!(
5161 found.sites.iter().all(|site| site.text != "6 * 7"),
5162 "{source}"
5163 );
5164 assert_eq!(
5165 found.sites.iter().any(|site| site.text == "x * 2"),
5166 marker.is_empty() && qualifier.is_empty(),
5167 "{source}"
5168 );
5169 }
5170 }
5171 }
5172 }
5173
5174 #[test]
5175 fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
5176 let source = r#"
5177 /// The mutants::skip attribute is documented here.
5178 #[cfg(any(test, feature = "production"))]
5179 fn public(x: u32) -> u32 { x + 1 }
5180
5181 #[cfg(all(test, feature = "production"))]
5182 fn for_tests(x: u32) -> u32 { x + 2 }
5183
5184 #[cfg_attr(any(), mutants::skip)]
5185 fn skipped(x: u32) -> u32 { x + 3 }
5186 "#;
5187 let found = discover(source, 0).unwrap();
5188 let arithmetic: Vec<_> = found
5189 .sites
5190 .iter()
5191 .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
5192 .map(|site| site.text.as_str())
5193 .collect();
5194 assert_eq!(arithmetic, ["x + 1"]);
5195 }
5196
5197 #[test]
5198 fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
5199 let src = "const HALF: u64 = SPAN / 2;\n\
5200 static LIMIT: i32 = -(1 << 4);\n\
5201 impl S { const K: bool = A < B; }\n\
5202 trait T { const D: u8 = 3 + 4; const R: u8; }\n\
5203 #[cfg(test)]\n\
5204 const ONLY_IN_TESTS: u8 = 5 + 6;\n\
5205 #[mutants::skip]\n\
5206 const MARKED: u8 = 7 + 8;\n\
5207 #[cfg(test)]\n\
5208 static TEST_LIMIT: u8 = 9 + 1;\n\
5209 impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
5210 trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
5211 fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
5212 fn one(s: &mut S) { s.go(); }\n\
5213 fn two(s: &mut S) { s.go(); s.stop(); }\n\
5214 fn value(s: &mut S) -> u8 { s.get() }\n";
5215 let found = discover(src, 0).unwrap();
5216 let built: Vec<String> = found
5217 .rebuild_sites
5218 .iter()
5219 .flat_map(|site| {
5220 source_mutants(site)
5221 .into_iter()
5222 .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
5223 })
5224 .collect();
5225 assert_eq!(
5226 built,
5227 [
5228 "SPAN / 2: / -> *",
5229 "SPAN / 2: / -> %",
5230 "-(1 << 4): - -> ",
5231 "1 << 4: << -> >>",
5232 "A < B: < -> ==",
5233 "A < B: < -> >",
5234 "A < B: < -> <=",
5235 "3 + 4: + -> -",
5236 "3 + 4: + -> *",
5237 "2 + 3: + -> -",
5238 "2 + 3: + -> *",
5239 "60 * 60: * -> /",
5241 "60 * 60: * -> +",
5242 ]
5243 );
5244 mutated(src, &found.rebuild_sites);
5245 let probed: Vec<&str> = found
5247 .sites
5248 .iter()
5249 .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
5250 .map(|s| s.text.as_str())
5251 .collect();
5252 assert_eq!(probed, ["x + 60 * 60"]);
5253 assert_eq!(found.single_statement_bodies, ["one"]);
5255 let bodies: Vec<String> = found
5256 .sites
5257 .iter()
5258 .filter_map(|s| match &s.kind {
5259 SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
5260 _ => None,
5261 })
5262 .collect();
5263 assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
5264 }
5265 #[test]
5266 fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
5267 for context in [
5269 "fn f() { @let _ = [0u8; 6 * 7]; }",
5270 "fn f() { let _ = @const { 6 * 7 }; }",
5271 "struct Items<@const N: usize = { 6 * 7 }>;",
5272 "@enum E { A = 6 * 7 }",
5273 "enum E { @A = 6 * 7 }",
5274 "enum E { @A([u8; 6 * 7]) }",
5275 "@struct S { a: [u8; 6 * 7] }",
5276 "struct S { @a: [u8; 6 * 7] }",
5277 "@union U { a: [u8; 6 * 7] }",
5278 "@trait T { const D: [u8; 6 * 7]; }",
5279 "trait T { @type A = [u8; 6 * 7]; }",
5280 "@type A = [u8; 6 * 7];",
5281 "impl T for S { @type A = [u8; 6 * 7]; }",
5282 ] {
5283 for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
5284 let source = context.replace('@', attribute);
5285 let found = discover(&source, 0).unwrap();
5286 let expected: &[&str] = if attribute.is_empty() {
5287 &["6 * 7"]
5288 } else {
5289 &[]
5290 };
5291 assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
5292 assert!(found_arith(&found.sites).is_empty(), "{source}");
5293 }
5294 }
5295 for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
5297 let source =
5298 format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
5299 let found = discover(&source, 0).unwrap();
5300 assert!(found.sites.is_empty(), "{source}");
5301 assert!(found.rebuild_sites.is_empty(), "{source}");
5302 }
5303 }
5304
5305 #[test]
5306 fn compile_time_expressions_are_found_inside_types() {
5307 let built = |source: &str| -> Vec<String> {
5308 let found = discover(source, 0).unwrap();
5309 assert!(found_arith(&found.sites).is_empty(), "{source}");
5310 found_arith(&found.rebuild_sites)
5311 .into_iter()
5312 .map(str::to_string)
5313 .collect()
5314 };
5315 assert_eq!(
5317 built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
5318 ["1 + 2", "3 + 4"]
5319 );
5320 assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
5322 assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
5325 }
5326
5327 #[test]
5328 fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
5329 let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
5330 #[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
5331 #[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
5332 #[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
5333 #[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
5334 #[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
5335 let found = discover(src, 0).unwrap();
5336 assert_eq!(
5337 found_arith(&found.sites),
5338 ["a + 1", "a + 2", "a + 5", "a + 6"]
5339 );
5340 }
5341
5342 #[test]
5343 fn which_arms_are_probed_built_or_left_alone() {
5344 let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
5345 \x20 let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
5346 \x20 let q = match k { Kind::A => 1, Kind::B => 2 };\n\
5347 \x20 let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
5348 \x20 p + q + r\n\
5349 }\n";
5350 let found = discover(src, 0).unwrap();
5351 let arms = |sites: &[Site]| -> Vec<String> {
5352 sites
5353 .iter()
5354 .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
5355 .map(|site| site.text.clone())
5356 .collect()
5357 };
5358 assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
5360 assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
5364 let in_arms: Vec<&str> = found_arith(&found.sites)
5366 .into_iter()
5367 .filter(|text| text.starts_with("a + "))
5368 .collect();
5369 assert_eq!(in_arms, ["a + 3", "a + 4"]);
5370 }
5371
5372 #[test]
5373 fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
5374 let src = "fn f(a: u8, base: S) {\n\
5375 \x20 let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
5376 \x20 g(#[mutants::skip] S { v: a + 4, ..base });\n\
5377 \x20 g(#[cfg(test)] S { v: a + 5, ..base });\n\
5378 \x20 g(#[allow(unused)] S { v: a + 6, ..base });\n\
5379 \x20 g(<S as Tr>::Out { v: a + 7, ..base });\n\
5380 }\n";
5381 let found = discover(src, 0).unwrap();
5382 let fields = |sites: &[Site]| -> Vec<String> {
5383 sites
5384 .iter()
5385 .filter_map(|site| match &site.kind {
5386 SiteKind::Field { from_base, .. } => Some(format!(
5387 "{} | {}",
5388 site.text,
5389 from_base.as_deref().unwrap_or("-")
5390 )),
5391 _ => None,
5392 })
5393 .collect()
5394 };
5395 assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
5397 assert_eq!(
5400 fields(&found.rebuild_sites),
5401 ["v: a + 6 | -", "v: a + 7 | -"]
5402 );
5403 assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
5404 }
5405
5406 #[test]
5407 fn body_values_that_are_only_built() {
5408 let bodies = |sites: &[Site]| -> Vec<String> {
5409 sites
5410 .iter()
5411 .filter_map(|site| match &site.kind {
5412 SiteKind::Body { value, .. } => Some(value.clone()),
5413 _ => None,
5414 })
5415 .collect()
5416 };
5417 let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
5420 assert_eq!(bodies(&found.sites), ["Default::default()"]);
5421 assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
5422 assert_eq!(
5423 bodies(&found.rebuild_sites),
5424 [
5425 "Wrapper::from_iter([true])",
5426 "Wrapper::new(true)",
5427 "Wrapper::from(true)",
5428 "Wrapper::from_iter([false])",
5429 "Wrapper::new(false)",
5430 "Wrapper::from(false)",
5431 ]
5432 );
5433 assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
5435 let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
5438 let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
5439 assert!(bodies(&found.sites).is_empty());
5440 assert_eq!(
5441 bodies(&found.rebuild_sites),
5442 [
5443 "::core::iter::empty()",
5444 "::core::iter::once(::core::iter::empty())",
5445 "::core::iter::once(::core::iter::once(0))",
5446 "::core::iter::once(::core::iter::once(1))",
5447 ]
5448 );
5449 let function: syn::ItemFn =
5450 syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
5451 assert_eq!(
5452 iterator_values(&function.sig.output),
5453 ["::core::iter::empty()"]
5454 );
5455 }
5456}