Skip to main content

forge/mutation/
visitor.rs

1use crate::mutation::{
2    mutant::{Mutant, OwnedLiteral},
3    mutators::{MutationContext, mutator_registry::MutatorRegistry},
4    type_analysis::{AssignmentReplacement, MutationExclusion, MutationExclusionSet},
5};
6use eyre::Report;
7use foundry_config::MutatorType;
8use solar::ast::{Expr, ItemContract, ItemFunction, VariableDefinition, visit::Visit, yul};
9use std::{ops::ControlFlow, path::PathBuf};
10
11#[cfg(test)]
12use crate::mutation::mutators::Mutator;
13
14#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
15pub enum AssignVarTypes {
16    Literal(OwnedLiteral),
17    Identifier(String),
18    NegatedIdentifier(String),
19}
20
21/// A visitor which collect all expression to mutate as well as the mutation types
22#[allow(clippy::type_complexity)]
23pub struct MutantVisitor<'src> {
24    pub mutation_to_conduct: Vec<Mutant>,
25    errors: Vec<Report>,
26    pub mutator_registry: MutatorRegistry,
27    pub path: PathBuf,
28    pub source: Option<&'src str>,
29    /// Optional per-contract name filter. When `Some`, mutations are only collected
30    /// from contracts whose name matches the predicate.
31    pub contract_filter: Option<Box<dyn Fn(&str) -> bool>>,
32    /// Whether the currently-visited contract is allowed by `contract_filter`.
33    /// `true` when no filter is set or when we are visiting a contract whose name
34    /// matched the filter. Top-level items (outside any contract) are always
35    /// considered "allowed".
36    in_allowed_contract: bool,
37    mutation_exclusions: MutationExclusionSet,
38}
39
40impl<'src> MutantVisitor<'src> {
41    /// Create a visitor with the specified mutator operators enabled
42    pub fn with_operators(path: PathBuf, operators: &[MutatorType]) -> Self {
43        Self {
44            mutation_to_conduct: Vec::new(),
45            errors: Vec::new(),
46            mutator_registry: MutatorRegistry::from_enabled(operators),
47            path,
48            source: None,
49            contract_filter: None,
50            in_allowed_contract: true,
51            mutation_exclusions: MutationExclusionSet::new(),
52        }
53    }
54
55    /// Use only a set of mutators
56    #[cfg(test)]
57    pub fn new_with_mutators(path: PathBuf, mutators: Vec<Box<dyn Mutator>>) -> Self {
58        Self {
59            mutator_registry: MutatorRegistry::new_with_mutators(mutators),
60            ..Self::with_operators(path, &[])
61        }
62    }
63
64    /// Set the source code for extracting original text
65    pub const fn with_source(mut self, source: &'src str) -> Self {
66        self.source = Some(source);
67        self
68    }
69
70    /// Set a contract-name filter; only contracts whose name matches the
71    /// predicate will have their bodies mutated.
72    pub fn with_contract_filter<F>(mut self, filter: F) -> Self
73    where
74        F: Fn(&str) -> bool + 'static,
75    {
76        self.contract_filter = Some(Box::new(filter));
77        self
78    }
79
80    /// Exclude operator replacements rejected by type analysis.
81    pub fn with_mutation_exclusions(mut self, mutations: MutationExclusionSet) -> Self {
82        self.mutation_exclusions = mutations;
83        self
84    }
85
86    pub fn take_errors(&mut self) -> Vec<Report> {
87        std::mem::take(&mut self.errors)
88    }
89
90    fn collect_mutations(&mut self, context: &MutationContext<'_>) {
91        let result = self.mutator_registry.generate_mutations(context);
92        self.mutation_to_conduct.extend(result.mutations.into_iter().filter(|mutant| {
93            let exclusion = match &mutant.mutation {
94                crate::mutation::mutant::MutationType::Assignment(kind) => {
95                    let replacement = match kind {
96                        AssignVarTypes::Literal(OwnedLiteral::Number(value)) if value.is_zero() => {
97                            AssignmentReplacement::Zero
98                        }
99                        AssignVarTypes::Literal(OwnedLiteral::NegatedNumber(_))
100                        | AssignVarTypes::NegatedIdentifier(_) => AssignmentReplacement::Negate,
101                        _ => return true,
102                    };
103                    MutationExclusion::assignment(mutant.span, replacement)
104                }
105                crate::mutation::mutant::MutationType::BinaryOpExpr { new_op, .. } => {
106                    MutationExclusion::binary(mutant.span, *new_op)
107                }
108                crate::mutation::mutant::MutationType::UnaryOperator(unary) => {
109                    MutationExclusion::unary(mutant.span, unary.resulting_op_kind)
110                }
111                _ => return true,
112            };
113            !self.mutation_exclusions.contains(&exclusion)
114        }));
115
116        for err in result.errors {
117            self.errors.push(err.wrap_err(format!(
118                "failed to generate mutations for {}:{}:{}",
119                self.path.display(),
120                context.line_number(),
121                context.column_number()
122            )));
123        }
124    }
125}
126
127impl<'ast> Visit<'ast> for MutantVisitor<'ast> {
128    type BreakValue = ();
129
130    fn visit_item_contract(
131        &mut self,
132        contract: &'ast ItemContract<'ast>,
133    ) -> ControlFlow<Self::BreakValue> {
134        // When a contract name filter is configured, only descend into matching
135        // contracts. We toggle `in_allowed_contract` for the duration of the
136        // walk so nested visit_expr / visit_variable_definition calls can gate
137        // mutant collection accordingly.
138        let prev = self.in_allowed_contract;
139        self.in_allowed_contract =
140            self.contract_filter.as_ref().is_none_or(|filter| filter(contract.name.as_str()));
141        let res = self.walk_item_contract(contract);
142        self.in_allowed_contract = prev;
143        res
144    }
145
146    fn visit_item_function(
147        &mut self,
148        function: &'ast ItemFunction<'ast>,
149    ) -> ControlFlow<Self::BreakValue> {
150        if self.in_allowed_contract && function.body.is_some() {
151            let mut builder = MutationContext::builder()
152                .with_path(self.path.clone())
153                .with_span(function.body_span)
154                .with_function(function);
155            if let Some(src) = self.source {
156                builder = builder.with_source(src);
157            }
158            self.collect_mutations(&builder.build().expect("function body context"));
159        }
160        self.walk_item_function(function)
161    }
162
163    fn visit_variable_definition(
164        &mut self,
165        var: &'ast VariableDefinition<'ast>,
166    ) -> ControlFlow<Self::BreakValue> {
167        // Skip entirely when the surrounding contract is filtered out.
168        if !self.in_allowed_contract {
169            return self.walk_variable_definition(var);
170        }
171
172        let mut builder = MutationContext::builder()
173            .with_path(self.path.clone())
174            .with_span(var.span)
175            .with_var_definition(var);
176
177        if let Some(src) = self.source {
178            builder = builder.with_source(src);
179        }
180
181        let context = builder
182            .build()
183            .expect("MutationContext requires both path and span for variable definition");
184
185        self.collect_mutations(&context);
186        self.walk_variable_definition(var)
187    }
188
189    fn visit_expr(&mut self, expr: &'ast Expr<'ast>) -> ControlFlow<Self::BreakValue> {
190        // Skip entirely when the surrounding contract is filtered out.
191        if !self.in_allowed_contract {
192            return self.walk_expr(expr);
193        }
194
195        let mut builder = MutationContext::builder()
196            .with_path(self.path.clone())
197            .with_span(expr.span)
198            .with_expr(expr);
199
200        if let Some(src) = self.source {
201            builder = builder.with_source(src);
202        }
203
204        let context =
205            builder.build().expect("MutationContext requires both path and span for expression");
206
207        self.collect_mutations(&context);
208        self.walk_expr(expr)
209    }
210
211    fn visit_yul_expr(&mut self, expr: &'ast yul::Expr<'ast>) -> ControlFlow<Self::BreakValue> {
212        // Skip entirely when the surrounding contract is filtered out.
213        if !self.in_allowed_contract {
214            return self.walk_yul_expr(expr);
215        }
216
217        let mut builder = MutationContext::builder()
218            .with_path(self.path.clone())
219            .with_span(expr.span)
220            .with_yul_expr(expr);
221
222        if let Some(src) = self.source {
223            builder = builder.with_source(src);
224        }
225
226        let context = builder
227            .build()
228            .expect("MutationContext requires both path and span for yul expression");
229
230        self.collect_mutations(&context);
231        self.walk_yul_expr(expr)
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use eyre::{Result, eyre};
238    use solar::{
239        ast::{Arena, interface::source_map::FileName},
240        parse::Parser,
241    };
242
243    use super::*;
244    use crate::mutation::{Session, mutant::MutationType};
245
246    struct FailingExprMutator;
247
248    impl Mutator for FailingExprMutator {
249        fn generate_mutants(&self, _ctxt: &MutationContext<'_>) -> Result<Vec<Mutant>> {
250            Err(eyre!("synthetic visitor failure"))
251        }
252
253        fn is_applicable(&self, ctxt: &MutationContext<'_>) -> bool {
254            ctxt.expr.is_some()
255        }
256    }
257
258    struct PassingExprMutator;
259
260    impl Mutator for PassingExprMutator {
261        fn generate_mutants(&self, ctxt: &MutationContext<'_>) -> Result<Vec<Mutant>> {
262            Ok(vec![Mutant {
263                path: ctxt.path.clone(),
264                span: ctxt.span,
265                mutation: MutationType::DeleteExpression,
266                original: ctxt.original_text(),
267                source_line: ctxt.source_line(),
268                line_number: ctxt.line_number(),
269                column_number: ctxt.column_number(),
270            }])
271        }
272
273        fn is_applicable(&self, ctxt: &MutationContext<'_>) -> bool {
274            ctxt.expr.is_some()
275        }
276    }
277
278    #[test]
279    fn visitor_collects_mutations_and_surfaces_mutator_errors() {
280        let source = "\
281// SPDX-License-Identifier: MIT
282pragma solidity ^0.8.0;
283contract Test {
284    function test() public {
285        uint256 x = 1 + 2;
286    }
287}
288";
289        let path = PathBuf::from("test.sol");
290        let sess = Session::builder().with_silent_emitter(None).build();
291
292        sess.enter(|| {
293            let arena = Arena::new();
294            let mut parser =
295                Parser::from_lazy_source_code(&sess, &arena, FileName::Real(path.clone()), || {
296                    Ok(source.to_string())
297                })
298                .unwrap();
299            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
300            drop(parser);
301            let mut visitor = MutantVisitor::new_with_mutators(
302                path,
303                vec![Box::new(FailingExprMutator), Box::new(PassingExprMutator)],
304            )
305            .with_source(source);
306
307            let _ = visitor.visit_source_unit(&ast);
308            let errors = visitor.take_errors();
309
310            assert!(!visitor.mutation_to_conduct.is_empty());
311            assert!(!errors.is_empty());
312
313            let err = format!("{:?}", errors[0]);
314            assert!(err.contains("failed to generate mutations for test.sol:"));
315            assert!(err.contains("synthetic visitor failure"));
316        });
317    }
318
319    #[test]
320    fn visitor_excludes_binary_mutations_rejected_by_type_analysis() {
321        let source = "\
322pragma solidity ^0.8.0;
323contract Test {
324    function check(uint256 x) public pure returns (bool) {
325        return x == 0;
326    }
327}
328";
329        let path = PathBuf::from("test.sol");
330        let lo = source.find("x == 0").unwrap() as u32;
331        let span = solar::ast::Span::new(
332            solar::interface::BytePos(lo),
333            solar::interface::BytePos(lo + "x == 0".len() as u32),
334        );
335        let mutation_exclusions =
336            [MutationExclusion::binary(span, solar::ast::BinOpKind::Le)].into_iter().collect();
337        let sess = Session::builder().with_silent_emitter(None).build();
338
339        sess.enter(|| {
340            let arena = Arena::new();
341            let mut parser =
342                Parser::from_lazy_source_code(&sess, &arena, FileName::Real(path.clone()), || {
343                    Ok(source.to_string())
344                })
345                .unwrap();
346            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
347            drop(parser);
348            let mut visitor = MutantVisitor::with_operators(path, &MutatorType::all())
349                .with_source(source)
350                .with_mutation_exclusions(mutation_exclusions);
351
352            let _ = visitor.visit_source_unit(&ast);
353            let comparison_mutations = visitor.mutation_to_conduct.iter().filter_map(|mutant| {
354                let MutationType::BinaryOpExpr { new_op, .. } = mutant.mutation else {
355                    return None;
356                };
357                (mutant.span == span).then_some(new_op)
358            });
359            let comparison_mutations = comparison_mutations.collect::<Vec<_>>();
360
361            assert!(!comparison_mutations.contains(&solar::ast::BinOpKind::Le));
362            assert!(comparison_mutations.contains(&solar::ast::BinOpKind::Lt));
363        });
364    }
365
366    #[test]
367    fn visitor_excludes_assignment_mutations_rejected_by_type_analysis() {
368        let source = "\
369pragma solidity ^0.8.0;
370contract Test {
371    function check(address account) public pure {
372        address copy = account;
373    }
374}
375";
376        let path = PathBuf::from("test.sol");
377        let lo = source.rfind("account").unwrap() as u32;
378        let span = solar::ast::Span::new(
379            solar::interface::BytePos(lo),
380            solar::interface::BytePos(lo + "account".len() as u32),
381        );
382        let mutation_exclusions = [
383            MutationExclusion::assignment(span, AssignmentReplacement::Zero),
384            MutationExclusion::assignment(span, AssignmentReplacement::Negate),
385        ]
386        .into_iter()
387        .collect();
388        let sess = Session::builder().with_silent_emitter(None).build();
389
390        sess.enter(|| {
391            let arena = Arena::new();
392            let mut parser =
393                Parser::from_lazy_source_code(&sess, &arena, FileName::Real(path.clone()), || {
394                    Ok(source.to_string())
395                })
396                .unwrap();
397            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
398            drop(parser);
399            let mut visitor = MutantVisitor::new_with_mutators(
400                path,
401                vec![Box::new(crate::mutation::mutators::assignment_mutator::AssignmentMutator)],
402            )
403            .with_source(source)
404            .with_mutation_exclusions(mutation_exclusions);
405
406            let _ = visitor.visit_source_unit(&ast);
407
408            assert!(visitor.mutation_to_conduct.iter().all(|mutant| mutant.span != span));
409        });
410    }
411
412    #[test]
413    fn visitor_excludes_negated_number_but_retains_zero_assignment() {
414        let source = "\
415pragma solidity ^0.8.0;
416contract Test {
417    function check() public pure {
418        uint8 copy = 1;
419    }
420}
421";
422        let path = PathBuf::from("test.sol");
423        let lo = source.rfind('1').unwrap() as u32;
424        let span =
425            solar::ast::Span::new(solar::interface::BytePos(lo), solar::interface::BytePos(lo + 1));
426        let mutation_exclusions =
427            [MutationExclusion::assignment(span, AssignmentReplacement::Negate)]
428                .into_iter()
429                .collect();
430        let sess = Session::builder().with_silent_emitter(None).build();
431
432        sess.enter(|| {
433            let arena = Arena::new();
434            let mut parser =
435                Parser::from_lazy_source_code(&sess, &arena, FileName::Real(path.clone()), || {
436                    Ok(source.to_string())
437                })
438                .unwrap();
439            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
440            drop(parser);
441            let mut visitor = MutantVisitor::new_with_mutators(
442                path,
443                vec![Box::new(crate::mutation::mutators::assignment_mutator::AssignmentMutator)],
444            )
445            .with_source(source)
446            .with_mutation_exclusions(mutation_exclusions);
447
448            let _ = visitor.visit_source_unit(&ast);
449            let replacements = visitor
450                .mutation_to_conduct
451                .iter()
452                .filter(|mutant| mutant.span == span)
453                .map(|mutant| mutant.mutation.to_string())
454                .collect::<Vec<_>>();
455
456            assert_eq!(replacements, ["0"]);
457        });
458    }
459
460    #[test]
461    fn visitor_excludes_unsigned_negation_but_retains_unary_swaps() {
462        let source = "\
463pragma solidity ^0.8.0;
464contract Test {
465    function increment(uint256 x) public pure {
466        x++;
467    }
468}
469";
470        let path = PathBuf::from("test.sol");
471        let lo = source.find("x++").unwrap() as u32;
472        let span = solar::ast::Span::new(
473            solar::interface::BytePos(lo),
474            solar::interface::BytePos(lo + "x++".len() as u32),
475        );
476        let mutation_exclusions =
477            [MutationExclusion::unary(span, solar::ast::UnOpKind::Neg)].into_iter().collect();
478        let sess = Session::builder().with_silent_emitter(None).build();
479
480        sess.enter(|| {
481            let arena = Arena::new();
482            let mut parser =
483                Parser::from_lazy_source_code(&sess, &arena, FileName::Real(path.clone()), || {
484                    Ok(source.to_string())
485                })
486                .unwrap();
487            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
488            drop(parser);
489            let mut visitor = MutantVisitor::new_with_mutators(
490                path,
491                vec![Box::new(crate::mutation::mutators::unary_op_mutator::UnaryOpMutator)],
492            )
493            .with_source(source)
494            .with_mutation_exclusions(mutation_exclusions);
495
496            let _ = visitor.visit_source_unit(&ast);
497            let unary_mutations = visitor
498                .mutation_to_conduct
499                .iter()
500                .filter_map(|mutant| {
501                    let MutationType::UnaryOperator(unary) = &mutant.mutation else {
502                        return None;
503                    };
504                    (mutant.span == span).then_some(unary.resulting_op_kind)
505                })
506                .collect::<Vec<_>>();
507
508            assert_eq!(unary_mutations.len(), 4);
509            assert!(!unary_mutations.contains(&solar::ast::UnOpKind::Neg));
510            assert!(unary_mutations.contains(&solar::ast::UnOpKind::PreInc));
511            assert!(unary_mutations.contains(&solar::ast::UnOpKind::PreDec));
512            assert!(unary_mutations.contains(&solar::ast::UnOpKind::BitNot));
513            assert!(unary_mutations.contains(&solar::ast::UnOpKind::PostDec));
514        });
515    }
516
517    #[test]
518    fn function_body_replacements_preserve_headers_and_skip_unsupported_functions() {
519        let source = r#"
520abstract contract Target {
521    constructor() { revert(); }
522    modifier guarded() { require(true); _; }
523    function effect() public guarded { revert(); }
524    function boolean() external pure returns (bool) { return 2 > 1; }
525    function unsigned() internal pure returns (uint8 result) { result = 7; }
526    function signed() private pure returns (int256) { return -7; }
527    function account() public view returns (address) { return msg.sender; }
528    function payableAccount() public view returns (address payable) { return payable(msg.sender); }
529    function tuple() public virtual returns (uint, bool);
530    function dynamic() public pure returns (bytes memory) { return hex"1234"; }
531    function multiple() public pure returns (uint, bool) { return (7, true); }
532    function testSomething() public { revert(); }
533    function invariantSomething() public { revert(); }
534    function setUp() public { revert(); }
535    function empty() public {}
536    function emptyCommented() public { /* No work. */ }
537    function implicitReturn() public pure returns (uint256 result) {}
538    receive() external payable { revert(); }
539    fallback() external { revert(); }
540}
541contract Other { function ignored() public { revert(); } }
542"#;
543        let mutants = function_body_mutants(source);
544        let first = &mutants[0];
545        let mut mutated = source.to_string();
546        mutated.replace_range(
547            first.span.lo().0 as usize..first.span.hi().0 as usize,
548            &first.mutation.to_string(),
549        );
550        assert_eq!(
551            mutated,
552            source.replacen(
553                "function effect() public guarded { revert(); }",
554                "function effect() public guarded {}",
555                1,
556            )
557        );
558        assert_eq!(
559            mutants.iter().map(|mutant| mutant.mutation.to_string()).collect::<Vec<_>>(),
560            [
561                "{}",
562                "{ return true; }",
563                "{ return false; }",
564                "{ return 0; }",
565                "{ return 1; }",
566                "{ return 0; }",
567                "{ return 1; }",
568                "{ return -1; }",
569                "{ return address(0); }",
570                "{ return payable(address(0)); }",
571                "{}",
572                "{}",
573                "{}",
574                "{ return 1; }",
575            ]
576        );
577    }
578
579    #[test]
580    fn function_body_replacements_skip_equivalent_constants() {
581        for (ty, expression, expected) in [
582            ("bool", "(true)", vec!["false"]),
583            ("bool", "(/* Always on. */ true)", vec!["false"]),
584            ("bool", "bool((false))", vec!["true"]),
585            ("uint256", "0x0", vec!["1"]),
586            ("uint8", "uint8(0)", vec!["1"]),
587            ("uint256", "1_0e-1", vec!["0"]),
588            ("int256", "-(int8((0x1)))", vec!["0", "1"]),
589            ("int256", "int256(-1)", vec!["0", "1"]),
590            ("int256", "-(-1)", vec!["0", "-1"]),
591            ("int256", "-0", vec!["1", "-1"]),
592            ("address", "address(uint160(0x0))", vec![]),
593            ("address payable", "payable(address((0)))", vec![]),
594            // Keep replacements when evaluating the original can have side effects.
595            ("bool", "other()", vec!["true", "false"]),
596            ("uint8", "uint8(other())", vec!["0", "1"]),
597        ] {
598            let source = format!(
599                "contract Target {{ function target() public returns ({ty}) {{ return {expression}; }} }}"
600            );
601            let replacements = function_body_mutants(&source)
602                .iter()
603                .map(|mutant| mutant.mutation.to_string())
604                .collect::<Vec<_>>();
605            assert_eq!(
606                replacements,
607                expected.iter().map(|value| format!("{{ return {value}; }}")).collect::<Vec<_>>(),
608                "{source}"
609            );
610        }
611    }
612
613    fn function_body_mutants(source: &str) -> Vec<Mutant> {
614        let sess = Session::builder().with_silent_emitter(None).build();
615        sess.enter(|| {
616            let arena = Arena::new();
617            let mut parser = Parser::from_lazy_source_code(
618                &sess,
619                &arena,
620                FileName::Real("target.sol".into()),
621                || Ok(source.to_string()),
622            )
623            .unwrap();
624            let ast = parser.parse_file().map_err(|e| e.emit()).unwrap();
625            drop(parser);
626            let mut visitor =
627                MutantVisitor::with_operators("target.sol".into(), &[MutatorType::FunctionBody])
628                    .with_source(source)
629                    .with_contract_filter(|name| name == "Target");
630            let _ = visitor.visit_source_unit(&ast);
631            assert!(visitor.take_errors().is_empty());
632            for mutant in &visitor.mutation_to_conduct {
633                assert_eq!(
634                    mutant.original,
635                    &source[mutant.span.lo().0 as usize..mutant.span.hi().0 as usize]
636                );
637            }
638            visitor.mutation_to_conduct
639        })
640    }
641}