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