Skip to main content

forge/cmd/test/
mod.rs

1use super::{fuzz::FuzzRunArgs, watch::WatchArgs};
2use crate::{
3    MultiContractRunner, MultiContractRunnerBuilder, brutalizer,
4    decode::decode_console_logs,
5    gas_report::GasReport,
6    multi_runner::{
7        FuzzFailureReplayConfig, FuzzMinimizeConfig, FuzzMinimizeEdgeIndices, FuzzMinimizeMode,
8        FuzzMinimizeObservation, MultiNetworkConfig, ShowmapConfig, SymbolicArtifactReplayConfig,
9        TestFunctionMatcher, is_generated_symbolic_regression_contract,
10    },
11    mutation::{MutationRunConfig, run_mutation_testing},
12    result::{
13        SYMBOLIC_COUNTEREXAMPLE_ARTIFACT_SCHEMA, SuiteResult, SymbolicCounterexampleArtifact,
14        SymbolicReplayStatus, TestKind, TestKindReport, TestOutcome, TestResult, TestStatus,
15    },
16    runner::{effective_test_function_kind, inline_config_for},
17    symbolic_regression::{
18        SymbolicRegression, SymbolicRegressionConfig, attach_symbolic_regressions_to_suites,
19        collect_symbolic_artifacts_from_suites, emit_symbolic_regressions,
20    },
21    traces::{
22        CallTraceDecoderBuilder, InternalTraceMode, TraceKind,
23        debug::{ContractSources, DebugTraceIdentifier},
24        decode_trace_arena, folded_stack_trace,
25        identifier::SignaturesIdentifier,
26        render_trace_arena_inner, speedscope,
27    },
28    workspace,
29};
30use alloy_json_abi::JsonAbi;
31use alloy_primitives::U256;
32use chrono::Utc;
33use clap::{Parser, ValueEnum, ValueHint};
34use dialoguer::{Select, console::Term};
35use eyre::{Context, OptionExt, Result, bail};
36use foundry_cli::{
37    opts::{BuildOpts, EvmArgs, GlobalArgs, TracingArgs},
38    utils::{self, FoundryPathExt, LoadConfig},
39};
40use foundry_common::{
41    ContractsByArtifact, EmptyTestFilter, TestFilter, TestFunctionExt, TestFunctionKind,
42    compile::{ProjectCompiler, compile_abi_project_cached},
43    external_compiler::is_external_artifact,
44    fs,
45    fs::canonicalize_path,
46    sh_status, sh_warn, shell,
47};
48use foundry_compilers::{
49    Artifact, ArtifactId, ProjectCompileOutput,
50    artifacts::{
51        BytecodeObject, ConfigurableContractArtifact, Libraries,
52        output_selection::ContractOutputSelection,
53    },
54    compilers::{
55        Language,
56        multi::{MultiCompiler, MultiCompilerLanguage},
57    },
58    utils::source_files_iter,
59};
60use foundry_config::{
61    Config, InlineConfig, InvariantDepthMode, InvariantWorkers, figment,
62    figment::{
63        Metadata, Profile, Provider,
64        value::{Dict, Map, Value},
65    },
66    filter::GlobMatcher,
67    fs_permissions::FsAccessPermission,
68};
69use foundry_debugger::{DebuggerBuilder, ensure_dump_dir};
70use foundry_evm::{
71    backend::Backend,
72    core::evm::{EthEvmNetwork, FoundryEvmNetwork, TempoEvmNetwork},
73    executors::{ExecutorBuilder, ShowmapDomain},
74    fuzz::{BaseCounterExample, BasicTxDetails, CounterExample},
75    opts::EvmOpts,
76    traces::{
77        backtrace::BacktraceBuilder, identifier::TraceIdentifiers, prune_trace_depth,
78        trace_arena_at_depth,
79    },
80};
81use foundry_evm_networks::NetworkVariant;
82use foundry_tui::tui_mode;
83use quick_junit::{NonSuccessKind, Report, TestCase, TestCaseStatus, TestSuite};
84use rand::Rng;
85use regex::Regex;
86use revm::{bytecode::opcode::OpCode, context::Transaction};
87use solar::ast::{ContractKind as SolarContractKind, ItemKind};
88use std::{
89    collections::{BTreeMap, BTreeSet, HashMap},
90    fmt::Write,
91    path::{Path, PathBuf},
92    sync::{Arc, LazyLock, Mutex, mpsc::channel},
93    time::{Duration, Instant},
94};
95use tempfile::TempDir;
96use yansi::Paint;
97
98#[cfg(feature = "base")]
99use foundry_evm::core::evm::BaseEvmNetwork;
100
101#[cfg(feature = "monad")]
102use foundry_evm::core::evm::MonadEvmNetwork;
103
104#[cfg(feature = "optimism")]
105use foundry_evm::core::evm::OpEvmNetwork;
106
107mod evm_profile_server;
108mod filter;
109mod summary;
110use filter::RerunFailures;
111use summary::{TestSummaryReport, format_invariant_metrics_table};
112
113pub use filter::{FilterArgs, ProjectPathsAwareFilter, RerunFailure};
114
115const DEBUGGER_MATCHING_TESTS_DISPLAY_LIMIT: usize = 12;
116const AUTO_FUZZ_FAILURE_DIR: &str = "fuzz";
117const AUTO_CORPUS_DIR: &str = "corpus";
118
119// Loads project's figment and merges the build cli arguments into it
120foundry_config::merge_impl_figment_convert!(TestArgs, build, evm);
121
122fn validate_showmap_config(showmap: &ShowmapConfig) -> Result<()> {
123    for (kind, name) in [("approach", &showmap.approach), ("trial", &showmap.trial)] {
124        let path = Path::new(name);
125        if name.is_empty()
126            || path.is_absolute()
127            || path.components().count() != 1
128            || name.contains(['/', '\\'])
129            || matches!(name.as_str(), "." | "..")
130        {
131            bail!(
132                "invalid showmap {kind} `{name}`: expected a single file-name component without path separators"
133            );
134        }
135    }
136    Ok(())
137}
138
139/// Compiled runners for every network pass of a `forge fuzz` minimization command.
140pub(crate) struct FuzzMinimizeReplaySession {
141    filter: ProjectPathsAwareFilter,
142    passes: Vec<FuzzMinimizeReplayPass>,
143}
144
145type FuzzMinimizeReplay = Box<dyn Fn(&ProjectPathsAwareFilter, FuzzMinimizeConfig) -> Result<()>>;
146
147struct FuzzMinimizeReplayPass {
148    target_count: usize,
149    replay: FuzzMinimizeReplay,
150}
151
152impl FuzzMinimizeReplaySession {
153    pub(crate) fn replay(
154        &self,
155        sequence: Vec<BasicTxDetails>,
156        evm_edge_indices: FuzzMinimizeEdgeIndices,
157        mode: FuzzMinimizeMode,
158    ) -> Result<Vec<FuzzMinimizeObservation>> {
159        let observations = Arc::new(Mutex::new(Vec::new()));
160        let fuzz_minimize = FuzzMinimizeConfig {
161            input: sequence.into(),
162            mode,
163            evm_edge_indices,
164            observations: observations.clone(),
165        };
166        for pass in self.passes.iter().filter(|pass| pass.target_count > 0) {
167            (pass.replay)(&self.filter, fuzz_minimize.clone())?;
168        }
169        let observations = observations
170            .lock()
171            .map_err(|_| eyre::eyre!("minimize observations lock poisoned"))?
172            .clone();
173        if observations.is_empty() {
174            bail!("fuzz minimization replay produced no observation for the matched test");
175        }
176        Ok(observations)
177    }
178}
179
180fn fuzz_minimize_pass<FEN: FoundryEvmNetwork>(
181    runner: MultiContractRunner<FEN>,
182    filter: &ProjectPathsAwareFilter,
183) -> FuzzMinimizeReplayPass {
184    let target_count = count_fuzz_minimize_targets(&runner, filter);
185    let replay = move |filter: &ProjectPathsAwareFilter, fuzz_minimize| -> Result<()> {
186        let mut runner = runner.clone();
187        // Release forks that this replay creates when the replay ends.
188        runner.backend = runner.backend.clone_with_fork_scope()?;
189        runner.tcfg.fuzz_minimize = Some(fuzz_minimize);
190        for (suite, suite_result) in runner.test_collect(filter)? {
191            for (test, test_result) in suite_result.test_results {
192                if test_result.status.is_failure() {
193                    bail!(
194                        "fuzz minimization replay failed for {suite}::{test}: {}",
195                        test_result.reason.as_deref().unwrap_or("unknown error")
196                    );
197                }
198            }
199        }
200        Ok(())
201    };
202    FuzzMinimizeReplayPass { target_count, replay: Box::new(replay) }
203}
204
205fn count_fuzz_minimize_targets<FEN: FoundryEvmNetwork>(
206    runner: &MultiContractRunner<FEN>,
207    filter: &dyn TestFilter,
208) -> usize {
209    let matcher = runner.test_function_matcher();
210    runner
211        .matching_contracts(filter)
212        .map(|(id, contract)| {
213            let (fuzz, invariant) = matcher.count_fuzz_engine_targets(
214                filter,
215                id,
216                &contract.abi,
217                &runner.tcfg.multi_network,
218            );
219            fuzz + invariant
220        })
221        .sum()
222}
223
224/// Evaluates `$body` with `$fen` bound to the concrete network type selected by `$evm_opts`.
225macro_rules! dispatch_network {
226    ($evm_opts:expr, | $fen:ident | $body:expr) => {
227        match $evm_opts.networks.execution_network() {
228            #[cfg(feature = "base")]
229            NetworkVariant::Base => {
230                type $fen = BaseEvmNetwork;
231                $body
232            }
233            NetworkVariant::Tempo => {
234                type $fen = TempoEvmNetwork;
235                $body
236            }
237            #[cfg(feature = "monad")]
238            NetworkVariant::Monad => {
239                type $fen = MonadEvmNetwork;
240                $body
241            }
242            #[cfg(feature = "optimism")]
243            NetworkVariant::Optimism => {
244                type $fen = OpEvmNetwork;
245                $body
246            }
247            NetworkVariant::Ethereum => {
248                type $fen = EthEvmNetwork;
249                $body
250            }
251        }
252    };
253}
254
255/// Output format for EVM execution profiles.
256#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
257pub enum EvmProfileFormat {
258    /// Speedscope format, opens in speedscope.app.
259    #[default]
260    Speedscope,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264enum TraceOutputKind {
265    Flamegraph,
266    Flamechart,
267    EvmProfile(EvmProfileFormat),
268}
269
270impl TraceOutputKind {
271    const fn label(self) -> &'static str {
272        match self {
273            Self::Flamegraph => "flamegraph",
274            Self::Flamechart => "flamechart",
275            Self::EvmProfile(_) => "EVM profile",
276        }
277    }
278}
279
280/// CLI mirror of `foundry_evm::executors::ShowmapDomain`.
281#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, ValueEnum)]
282#[clap(rename_all = "lowercase")]
283pub enum ShowmapDomainArg {
284    #[default]
285    Evm,
286    Sancov,
287    Both,
288}
289
290impl From<ShowmapDomainArg> for ShowmapDomain {
291    fn from(d: ShowmapDomainArg) -> Self {
292        match d {
293            ShowmapDomainArg::Evm => Self::Evm,
294            ShowmapDomainArg::Sancov => Self::Sancov,
295            ShowmapDomainArg::Both => Self::Both,
296        }
297    }
298}
299
300#[derive(Clone, Debug)]
301pub(crate) struct TestExecutionOptions {
302    pub(crate) coverage: bool,
303    pub(crate) decode_internal: InternalTraceMode,
304    pub(crate) multi_network: MultiNetworkConfig,
305    pub(crate) fuzz_input: Option<FuzzFailureReplayConfig>,
306    pub(crate) replay_symbolic_artifact: Option<SymbolicArtifactReplayConfig>,
307    pub(crate) inline_config: Arc<InlineConfig>,
308    pub(crate) selected_sources: BTreeSet<PathBuf>,
309}
310
311impl TestExecutionOptions {
312    pub(crate) fn default_run(inline_config: Arc<InlineConfig>) -> Self {
313        Self {
314            coverage: false,
315            decode_internal: InternalTraceMode::None,
316            multi_network: MultiNetworkConfig::default(),
317            fuzz_input: None,
318            replay_symbolic_artifact: None,
319            inline_config,
320            selected_sources: BTreeSet::new(),
321        }
322    }
323
324    pub(crate) fn coverage(inline_config: Arc<InlineConfig>) -> Self {
325        Self { coverage: true, ..Self::default_run(inline_config) }
326    }
327}
328
329/// Config and EVM options for one network pass of a multi-network run.
330struct NetworkPass {
331    config: Config,
332    evm_opts: EvmOpts,
333    multi_network: MultiNetworkConfig,
334}
335
336/// Splits a run into the default network pass and one override pass per annotated network.
337fn network_passes(
338    config: Config,
339    evm_opts: EvmOpts,
340    override_networks: &[NetworkVariant],
341) -> (NetworkPass, Vec<NetworkPass>) {
342    let multi_network = |pass_network| MultiNetworkConfig {
343        all_override_networks: override_networks.to_vec(),
344        pass_network,
345    };
346    let override_passes = override_networks
347        .iter()
348        .map(|&network| {
349            let mut evm_opts = evm_opts.clone();
350            evm_opts.set_explicit_network(network);
351            let mut config = config.clone();
352            config.networks = evm_opts.networks;
353            NetworkPass { config, evm_opts, multi_network: multi_network(Some(network)) }
354        })
355        .collect();
356    (NetworkPass { config, evm_opts, multi_network: multi_network(None) }, override_passes)
357}
358
359struct CompiledTestProject {
360    project_root: PathBuf,
361    config: Config,
362    evm_opts: EvmOpts,
363    output: ProjectCompileOutput,
364    filter: ProjectPathsAwareFilter,
365    inline_config: Arc<InlineConfig>,
366    replay_symbolic_artifact: Option<SymbolicArtifactReplayConfig>,
367    selected_sources: BTreeSet<PathBuf>,
368    /// Keeps the brutalized copy of the project alive while its tests run.
369    _brutalized_workspace: Option<TempDir>,
370}
371
372/// Shared campaign arguments for `forge fuzz run`.
373#[derive(Clone, Debug, Parser)]
374#[command(next_help_heading = "Campaign options")]
375pub struct CampaignArgs {
376    /// Number of runs to execute for each fuzz or invariant campaign.
377    #[arg(long, value_name = "RUNS")]
378    pub runs: Option<u64>,
379
380    /// Campaign-global timeout in seconds.
381    #[arg(long, value_name = "TIMEOUT")]
382    pub timeout: Option<u32>,
383
384    /// Set seed used to generate randomness during fuzz runs.
385    #[arg(long)]
386    pub seed: Option<U256>,
387
388    /// Number of calls executed to try to break invariants in one run.
389    #[arg(long, value_name = "DEPTH")]
390    pub depth: Option<u32>,
391
392    /// Minimum sampled invariant depth when `--depth-mode random` is active.
393    #[arg(long, value_name = "DEPTH")]
394    pub min_depth: Option<u32>,
395
396    /// How invariant run depth is selected.
397    #[arg(long, value_name = "fixed|random")]
398    pub depth_mode: Option<InvariantDepthMode>,
399
400    /// Number of workers to use for invariant test campaigns, or `auto` to derive from `--jobs`.
401    #[arg(long, value_name = "WORKERS")]
402    pub workers: Option<InvariantWorkers>,
403
404    /// Directory for fuzz and invariant corpus persistence.
405    #[arg(long, value_name = "PATH", value_hint = ValueHint::DirPath)]
406    pub corpus_dir: Option<PathBuf>,
407
408    /// Percent of calldata generated from the dictionary.
409    #[arg(long, value_name = "PERCENT")]
410    pub dictionary_weight: Option<u32>,
411
412    /// Maximum dictionary addresses, or `max`.
413    #[arg(long, value_name = "N|max")]
414    pub dictionary_addresses: Option<String>,
415
416    /// Maximum dictionary values, or `max`.
417    #[arg(long, value_name = "N|max")]
418    pub dictionary_values: Option<String>,
419
420    /// Maximum dictionary literals, or `max`.
421    #[arg(long, value_name = "N|max")]
422    pub dictionary_literals: Option<String>,
423
424    /// Percent chance that coverage-guided fuzzing generates fresh input instead of mutating
425    /// corpus input.
426    #[arg(long, value_name = "PERCENT")]
427    pub corpus_random_sequence_weight: Option<u32>,
428
429    /// Percent chance that fuzzed payable calls carry non-zero msg.value.
430    #[arg(long, value_name = "PERCENT")]
431    pub payable_value_weight: Option<u32>,
432
433    /// Corpus mutation weight for splice.
434    #[arg(long, value_name = "WEIGHT")]
435    pub mutation_weight_splice: Option<u32>,
436
437    /// Corpus mutation weight for repeat.
438    #[arg(long, value_name = "WEIGHT")]
439    pub mutation_weight_repeat: Option<u32>,
440
441    /// Corpus mutation weight for interleave.
442    #[arg(long, value_name = "WEIGHT")]
443    pub mutation_weight_interleave: Option<u32>,
444
445    /// Corpus mutation weight for prefix replacement.
446    #[arg(long, value_name = "WEIGHT")]
447    pub mutation_weight_prefix: Option<u32>,
448
449    /// Corpus mutation weight for suffix replacement.
450    #[arg(long, value_name = "WEIGHT")]
451    pub mutation_weight_suffix: Option<u32>,
452
453    /// Corpus mutation weight for ABI argument mutation.
454    #[arg(long, value_name = "WEIGHT")]
455    pub mutation_weight_abi: Option<u32>,
456
457    /// Corpus mutation weight for comparison-operand mutation.
458    #[arg(long, value_name = "WEIGHT")]
459    pub mutation_weight_cmp: Option<u32>,
460
461    /// Directory for fuzz branch frontier artifacts.
462    #[arg(long, value_name = "PATH", value_hint = ValueHint::DirPath)]
463    pub frontier_dir: Option<PathBuf>,
464
465    /// Maximum number of fuzz branch frontier records to write per test.
466    #[arg(long, value_name = "COUNT")]
467    pub frontier_limit: Option<usize>,
468}
469
470/// CLI arguments for `forge test`.
471#[derive(Clone, Debug, Default, Parser)]
472#[command(next_help_heading = "Test options")]
473pub struct TestArgs {
474    /// Internal mode used by `forge fuzz` to run only fuzz and invariant tests.
475    #[arg(skip)]
476    fuzz_only: bool,
477
478    /// Internal mode used by `forge fuzz run` to default the fuzz corpus dir.
479    #[arg(skip)]
480    auto_fuzz_corpus: bool,
481
482    /// Internal showmap/replay override used by `forge fuzz replay`.
483    #[arg(skip)]
484    pub(crate) showmap_override: Option<ShowmapConfig>,
485
486    /// Internal mode used by `forge fuzz replay` to replay persisted fuzz failures.
487    #[arg(skip)]
488    pub(crate) fuzz_failure_replay: bool,
489
490    /// Internal override used by `forge fuzz run --runs` for invariant campaigns.
491    #[arg(skip)]
492    pub(crate) invariant_runs_override: Option<u64>,
493
494    /// Internal override used by `forge fuzz run --timeout` for invariant campaigns.
495    #[arg(skip)]
496    pub(crate) invariant_timeout_override: Option<u32>,
497
498    // Include global options for users of this struct.
499    #[command(flatten)]
500    pub global: GlobalArgs,
501
502    /// The contract file you want to test, it's a shortcut for --match-path.
503    #[arg(value_hint = ValueHint::FilePath)]
504    pub path: Option<GlobMatcher>,
505
506    /// Run a single test in the debugger.
507    ///
508    /// The matching test will be opened in the debugger regardless of the outcome of the test.
509    ///
510    /// If the matching test is a fuzz test, then it will open the debugger on the first failure
511    /// case. If the fuzz test does not fail, it will open the debugger on the last fuzz case.
512    #[arg(long, conflicts_with_all = ["flamegraph", "flamechart", "evm_profile", "decode_internal", "rerun"])]
513    debug: bool,
514
515    /// Generate a flamegraph for a single test. Implies `--decode-internal`.
516    ///
517    /// A flame graph is used to visualize which functions or operations within the smart contract
518    /// are consuming the most gas overall in a sorted manner.
519    #[arg(
520        long,
521        group = "trace_output",
522        conflicts_with_all = ["flamechart", "evm_profile", "json", "junit", "list"]
523    )]
524    flamegraph: bool,
525
526    /// Generate a flamechart for a single test. Implies `--decode-internal`.
527    ///
528    /// A flame chart shows the gas usage over time, illustrating when each function is
529    /// called (execution order) and how much gas it consumes at each point in the timeline.
530    #[arg(
531        long,
532        group = "trace_output",
533        conflicts_with_all = ["flamegraph", "evm_profile", "json", "junit", "list"]
534    )]
535    flamechart: bool,
536
537    /// Generate an execution profile for a single test.
538    ///
539    /// Creates a profile where each EVM call is recorded with gas consumption.
540    /// Opens the profile in speedscope.app unless `--no-open` is passed.
541    /// Implies `--decode-internal`.
542    #[arg(
543        long,
544        value_name = "FORMAT",
545        num_args = 0..=1,
546        default_missing_value = "speedscope",
547        value_enum,
548        group = "trace_output",
549        conflicts_with_all = ["flamegraph", "flamechart", "json", "junit", "list"]
550    )]
551    evm_profile: Option<EvmProfileFormat>,
552
553    /// Don't open the generated profile, flamegraph, or flamechart.
554    ///
555    /// The profile is saved to disk without starting the local viewer server.
556    #[arg(long, requires = "trace_output")]
557    no_open: bool,
558
559    #[command(flatten)]
560    tracing: TracingArgs,
561
562    /// Writes a SolDB trace and source bundle to a directory.
563    ///
564    /// Read the bundle with SolDB tools, for example:
565    /// `soldb profile --trace-file <PATH>/trace.json --contracts <PATH>/contracts.json`.
566    #[arg(
567        long,
568        requires = "debug",
569        value_hint = ValueHint::DirPath,
570        value_name = "PATH"
571    )]
572    dump: Option<PathBuf>,
573
574    /// Print a gas report.
575    #[arg(long, env = "FORGE_GAS_REPORT")]
576    gas_report: bool,
577
578    /// Check gas snapshots against previous runs.
579    #[arg(long, env = "FORGE_SNAPSHOT_CHECK")]
580    gas_snapshot_check: Option<bool>,
581
582    /// Enable/disable recording of gas snapshot results.
583    #[arg(long, env = "FORGE_SNAPSHOT_EMIT")]
584    gas_snapshot_emit: Option<bool>,
585
586    /// Exit with code 0 even if a test fails.
587    #[arg(long, env = "FORGE_ALLOW_FAILURE")]
588    allow_failure: bool,
589
590    /// Suppress successful test traces and show only traces for failures.
591    #[arg(long, short, env = "FORGE_SUPPRESS_SUCCESSFUL_TRACES", help_heading = "Trace options")]
592    suppress_successful_traces: bool,
593
594    /// Write test results as JSON to the specified file.
595    #[arg(
596        long,
597        value_name = "PATH",
598        value_hint = ValueHint::FilePath,
599        conflicts_with = "list",
600        help_heading = "Display options"
601    )]
602    json_file: Option<PathBuf>,
603
604    /// Output test results as JUnit XML report.
605    #[arg(long, conflicts_with_all = ["quiet", "json", "gas_report", "summary", "list", "show_progress"], help_heading = "Display options")]
606    pub junit: bool,
607
608    /// Stop running tests after the first failure.
609    #[arg(long)]
610    pub fail_fast: bool,
611
612    /// The Etherscan (or equivalent) API key.
613    #[arg(long, env = "ETHERSCAN_API_KEY", value_name = "KEY")]
614    etherscan_api_key: Option<String>,
615
616    /// List tests instead of running them.
617    #[arg(long, short, conflicts_with_all = ["show_progress", "decode_internal", "summary"], help_heading = "Display options")]
618    list: bool,
619
620    /// Set seed used to generate randomness during your fuzz runs.
621    #[arg(long)]
622    pub fuzz_seed: Option<U256>,
623
624    #[arg(long, env = "FOUNDRY_FUZZ_RUNS", value_name = "RUNS")]
625    pub fuzz_runs: Option<u64>,
626
627    /// Number of workers to use for invariant test campaigns, or `auto` to derive from `--jobs`.
628    #[arg(long, env = "FOUNDRY_INVARIANT_WORKERS", value_name = "WORKERS")]
629    pub invariant_workers: Option<InvariantWorkers>,
630
631    /// Run only the fuzz case at the given 1-based run index.
632    #[arg(long, env = "FOUNDRY_FUZZ_RUN", value_name = "RUN")]
633    pub fuzz_run: Option<u32>,
634
635    /// Run the fuzz case from the given worker. Requires `--fuzz-run`.
636    #[arg(long, env = "FOUNDRY_FUZZ_WORKER", value_name = "WORKER", requires = "fuzz_run")]
637    pub fuzz_worker: Option<u32>,
638
639    /// Timeout for each fuzz run in seconds.
640    #[arg(long, env = "FOUNDRY_FUZZ_TIMEOUT", value_name = "TIMEOUT")]
641    pub fuzz_timeout: Option<u64>,
642
643    /// Percent of fuzz calldata generated from the dictionary.
644    #[arg(long, env = "FOUNDRY_FUZZ_DICTIONARY_WEIGHT", value_name = "PERCENT")]
645    pub fuzz_dictionary_weight: Option<u32>,
646
647    /// Maximum fuzz dictionary addresses, or `max`.
648    #[arg(long, env = "FOUNDRY_FUZZ_MAX_FUZZ_DICTIONARY_ADDRESSES", value_name = "N|max")]
649    pub fuzz_dictionary_addresses: Option<String>,
650
651    /// Maximum fuzz dictionary values, or `max`.
652    #[arg(long, env = "FOUNDRY_FUZZ_MAX_FUZZ_DICTIONARY_VALUES", value_name = "N|max")]
653    pub fuzz_dictionary_values: Option<String>,
654
655    /// Maximum fuzz dictionary literals, or `max`.
656    #[arg(long, env = "FOUNDRY_FUZZ_MAX_FUZZ_DICTIONARY_LITERALS", value_name = "N|max")]
657    pub fuzz_dictionary_literals: Option<String>,
658
659    /// Percent chance that coverage-guided fuzzing generates fresh input instead of mutating
660    /// corpus input.
661    #[arg(long, env = "FOUNDRY_FUZZ_CORPUS_RANDOM_SEQUENCE_WEIGHT", value_name = "PERCENT")]
662    pub fuzz_corpus_random_sequence_weight: Option<u32>,
663
664    /// Directory for fuzz corpus persistence.
665    #[arg(long, env = "FOUNDRY_FUZZ_CORPUS_DIR", value_name = "PATH", value_hint = ValueHint::DirPath)]
666    pub fuzz_corpus_dir: Option<PathBuf>,
667
668    /// Directory for fuzz branch frontier artifacts.
669    #[arg(long, env = "FOUNDRY_FUZZ_FRONTIER_DIR", value_name = "PATH", value_hint = ValueHint::DirPath)]
670    pub fuzz_frontier_dir: Option<PathBuf>,
671
672    /// Maximum number of fuzz branch frontier records to write per test.
673    #[arg(long, env = "FOUNDRY_FUZZ_FRONTIER_LIMIT", value_name = "COUNT")]
674    pub fuzz_frontier_limit: Option<usize>,
675
676    /// Percent chance that fuzzed payable calls carry non-zero msg.value.
677    #[arg(long, env = "FOUNDRY_FUZZ_PAYABLE_VALUE_WEIGHT", value_name = "PERCENT")]
678    pub fuzz_payable_value_weight: Option<u32>,
679
680    /// Corpus mutation weight for splice.
681    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_SPLICE", value_name = "WEIGHT")]
682    pub fuzz_mutation_weight_splice: Option<u32>,
683
684    /// Corpus mutation weight for repeat.
685    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_REPEAT", value_name = "WEIGHT")]
686    pub fuzz_mutation_weight_repeat: Option<u32>,
687
688    /// Corpus mutation weight for interleave.
689    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_INTERLEAVE", value_name = "WEIGHT")]
690    pub fuzz_mutation_weight_interleave: Option<u32>,
691
692    /// Corpus mutation weight for prefix replacement.
693    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_PREFIX", value_name = "WEIGHT")]
694    pub fuzz_mutation_weight_prefix: Option<u32>,
695
696    /// Corpus mutation weight for suffix replacement.
697    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_SUFFIX", value_name = "WEIGHT")]
698    pub fuzz_mutation_weight_suffix: Option<u32>,
699
700    /// Corpus mutation weight for ABI argument mutation.
701    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_ABI", value_name = "WEIGHT")]
702    pub fuzz_mutation_weight_abi: Option<u32>,
703
704    /// Corpus mutation weight for comparison-operand mutation.
705    #[arg(long, env = "FOUNDRY_FUZZ_MUTATION_WEIGHT_CMP", value_name = "WEIGHT")]
706    pub fuzz_mutation_weight_cmp: Option<u32>,
707
708    /// File to rerun fuzz failures from.
709    #[arg(
710        long,
711        value_name = "PATH",
712        value_hint = ValueHint::FilePath,
713        conflicts_with_all = ["fuzz_run", "list"]
714    )]
715    pub fuzz_input_file: Option<PathBuf>,
716
717    /// Number of calls executed to try to break invariants in one run.
718    #[arg(long, env = "FOUNDRY_INVARIANT_DEPTH", value_name = "DEPTH")]
719    pub invariant_depth: Option<u32>,
720
721    /// Minimum sampled invariant depth when `--invariant-depth-mode random` is active.
722    #[arg(long, env = "FOUNDRY_INVARIANT_MIN_DEPTH", value_name = "DEPTH")]
723    pub invariant_min_depth: Option<u32>,
724
725    /// How invariant run depth is selected.
726    #[arg(long, env = "FOUNDRY_INVARIANT_DEPTH_MODE", value_name = "fixed|random")]
727    pub invariant_depth_mode: Option<InvariantDepthMode>,
728
729    /// Percent of invariant calldata/senders generated from the dictionary.
730    #[arg(long, env = "FOUNDRY_INVARIANT_DICTIONARY_WEIGHT", value_name = "PERCENT")]
731    pub invariant_dictionary_weight: Option<u32>,
732
733    /// Maximum invariant dictionary addresses, or `max`.
734    #[arg(long, env = "FOUNDRY_INVARIANT_MAX_FUZZ_DICTIONARY_ADDRESSES", value_name = "N|max")]
735    pub invariant_dictionary_addresses: Option<String>,
736
737    /// Maximum invariant dictionary values, or `max`.
738    #[arg(long, env = "FOUNDRY_INVARIANT_MAX_FUZZ_DICTIONARY_VALUES", value_name = "N|max")]
739    pub invariant_dictionary_values: Option<String>,
740
741    /// Maximum invariant dictionary literals, or `max`.
742    #[arg(long, env = "FOUNDRY_INVARIANT_MAX_FUZZ_DICTIONARY_LITERALS", value_name = "N|max")]
743    pub invariant_dictionary_literals: Option<String>,
744
745    /// Percent chance that coverage-guided invariant fuzzing injects fresh calls while extending
746    /// corpus sequences.
747    #[arg(long, env = "FOUNDRY_INVARIANT_CORPUS_RANDOM_SEQUENCE_WEIGHT", value_name = "PERCENT")]
748    pub invariant_corpus_random_sequence_weight: Option<u32>,
749
750    /// Directory for invariant corpus persistence.
751    #[arg(long, env = "FOUNDRY_INVARIANT_CORPUS_DIR", value_name = "PATH", value_hint = ValueHint::DirPath)]
752    pub invariant_corpus_dir: Option<PathBuf>,
753
754    /// Directory for invariant branch frontier artifacts.
755    #[arg(long, env = "FOUNDRY_INVARIANT_FRONTIER_DIR", value_name = "PATH", value_hint = ValueHint::DirPath)]
756    pub invariant_frontier_dir: Option<PathBuf>,
757
758    /// Maximum number of invariant branch frontier records to write per campaign.
759    #[arg(long, env = "FOUNDRY_INVARIANT_FRONTIER_LIMIT", value_name = "COUNT")]
760    pub invariant_frontier_limit: Option<usize>,
761
762    /// Percent chance that fuzzed payable invariant calls carry non-zero msg.value.
763    #[arg(long, env = "FOUNDRY_INVARIANT_PAYABLE_VALUE_WEIGHT", value_name = "PERCENT")]
764    pub invariant_payable_value_weight: Option<u32>,
765
766    /// Corpus mutation weight for splice.
767    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_SPLICE", value_name = "WEIGHT")]
768    pub invariant_mutation_weight_splice: Option<u32>,
769
770    /// Corpus mutation weight for repeat.
771    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_REPEAT", value_name = "WEIGHT")]
772    pub invariant_mutation_weight_repeat: Option<u32>,
773
774    /// Corpus mutation weight for interleave.
775    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_INTERLEAVE", value_name = "WEIGHT")]
776    pub invariant_mutation_weight_interleave: Option<u32>,
777
778    /// Corpus mutation weight for prefix replacement.
779    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_PREFIX", value_name = "WEIGHT")]
780    pub invariant_mutation_weight_prefix: Option<u32>,
781
782    /// Corpus mutation weight for suffix replacement.
783    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_SUFFIX", value_name = "WEIGHT")]
784    pub invariant_mutation_weight_suffix: Option<u32>,
785
786    /// Corpus mutation weight for ABI argument mutation.
787    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_ABI", value_name = "WEIGHT")]
788    pub invariant_mutation_weight_abi: Option<u32>,
789
790    /// Corpus mutation weight for comparison-operand mutation.
791    #[arg(long, env = "FOUNDRY_INVARIANT_MUTATION_WEIGHT_CMP", value_name = "WEIGHT")]
792    pub invariant_mutation_weight_cmp: Option<u32>,
793
794    /// Run symbolic check*/prove*/invariant*/statefulFuzz* tests.
795    #[arg(long, env = "FOUNDRY_SYMBOLIC")]
796    pub symbolic: bool,
797
798    /// Replay a durable symbolic counterexample artifact emitted by `forge test --symbolic`.
799    #[arg(
800        long,
801        value_name = "PATH",
802        value_hint = ValueHint::FilePath,
803        conflicts_with_all = [
804            "debug",
805            "flamegraph",
806            "flamechart",
807            "rerun",
808            "fuzz_input_file",
809            "showmap_out",
810            "path",
811            "test_pattern",
812            "test_pattern_inverse",
813            "contract_pattern",
814            "contract_pattern_inverse",
815            "path_pattern",
816            "no-match-path",
817        ],
818    )]
819    pub replay_symbolic_artifact: Option<PathBuf>,
820
821    /// Emit Solidity regression tests for confirmed symbolic counterexamples.
822    #[arg(long, env = "FOUNDRY_SYMBOLIC_EMIT_REGRESSION")]
823    pub emit_regression: bool,
824
825    /// File or directory for generated symbolic regression tests.
826    #[arg(
827        long,
828        env = "FOUNDRY_SYMBOLIC_REGRESSION_OUT",
829        value_name = "PATH",
830        value_hint = ValueHint::AnyPath,
831        requires = "emit_regression"
832    )]
833    pub regression_out: Option<PathBuf>,
834
835    /// Overwrite existing generated symbolic regression tests.
836    #[arg(long, env = "FOUNDRY_SYMBOLIC_REGRESSION_OVERWRITE", requires = "emit_regression")]
837    pub regression_overwrite: bool,
838
839    /// Run fuzz tests symbolically and persist non-failing concrete inputs to the fuzz corpus.
840    #[arg(long, env = "FOUNDRY_SYMBOLIC_SEED_CORPUS")]
841    pub symbolic_seed_corpus: bool,
842
843    /// Run fuzz tests symbolically using existing fuzz corpus entries as path-priority hints.
844    #[arg(long, env = "FOUNDRY_SYMBOLIC_USE_FUZZ_CORPUS")]
845    pub symbolic_use_fuzz_corpus: bool,
846
847    /// Maximum number of fuzz corpus entries to import for one symbolic test.
848    #[arg(long, env = "FOUNDRY_SYMBOLIC_CORPUS_SEED_LIMIT", value_name = "COUNT")]
849    pub symbolic_corpus_seed_limit: Option<usize>,
850
851    /// Run targeted symbolic solving from existing fuzz branch frontier artifacts.
852    #[arg(long, env = "FOUNDRY_SYMBOLIC_USE_FUZZ_FRONTIERS")]
853    pub symbolic_use_fuzz_frontiers: bool,
854
855    /// Check invariants from imported stateful fuzz frontier prefixes before flipping comparisons.
856    /// Also enables invariant frontier seeding.
857    #[arg(long, env = "FOUNDRY_SYMBOLIC_CHECK_INVARIANT_FRONTIERS")]
858    pub symbolic_check_invariant_frontiers: bool,
859
860    /// Assist invariant campaigns with one bounded live symbolic worker.
861    #[arg(long, env = "FOUNDRY_SYMBOLIC_LIVE")]
862    pub symbolic_live: bool,
863
864    /// Maximum number of imported or live branch frontiers to try per test.
865    #[arg(long, env = "FOUNDRY_SYMBOLIC_FRONTIER_LIMIT", value_name = "COUNT")]
866    pub symbolic_frontier_limit: Option<usize>,
867
868    /// Comma-separated fuzz branch frontier artifact IDs to try.
869    #[arg(long, env = "FOUNDRY_SYMBOLIC_FRONTIER_IDS", value_name = "IDS", value_delimiter = ',')]
870    pub symbolic_frontier_ids: Option<Vec<u64>>,
871
872    /// Comma-separated fuzz branch frontier comparison PCs to try.
873    #[arg(long, env = "FOUNDRY_SYMBOLIC_FRONTIER_PCS", value_name = "PCS", value_delimiter = ',')]
874    pub symbolic_frontier_pcs: Option<Vec<usize>>,
875
876    /// Comma-separated fuzz branch frontier calldata selectors to try.
877    #[arg(
878        long,
879        env = "FOUNDRY_SYMBOLIC_FRONTIER_SELECTORS",
880        value_name = "SELECTORS",
881        value_delimiter = ','
882    )]
883    pub symbolic_frontier_selectors: Option<Vec<String>>,
884
885    /// Solver executable used for symbolic tests.
886    #[arg(long, env = "FOUNDRY_SYMBOLIC_SOLVER", value_name = "PATH_OR_NAME")]
887    pub symbolic_solver: Option<String>,
888
889    /// Exact solver command used for symbolic tests.
890    #[arg(long, env = "FOUNDRY_SYMBOLIC_SOLVER_COMMAND", value_name = "COMMAND")]
891    pub symbolic_solver_command: Option<String>,
892
893    /// Comma-separated SMT solver names or commands to race in parallel for symbolic tests.
894    #[arg(
895        long,
896        env = "FOUNDRY_SYMBOLIC_SOLVER_PORTFOLIO",
897        value_delimiter = ',',
898        value_name = "SOLVER_OR_COMMAND,..."
899    )]
900    pub symbolic_solver_portfolio: Option<Vec<String>>,
901
902    /// SMT solver timeout in seconds; also bounds symbolic invariant exploration.
903    #[arg(long, env = "FOUNDRY_SYMBOLIC_TIMEOUT", value_name = "SECONDS")]
904    pub symbolic_timeout: Option<u32>,
905
906    /// Halmos-compatible symbolic loop bound.
907    #[arg(long, env = "FOUNDRY_SYMBOLIC_LOOP", value_name = "N")]
908    pub symbolic_loop: Option<u32>,
909
910    /// Halmos-compatible symbolic execution depth alias.
911    #[arg(long, env = "FOUNDRY_SYMBOLIC_DEPTH", value_name = "N")]
912    pub symbolic_depth: Option<u32>,
913
914    /// Halmos-compatible symbolic path width alias.
915    #[arg(long, env = "FOUNDRY_SYMBOLIC_WIDTH", value_name = "N")]
916    pub symbolic_width: Option<u32>,
917
918    /// Maximum number of opcodes executed along a symbolic path.
919    #[arg(long, env = "FOUNDRY_SYMBOLIC_MAX_DEPTH", value_name = "N")]
920    pub symbolic_max_depth: Option<u32>,
921
922    /// Maximum number of symbolic paths to explore per test.
923    #[arg(long, env = "FOUNDRY_SYMBOLIC_MAX_PATHS", value_name = "N")]
924    pub symbolic_max_paths: Option<u32>,
925
926    /// Maximum number of calls in a bounded symbolic invariant sequence.
927    #[arg(long, env = "FOUNDRY_SYMBOLIC_INVARIANT_DEPTH", value_name = "N")]
928    pub symbolic_invariant_depth: Option<u32>,
929
930    /// Maximum number of solver queries per symbolic test.
931    #[arg(long, env = "FOUNDRY_SYMBOLIC_MAX_SOLVER_QUERIES", value_name = "N")]
932    pub symbolic_max_solver_queries: Option<u32>,
933
934    /// Default bounded length for symbolic dynamic ABI inputs.
935    #[arg(long, env = "FOUNDRY_SYMBOLIC_DEFAULT_DYNAMIC_LENGTH", value_name = "N")]
936    pub symbolic_default_dynamic_length: Option<u32>,
937
938    /// Maximum permitted bounded length for symbolic dynamic ABI inputs.
939    #[arg(long, env = "FOUNDRY_SYMBOLIC_MAX_DYNAMIC_LENGTH", value_name = "N")]
940    pub symbolic_max_dynamic_length: Option<u32>,
941
942    /// Per-dynamic-input symbolic lengths, applied in ABI traversal order.
943    #[arg(
944        long,
945        env = "FOUNDRY_SYMBOLIC_ARRAY_LENGTHS",
946        value_delimiter = ',',
947        value_name = "N,..."
948    )]
949    pub symbolic_array_lengths: Option<Vec<u32>>,
950
951    /// Maximum symbolic calldata size in bytes.
952    #[arg(long, env = "FOUNDRY_SYMBOLIC_MAX_CALLDATA_BYTES", value_name = "N")]
953    pub symbolic_max_calldata_bytes: Option<u32>,
954
955    /// Expand symbolic external call targets over known deployed contracts.
956    #[arg(long, env = "FOUNDRY_SYMBOLIC_CALL_TARGETS")]
957    pub symbolic_call_targets: bool,
958
959    /// Dump SMT-LIB queries issued by symbolic tests.
960    #[arg(long, env = "FOUNDRY_SYMBOLIC_DUMP_SMT")]
961    pub symbolic_dump_smt: bool,
962
963    /// Symbolic storage modelling mode.
964    #[arg(
965        long,
966        env = "FOUNDRY_SYMBOLIC_STORAGE_LAYOUT",
967        value_name = "solidity|generic|zero_init",
968        value_parser = ["solidity", "generic", "zero_init"]
969    )]
970    pub symbolic_storage_layout: Option<String>,
971
972    /// Show test execution progress.
973    #[arg(long, conflicts_with_all = ["quiet", "json"], help_heading = "Display options")]
974    pub show_progress: bool,
975
976    /// Re-run recorded test failures from last run.
977    /// If no failure recorded then regular test run is performed.
978    #[arg(long)]
979    pub rerun: bool,
980
981    /// Print the given opcodes in trace output, with their gas
982    /// cost and the storage slot and value, if available.
983    ///
984    /// Accepts a comma-separated list of opcode names, e.g.
985    /// `--opcodes SLOAD,MLOAD,SSTORE`. Names are in uppercase.
986    /// Requires `-vvvvv` to render.
987    #[arg(long, value_parser = parse_opcode, value_delimiter(','), conflicts_with_all = ["json", "junit", "list", "debug"])]
988    pub opcodes: Vec<OpCode>,
989
990    /// Print test summary table.
991    #[arg(long, help_heading = "Display options")]
992    pub summary: bool,
993
994    /// Print detailed test summary table.
995    #[arg(long, help_heading = "Display options", requires = "summary")]
996    pub detailed: bool,
997
998    /// Replay the persisted corpus and emit AFL-`afl-showmap`-style coverage
999    /// files at the given output directory. Disables the regular fuzz/invariant
1000    /// campaign and skips unit tests.
1001    #[arg(
1002        long,
1003        value_name = "DIR",
1004        value_hint = ValueHint::DirPath,
1005        help_heading = "Showmap replay",
1006        conflicts_with_all = ["debug", "flamegraph", "flamechart", "evm_profile", "rerun", "fuzz_input_file", "gas_report"],
1007    )]
1008    pub showmap_out: Option<PathBuf>,
1009
1010    /// Emit one showmap file per corpus entry (default: one aggregated file per test).
1011    #[arg(long, help_heading = "Showmap replay", requires = "showmap_out")]
1012    pub showmap_per_input: bool,
1013
1014    /// Coverage domain(s) to dump.
1015    #[arg(
1016        long,
1017        value_enum,
1018        default_value_t = ShowmapDomainArg::Evm,
1019        help_heading = "Showmap replay",
1020        requires = "showmap_out",
1021    )]
1022    pub showmap_domain: ShowmapDomainArg,
1023
1024    /// Approach name (used as a subdirectory of `--showmap-out`).
1025    #[arg(
1026        long,
1027        default_value = "replay",
1028        help_heading = "Showmap replay",
1029        requires = "showmap_out"
1030    )]
1031    pub showmap_approach: String,
1032
1033    /// Trial identifier embedded in each showmap filename. Defaults to a unique
1034    /// `trial-<unix_nanos>` so reruns don't overwrite previous trials.
1035    #[arg(long, help_heading = "Showmap replay", requires = "showmap_out")]
1036    pub showmap_trial: Option<String>,
1037
1038    /// Override the corpus directory to replay (defaults to the per-test
1039    /// `corpus_dir` resolved from config).
1040    #[arg(
1041        long,
1042        value_name = "PATH",
1043        value_hint = ValueHint::DirPath,
1044        help_heading = "Showmap replay",
1045        requires = "showmap_out",
1046    )]
1047    pub showmap_corpus_dir: Option<PathBuf>,
1048
1049    /// Decode the storage layouts of contracts outside the local project in state diffs, by
1050    /// compiling the verified source a block explorer has for them.
1051    #[arg(long)]
1052    pub decode_external_storage: bool,
1053
1054    #[command(flatten)]
1055    filter: FilterArgs,
1056
1057    #[command(flatten)]
1058    evm: EvmArgs,
1059
1060    #[command(flatten)]
1061    pub build: BuildOpts,
1062
1063    #[command(flatten)]
1064    pub watch: WatchArgs,
1065
1066    /// Enable mutation testing.
1067    /// If passed with file paths, only those files will be tested.
1068    #[arg(long, num_args(0..), value_name = "PATH")]
1069    pub mutate: Option<Vec<PathBuf>>,
1070
1071    /// Specify which files to mutate with glob pattern matching.
1072    ///
1073    /// Mutually exclusive with passing explicit paths to `--mutate`; either
1074    /// supply paths to `--mutate` or use this glob filter, not both.
1075    #[arg(long, value_name = "PATTERN", requires = "mutate", conflicts_with = "mutate_contract")]
1076    pub mutate_path: Option<GlobMatcher>,
1077
1078    /// Only mutate contracts whose name matches the specified regex pattern.
1079    ///
1080    /// Mutually exclusive with `--mutate-path`.
1081    #[arg(long, value_name = "REGEX", requires = "mutate")]
1082    pub mutate_contract: Option<regex::Regex>,
1083
1084    /// Number of parallel workers for mutation testing.
1085    /// Defaults to the number of CPU cores.
1086    #[arg(long, value_name = "JOBS", requires = "mutate")]
1087    pub mutation_jobs: Option<usize>,
1088
1089    /// Best-effort per-mutant wall-clock timeout in seconds. Mutants that
1090    /// exceed it are recorded as "timed out" and cleanup continues in the
1091    /// background with bounded pending workers.
1092    ///
1093    /// Analogous to `--invariant-timeout` for invariant campaigns.
1094    #[arg(long, value_name = "TIMEOUT", requires = "mutate")]
1095    pub mutation_timeout: Option<u32>,
1096
1097    /// Override optimizer runs for mutation testing compile-and-test runs.
1098    #[arg(long, value_name = "RUNS", requires = "mutate")]
1099    pub mutation_optimizer_runs: Option<u32>,
1100
1101    /// Override via-ir for mutation testing compile-and-test runs.
1102    #[arg(long, default_missing_value = "true", num_args = 0..=1, requires = "mutate")]
1103    pub mutation_via_ir: Option<bool>,
1104
1105    /// Enable brutalization mode.
1106    ///
1107    /// Catches latent bugs that normal tests miss because the EVM initializes
1108    /// memory to zero and registers to clean values. Applies source-level
1109    /// sanitizers before compiling:
1110    ///
1111    /// - Dirties unused bits in sub-256-bit type casts (address, uint8, bytes4, etc.) to catch
1112    ///   assembly code that assumes clean upper bits when using legacy codegen. Via-IR may clean
1113    ///   these bits before inline assembly observes them.
1114    /// - Fills scratch space (0x00-0x3f) and memory beyond the free memory pointer with junk to
1115    ///   catch uninitialized memory reads
1116    /// - Misaligns the free memory pointer to catch word-alignment assumptions
1117    ///
1118    /// If `forge test` passes but `forge test --brutalize` fails, the code has
1119    /// a robustness issue that could manifest when called in a different context.
1120    // TODO: evaluate if we can relax the conflict with replay_symbolic_artifact
1121    #[arg(long, conflicts_with_all = ["mutate", "replay_symbolic_artifact"])]
1122    pub brutalize: bool,
1123
1124    /// Make every cheatcode that opens a network connection fail. `forge properties` sets it for
1125    /// generated tests.
1126    #[arg(long, hide = true)]
1127    pub no_network: bool,
1128
1129    /// Let inline config only lower fuzz and invariant runs, depth, and rejects and change a few
1130    /// settings that steer them. `forge properties` and `forge exploit` set it for generated
1131    /// tests.
1132    #[arg(long, hide = true)]
1133    pub restrict_inline_config: bool,
1134}
1135
1136impl TestArgs {
1137    pub async fn run(mut self) -> Result<TestOutcome> {
1138        trace!(target: "forge::test", "executing test command");
1139        self.compile_and_run().await
1140    }
1141
1142    pub(crate) fn ensure_mutation_mode_compatible(&self, coverage: bool) -> Result<()> {
1143        if self.mutate.is_none() {
1144            return Ok(());
1145        }
1146        // Mutation testing has bespoke orchestration that is not compatible with these modes.
1147        // Run this before compiling when the caller owns the build step so project errors do not
1148        // mask CLI conflicts.
1149        let conflicts = enabled_flags([
1150            (self.list, "--list"),
1151            (self.debug, "--debug"),
1152            (self.flamegraph, "--flamegraph"),
1153            (self.flamechart, "--flamechart"),
1154            (self.evm_profile.is_some(), "--evm-profile"),
1155            (self.junit, "--junit"),
1156            (self.json_file.is_some(), "--json-file"),
1157            (coverage, "coverage"),
1158            (self.showmap_out.is_some(), "--showmap-out"),
1159            (self.replay_symbolic_artifact.is_some(), "--replay-symbolic-artifact"),
1160        ]);
1161        if !conflicts.is_empty() {
1162            bail!(
1163                "`--mutate` cannot be combined with: {}. Re-run without those flags to use \
1164                 mutation testing.",
1165                conflicts.join(", ")
1166            );
1167        }
1168        Ok(())
1169    }
1170
1171    pub(crate) fn ensure_coverage_mode_compatible(&self) -> Result<()> {
1172        self.ensure_mutation_mode_compatible(true)?;
1173        let conflicts = enabled_flags([
1174            (shell::is_json(), "--json"),
1175            (self.junit, "--junit"),
1176            (self.json_file.is_some(), "--json-file"),
1177            (self.list, "--list"),
1178            (self.debug, "--debug"),
1179            (self.flamegraph, "--flamegraph"),
1180            (self.flamechart, "--flamechart"),
1181            (self.evm_profile.is_some(), "--evm-profile"),
1182            (self.showmap_out.is_some(), "--showmap-out"),
1183            (self.brutalize, "--brutalize"),
1184            (self.replay_symbolic_artifact.is_some(), "--replay-symbolic-artifact"),
1185        ]);
1186        if !conflicts.is_empty() {
1187            bail!(
1188                "`forge coverage` cannot be combined with: {}. Use `--report lcov` for an \
1189                 interoperable coverage report or `--report attribution` for per-test JSON \
1190                attribution.",
1191                conflicts.join(", ")
1192            );
1193        }
1194        Ok(())
1195    }
1196
1197    /// Builds a `ShowmapConfig` from the showmap CLI flags, if `--showmap-out` is set.
1198    fn showmap_config(&self) -> Result<Option<ShowmapConfig>> {
1199        let showmap = match (&self.showmap_override, &self.showmap_out) {
1200            (Some(showmap), _) => showmap.clone(),
1201            (None, Some(out_dir)) => ShowmapConfig {
1202                out_dir: out_dir.clone(),
1203                approach: self.showmap_approach.clone(),
1204                // Default trial id uses nanosecond precision so back-to-back invocations
1205                // don't collide and overwrite each other's output files.
1206                trial: self.showmap_trial.clone().unwrap_or_else(|| {
1207                    let ns = std::time::SystemTime::now()
1208                        .duration_since(std::time::UNIX_EPOCH)
1209                        .map(|d| d.as_nanos())
1210                        .unwrap_or(0);
1211                    format!("trial-{ns}")
1212                }),
1213                per_input: self.showmap_per_input,
1214                domain: self.showmap_domain.into(),
1215                corpus_dir: self.showmap_corpus_dir.clone(),
1216                emit_files: true,
1217            },
1218            (None, None) => return Ok(None),
1219        };
1220        validate_showmap_config(&showmap)?;
1221        Ok(Some(showmap))
1222    }
1223
1224    /// Restricts this test invocation to fuzz and invariant tests.
1225    pub(crate) const fn enable_fuzz_only(&mut self) {
1226        self.fuzz_only = true;
1227    }
1228
1229    /// Restricts this test invocation to fuzz and invariant tests and enables a default fuzz corpus
1230    /// dir after user config is loaded.
1231    pub(crate) const fn enable_fuzz_only_with_auto_fuzz_corpus(&mut self) {
1232        self.fuzz_only = true;
1233        self.auto_fuzz_corpus = true;
1234    }
1235
1236    fn apply_test_config_overrides(&self, config: &mut Config) {
1237        if self.auto_fuzz_corpus && config.fuzz.corpus.corpus_dir.is_none() {
1238            config.fuzz.corpus.corpus_dir = Some(match &config.fuzz.failure_persist_dir {
1239                Some(root) => root.join(AUTO_CORPUS_DIR),
1240                None => config.cache_path.join(AUTO_FUZZ_FAILURE_DIR).join(AUTO_CORPUS_DIR),
1241            });
1242        }
1243        if self.debug {
1244            if !config.extra_output.contains(&ContractOutputSelection::StorageLayout) {
1245                config.extra_output.push(ContractOutputSelection::StorageLayout);
1246            }
1247            // Full build infos keep the sources the compiler saw, which dynamic test linking
1248            // rewrites in test files.
1249            if let Err(error) = config.enable_debug_build_info() {
1250                let _ = sh_warn!(
1251                    "the debugger may show source files that differ from the compiled ones: {error:#}"
1252                );
1253            }
1254        }
1255    }
1256
1257    /// Disables gas report sampling unless a gas report is requested, in which case isolation is
1258    /// enabled for more correct gas accounting.
1259    const fn apply_gas_report_overrides(&self, config: &mut Config, evm_opts: &mut EvmOpts) {
1260        if self.gas_report {
1261            evm_opts.isolate = true;
1262        } else {
1263            config.fuzz.gas_report_samples = 0;
1264            config.invariant.gas_report_samples = 0;
1265        }
1266    }
1267
1268    /// Overrides showmap config for callers that reuse replay mode without the
1269    /// `forge test --showmap-*` CLI flags.
1270    pub(crate) fn set_showmap_override(&mut self, showmap: ShowmapConfig) {
1271        self.showmap_override = Some(showmap);
1272    }
1273
1274    /// Sets replay-critical options for internal fuzz minimizer callers.
1275    pub(crate) fn set_fuzz_minimize_replay_options(
1276        &mut self,
1277        global: GlobalArgs,
1278        evm: EvmArgs,
1279        build: BuildOpts,
1280        filter: FilterArgs,
1281    ) {
1282        self.global = global;
1283        self.evm = evm;
1284        self.build = build;
1285        self.filter = filter;
1286    }
1287
1288    /// Replays persisted fuzz failures without running a new fuzz campaign.
1289    pub(crate) const fn enable_fuzz_failure_replay(&mut self) {
1290        self.fuzz_failure_replay = true;
1291    }
1292
1293    fn warn_unsupported_engine_flags(
1294        &self,
1295        output: &ProjectCompileOutput,
1296        config: &Config,
1297        inline_config: &InlineConfig,
1298        filter: &ProjectPathsAwareFilter,
1299        multi_network: &MultiNetworkConfig,
1300    ) -> Result<()> {
1301        if !self.fuzz_only {
1302            return Ok(());
1303        }
1304        let matcher = TestFunctionMatcher::new(config, inline_config, None);
1305        let (mut fuzz, mut invariant) = (0, 0);
1306        for (id, _, abi) in matching_test_contracts(output, config, &matcher, filter) {
1307            let (f, i) = matcher.count_fuzz_engine_targets(filter, &id, abi, multi_network);
1308            fuzz += f;
1309            invariant += i;
1310        }
1311        let unused: &[(bool, &str, &str)] = if fuzz == 0 && invariant > 0 {
1312            &[
1313                (
1314                    self.fuzz_frontier_dir.is_some() && self.invariant_frontier_dir.is_none(),
1315                    "--frontier-dir",
1316                    "fuzz",
1317                ),
1318                (
1319                    self.fuzz_frontier_limit.is_some() && self.invariant_frontier_limit.is_none(),
1320                    "--frontier-limit",
1321                    "fuzz",
1322                ),
1323                (self.fuzz_run.is_some(), "--fuzz-run", "fuzz"),
1324            ]
1325        } else if invariant == 0 && fuzz > 0 {
1326            &[
1327                (self.invariant_depth.is_some(), "--depth", "invariant"),
1328                (self.invariant_min_depth.is_some(), "--min-depth", "invariant"),
1329                (self.invariant_depth_mode.is_some(), "--depth-mode", "invariant"),
1330                (self.invariant_workers.is_some(), "--workers", "invariant"),
1331            ]
1332        } else {
1333            &[]
1334        };
1335        for (set, flag, engine) in unused {
1336            if *set {
1337                sh_warn!(
1338                    "`{flag}` only applies to {engine} tests; no matched {engine} tests were found."
1339                )?;
1340            }
1341        }
1342        Ok(())
1343    }
1344
1345    /// Builds the delegated `forge test` invocation for `forge fuzz run`.
1346    pub(crate) fn from_fuzz_run(args: FuzzRunArgs) -> Self {
1347        let campaign = args.campaign;
1348        Self {
1349            fuzz_only: true,
1350            global: args.global,
1351            path: args.path,
1352            gas_report: args.gas_report,
1353            allow_failure: args.allow_failure,
1354            junit: args.junit,
1355            fail_fast: args.fail_fast,
1356            etherscan_api_key: args.etherscan_api_key,
1357            list: args.list,
1358            fuzz_input_file: args.fuzz_input_file,
1359            show_progress: args.show_progress,
1360            rerun: args.rerun,
1361            showmap_out: args.showmap_out,
1362            showmap_per_input: args.showmap_per_input,
1363            showmap_domain: args.showmap_domain,
1364            showmap_approach: args.showmap_approach,
1365            showmap_trial: args.showmap_trial,
1366            showmap_corpus_dir: args.showmap_corpus_dir,
1367            filter: args.filter,
1368            evm: args.evm,
1369            build: args.build,
1370            fuzz_seed: campaign.seed,
1371            fuzz_runs: campaign.runs,
1372            invariant_runs_override: campaign.runs,
1373            fuzz_timeout: campaign.timeout.map(u64::from),
1374            invariant_timeout_override: campaign.timeout,
1375            fuzz_dictionary_weight: campaign.dictionary_weight,
1376            invariant_dictionary_weight: campaign.dictionary_weight,
1377            fuzz_dictionary_addresses: campaign.dictionary_addresses.clone(),
1378            invariant_dictionary_addresses: campaign.dictionary_addresses,
1379            fuzz_dictionary_values: campaign.dictionary_values.clone(),
1380            invariant_dictionary_values: campaign.dictionary_values,
1381            fuzz_dictionary_literals: campaign.dictionary_literals.clone(),
1382            invariant_dictionary_literals: campaign.dictionary_literals,
1383            fuzz_corpus_random_sequence_weight: campaign.corpus_random_sequence_weight,
1384            invariant_corpus_random_sequence_weight: campaign.corpus_random_sequence_weight,
1385            fuzz_corpus_dir: campaign.corpus_dir.clone(),
1386            invariant_corpus_dir: campaign.corpus_dir,
1387            fuzz_payable_value_weight: campaign.payable_value_weight,
1388            invariant_payable_value_weight: campaign.payable_value_weight,
1389            fuzz_mutation_weight_splice: campaign.mutation_weight_splice,
1390            invariant_mutation_weight_splice: campaign.mutation_weight_splice,
1391            fuzz_mutation_weight_repeat: campaign.mutation_weight_repeat,
1392            invariant_mutation_weight_repeat: campaign.mutation_weight_repeat,
1393            fuzz_mutation_weight_interleave: campaign.mutation_weight_interleave,
1394            invariant_mutation_weight_interleave: campaign.mutation_weight_interleave,
1395            fuzz_mutation_weight_prefix: campaign.mutation_weight_prefix,
1396            invariant_mutation_weight_prefix: campaign.mutation_weight_prefix,
1397            fuzz_mutation_weight_suffix: campaign.mutation_weight_suffix,
1398            invariant_mutation_weight_suffix: campaign.mutation_weight_suffix,
1399            fuzz_mutation_weight_abi: campaign.mutation_weight_abi,
1400            invariant_mutation_weight_abi: campaign.mutation_weight_abi,
1401            fuzz_mutation_weight_cmp: campaign.mutation_weight_cmp,
1402            invariant_mutation_weight_cmp: campaign.mutation_weight_cmp,
1403            fuzz_frontier_dir: campaign.frontier_dir.clone(),
1404            invariant_frontier_dir: campaign.frontier_dir,
1405            fuzz_frontier_limit: campaign.frontier_limit,
1406            invariant_frontier_limit: campaign.frontier_limit,
1407            invariant_depth: campaign.depth,
1408            invariant_min_depth: campaign.min_depth,
1409            invariant_depth_mode: campaign.depth_mode,
1410            invariant_workers: campaign.workers,
1411            ..Self::default()
1412        }
1413    }
1414
1415    fn load_symbolic_artifact_replay(&self) -> Result<Option<SymbolicArtifactReplayConfig>> {
1416        let Some(path) = &self.replay_symbolic_artifact else {
1417            return Ok(None);
1418        };
1419        if !self.filter.is_empty() || self.path.is_some() {
1420            bail!(
1421                "symbolic artifact mode cannot be combined with test selection filters; \
1422                 the artifact selects its original target"
1423            );
1424        }
1425
1426        let display = path.display();
1427        let value = fs::read_json_file::<serde_json::Value>(path)
1428            .wrap_err(format!("failed to read symbolic counterexample artifact {display}"))?;
1429        let schema_version =
1430            value.get("schema_version").and_then(serde_json::Value::as_u64).ok_or_else(|| {
1431                eyre::eyre!(
1432                    "symbolic counterexample artifact {display} is missing numeric schema_version"
1433                )
1434            })?;
1435        if schema_version != 1 {
1436            bail!(
1437                "unsupported symbolic counterexample artifact schema version {schema_version} in {display}"
1438            );
1439        }
1440        let schema = value.get("schema").and_then(serde_json::Value::as_str).ok_or_else(|| {
1441            eyre::eyre!("symbolic counterexample artifact {display} is missing string schema")
1442        })?;
1443        if schema != SYMBOLIC_COUNTEREXAMPLE_ARTIFACT_SCHEMA {
1444            bail!("unsupported symbolic counterexample artifact schema `{schema}` in {display}");
1445        }
1446        let artifact = serde_json::from_value::<SymbolicCounterexampleArtifact>(value)
1447            .wrap_err(format!("failed to parse symbolic counterexample artifact {display}"))?;
1448        if artifact.calls.is_empty() {
1449            bail!("symbolic counterexample artifact {display} has no calls");
1450        }
1451        if artifact.replay.status != SymbolicReplayStatus::Confirmed {
1452            bail!(
1453                "symbolic counterexample artifact {display} replay status must be confirmed, got {:?}",
1454                artifact.replay.status,
1455            );
1456        }
1457        let contract = &artifact.test.contract;
1458        if !matches!(contract.rsplit_once(':'), Some((p, n)) if !p.is_empty() && !n.is_empty()) {
1459            bail!(
1460                "symbolic counterexample artifact {display} test.contract must be `path:Contract`, got `{contract}`"
1461            );
1462        }
1463        Ok(Some(SymbolicArtifactReplayConfig { artifact, path: path.clone() }))
1464    }
1465
1466    fn load_fuzz_input(
1467        &self,
1468        output: &ProjectCompileOutput,
1469        config: &Config,
1470        inline_config: &InlineConfig,
1471        filter: &ProjectPathsAwareFilter,
1472    ) -> Result<Option<FuzzFailureReplayConfig>> {
1473        let Some(path) = &self.fuzz_input_file else {
1474            return Ok(None);
1475        };
1476        let failure = fs::read_json_file::<BaseCounterExample>(path)?;
1477        let Some(selector) = failure.calldata.get(..4) else {
1478            bail!(
1479                "fuzz input file {} contains calldata shorter than a 4-byte selector",
1480                path.display()
1481            );
1482        };
1483        let targets =
1484            matching_fuzz_replay_targets(output, config, inline_config, filter, selector)?;
1485        let [(contract, test)] = targets.as_slice() else {
1486            if targets.is_empty() {
1487                bail!(
1488                    "fuzz input file {} does not match any selected stateless fuzz test",
1489                    path.display()
1490                );
1491            }
1492            bail!(
1493                "fuzz input file {} matches {} selected stateless fuzz tests; replay requires exactly one target",
1494                path.display(),
1495                targets.len()
1496            );
1497        };
1498        Ok(Some(FuzzFailureReplayConfig {
1499            failure: Arc::new(failure),
1500            contract: contract.clone(),
1501            test: test.clone(),
1502        }))
1503    }
1504
1505    /// Discovers test ABIs before contract and function filters select compilation roots.
1506    fn compile_test_abis(
1507        &self,
1508        config: &Config,
1509        test_filter: &ProjectPathsAwareFilter,
1510    ) -> Result<(BTreeSet<PathBuf>, ProjectCompileOutput)> {
1511        let mut project = config.create_project(config.cache, true)?;
1512        let sources = source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS)
1513            .chain(
1514                // Preserve path-filter behavior for conventional test files while still
1515                // scanning non-test fixtures under the test root.
1516                source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS)
1517                    .filter(|path| !path.is_sol_test() || test_filter.matches_path(path)),
1518            )
1519            .collect::<BTreeSet<_>>();
1520        // ABI discovery does not need dynamic linking, whose job-specific cache prevents
1521        // incremental ABI compilation after edits.
1522        let output = compile_abi_project_cached(
1523            &mut project,
1524            ProjectCompiler::new()
1525                .external_compilers(config)
1526                .files(sources.iter().cloned())
1527                .source_order_fallback(
1528                    source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS).chain(
1529                        source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS),
1530                    ),
1531                )
1532                .quiet(true),
1533        )?;
1534        if output.has_compiler_errors() {
1535            sh_println!("{output}")?;
1536            bail!("Compilation failed");
1537        }
1538
1539        Ok((sources, output))
1540    }
1541
1542    /// Returns a list of files that need to be compiled in order to run all the tests that match
1543    /// the given filter, and the inline config parsed from the ABI-only compilation when one was
1544    /// needed.
1545    ///
1546    /// For filtered runs, this includes all configured source roots, non-test fixture roots, and
1547    /// runnable tests that match the filter. Imported dependencies remain attached to those roots
1548    /// so compiler profiles and restrictions apply to the complete source graph.
1549    #[instrument(target = "forge::test", skip_all)]
1550    fn get_sources_to_compile(
1551        &self,
1552        config: &Config,
1553        test_filter: &ProjectPathsAwareFilter,
1554        symbolic_artifact_replay: Option<&SymbolicArtifactReplayConfig>,
1555    ) -> Result<(BTreeSet<PathBuf>, Option<Arc<InlineConfig>>)> {
1556        let src_files = || source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS);
1557        let test_files = || source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS);
1558
1559        // An empty filter doesn't filter out anything.
1560        // We can still optimize slightly by excluding scripts.
1561        if test_filter.is_empty() {
1562            return Ok((src_files().chain(test_files()).collect(), None));
1563        }
1564
1565        let (sources, output) = self.compile_test_abis(config, test_filter)?;
1566
1567        let inline_config = Arc::new(InlineConfig::new_parsed(&output, config)?);
1568        let test_matcher =
1569            TestFunctionMatcher::new(config, &inline_config, symbolic_artifact_replay);
1570        let paths = config.project_paths::<MultiCompilerLanguage>();
1571        let empty_filter = EmptyTestFilter::default();
1572        let filter_args = test_filter.args();
1573        let has_contract_or_test_filter = filter_args.test_pattern.is_some()
1574            || filter_args.test_pattern_inverse.is_some()
1575            || filter_args.contract_pattern.is_some()
1576            || filter_args.contract_pattern_inverse.is_some();
1577
1578        // `MultiContractRunner::build` strips the root prefix from artifact source paths so the
1579        // identifiers it constructs are project-relative. Match that here for the filter check
1580        // (notably for the `--rerun` failure list, which is persisted relative) but return the
1581        // original absolute source paths so downstream compilation can locate them.
1582        let files = output
1583            .artifact_ids()
1584            .filter_map(|(id, artifact)| artifact.abi.as_ref().map(|abi| (id, abi)))
1585            // Imported dependencies must remain attached to their roots so compilation restrictions
1586            // apply to the entire source graph instead of compiling dependencies with default
1587            // settings.
1588            .filter(|(id, _)| sources.contains(&id.source))
1589            .filter(|(id, abi)| {
1590                if id.source.starts_with(&paths.sources) {
1591                    return true;
1592                }
1593                if paths.is_script(&id.source) && !paths.is_test(&id.source) {
1594                    return false;
1595                }
1596                let stripped = id.clone().with_stripped_file_prefixes(&config.root);
1597                // ABI-only compilation can omit test functions with invalid bodies, so preserve the
1598                // existing filter behavior for conventional test files instead of treating them as
1599                // fixtures.
1600                if stripped.source.is_sol_test() {
1601                    return if has_contract_or_test_filter {
1602                        test_matcher.matches_contract(test_filter, &stripped, abi)
1603                    } else {
1604                        test_filter.matches_path(&stripped.source)
1605                    };
1606                }
1607                !test_matcher.matches_contract(&empty_filter, &stripped, abi)
1608                    || test_matcher.matches_contract(test_filter, &stripped, abi)
1609            })
1610            .map(|(id, _)| id.source)
1611            .collect();
1612        Ok((files, Some(inline_config)))
1613    }
1614
1615    /// Executes all the tests in the project.
1616    ///
1617    /// This will trigger the build process first. On success all test contracts that match the
1618    /// configured filter will be executed
1619    ///
1620    /// Returns the test results for all matching tests.
1621    pub async fn compile_and_run(&mut self) -> Result<TestOutcome> {
1622        self.ensure_mutation_mode_compatible(false)?;
1623        if let Some(dir) = &self.dump {
1624            ensure_dump_dir(dir)?;
1625        }
1626        let compiled = self.compile_project().await?;
1627        self.run_tests(
1628            &compiled.project_root,
1629            compiled.config,
1630            compiled.evm_opts,
1631            &compiled.output,
1632            &compiled.filter,
1633            TestExecutionOptions {
1634                replay_symbolic_artifact: compiled.replay_symbolic_artifact,
1635                selected_sources: compiled.selected_sources,
1636                ..TestExecutionOptions::default_run(compiled.inline_config)
1637            },
1638        )
1639        .await
1640    }
1641
1642    /// Copies the project into a temporary workspace, brutalizes its sources and rebases `config`
1643    /// onto that workspace.
1644    fn brutalize_workspace(&self, config: &mut Config) -> Result<TempDir> {
1645        let silent = shell::is_json();
1646        let temp_dir = TempDir::with_prefix("forge_brutalize_")?;
1647        let temp_path = temp_dir.path();
1648
1649        if config.via_ir && !silent {
1650            sh_warn!(
1651                "--brutalize value cast dirty-bits checks are ineffective with via-IR; memory and free-memory-pointer checks still apply"
1652            )?;
1653        }
1654        if !silent {
1655            sh_status!("Brutalizing source files...")?;
1656        }
1657        workspace::copy_project(config, temp_path)?;
1658        let count = brutalizer::brutalize_project(config, temp_path)?;
1659        if !silent {
1660            sh_status!("Brutalized {count} source files, compiling from temp workspace...")?;
1661        }
1662
1663        let test_failures_file = config.test_failures_file.clone();
1664        *config = workspace::rebase_config_paths(config, temp_path).sanitized();
1665        config.test_failures_file = test_failures_file;
1666        Ok(temp_dir)
1667    }
1668
1669    async fn compile_project(&mut self) -> Result<CompiledTestProject> {
1670        // Merge all configs.
1671        let (mut config, mut evm_opts) = self.load_config_and_evm_opts()?;
1672        evm_opts.no_network = self.no_network;
1673
1674        self.install_missing_dependencies(&mut config)?;
1675        // After the install, which can reload the config.
1676        config.restrict_inline_config = self.restrict_inline_config;
1677        let brutalized_workspace =
1678            if self.brutalize { Some(self.brutalize_workspace(&mut config)?) } else { None };
1679        let should_mutate = self.mutate.is_some();
1680        if should_mutate {
1681            // Force dyn test linking and cache usage for mutation testing after any config reload.
1682            config.dynamic_test_linking = true;
1683            config.cache = true;
1684            apply_mutation_compiler_overrides(&mut config);
1685        }
1686        self.apply_test_config_overrides(&mut config);
1687
1688        // Set up the project.
1689        let project = config.project()?;
1690        let project_root = project.paths.root.clone();
1691
1692        let replay_symbolic_artifact = self.load_symbolic_artifact_replay()?;
1693        let mut filter = self.filter(&config)?;
1694        if let Some(replay) = &replay_symbolic_artifact {
1695            let filter_args = filter.args_mut();
1696            filter_args.test_pattern_inverse = None;
1697            filter_args.contract_pattern_inverse = None;
1698            filter_args.path_pattern_inverse = None;
1699            let contract = replay.artifact.test.contract.as_str();
1700            let (path, contract) = contract.rsplit_once(':').unwrap_or(("", contract));
1701            filter_args.test_pattern =
1702                Some(Regex::new(&format!("^{}$", regex::escape(&replay.artifact.test.test)))?);
1703            filter_args.contract_pattern =
1704                Some(Regex::new(&format!("^{}$", regex::escape(contract)))?);
1705            if !path.is_empty() {
1706                filter_args.path_pattern = Some(globset::escape(path).parse::<GlobMatcher>()?);
1707            }
1708        }
1709        trace!(target: "forge::test", ?filter, "using filter");
1710
1711        let compiler = ProjectCompiler::new()
1712            .allow_linked_libraries(config.allow_linked_libraries || self.list)
1713            .external_compilers(&config)
1714            .dynamic_test_linking(config.dynamic_test_linking)
1715            .quiet(shell::is_json() || self.junit);
1716        let (output, selected_sources, inline_config) = if self.list {
1717            let compiler = compiler.external_artifacts(false);
1718            // Only the ABI is needed to list tests, so skip the full compile when possible.
1719            let compiler = if filter.args().path_pattern.is_some()
1720                && config.extra_output.is_empty()
1721                && config.extra_output_files.is_empty()
1722                && !config.build_info
1723            {
1724                let files = project
1725                    .paths
1726                    .input_files_iter()
1727                    .filter(|path| filter.matches_path(path))
1728                    .collect::<Vec<_>>();
1729                if files.is_empty() { compiler } else { compiler.files(files) }
1730            } else {
1731                compiler
1732            };
1733            // Listing must not replace full artifacts with ABI-only ones, which later cached
1734            // builds would treat as fresh.
1735            let mut project = config.create_project(config.cache, true)?;
1736            (compile_abi_project_cached(&mut project, compiler)?, BTreeSet::new(), None)
1737        } else {
1738            let (files, inline_config) =
1739                self.get_sources_to_compile(&config, &filter, replay_symbolic_artifact.as_ref())?;
1740            let compiler = if filter.is_empty() {
1741                compiler
1742            } else {
1743                compiler.source_order_fallback(
1744                    source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS).chain(
1745                        source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS),
1746                    ),
1747                )
1748            };
1749            let output = compiler.files(files.clone()).compile(&project);
1750            let output = if should_mutate {
1751                output.wrap_err(
1752                    "Mutation testing compiler profile failed to compile before applying mutations",
1753                )?
1754            } else {
1755                output?
1756            };
1757            (output, files, inline_config)
1758        };
1759        let inline_config = match inline_config {
1760            Some(inline_config) => inline_config,
1761            None => Arc::new(InlineConfig::new_parsed(&output, &config)?),
1762        };
1763
1764        Ok(CompiledTestProject {
1765            project_root,
1766            config,
1767            evm_opts,
1768            output,
1769            filter,
1770            inline_config,
1771            replay_symbolic_artifact,
1772            selected_sources,
1773            _brutalized_workspace: brutalized_workspace,
1774        })
1775    }
1776
1777    pub(crate) async fn prepare_fuzz_minimize_replay(
1778        &mut self,
1779        corpus_dir: &Path,
1780    ) -> Result<FuzzMinimizeReplaySession> {
1781        let CompiledTestProject { mut config, mut evm_opts, output, filter, inline_config, .. } =
1782            self.compile_project().await?;
1783
1784        if config.fuzz.run == Some(0) {
1785            bail!("`fuzz.run` must be greater than 0");
1786        }
1787        self.apply_gas_report_overrides(&mut config, &mut evm_opts);
1788        for corpus in [&mut config.fuzz.corpus, &mut config.invariant.corpus] {
1789            corpus.corpus_dir.get_or_insert_with(|| corpus_dir.to_path_buf());
1790        }
1791        config.fuzz.seed = config.fuzz.seed.or(Some(U256::ZERO));
1792
1793        evm_opts.infer_network_from_fork().await?;
1794        config.networks = evm_opts.networks;
1795
1796        let override_networks = inline_config.referenced_override_networks(&config.profile);
1797        let (default_pass, override_passes) = network_passes(config, evm_opts, &override_networks);
1798        let mut passes = Vec::new();
1799        for NetworkPass { config, evm_opts, multi_network } in
1800            std::iter::once(default_pass).chain(override_passes)
1801        {
1802            let execution = TestExecutionOptions {
1803                multi_network,
1804                ..TestExecutionOptions::default_run(inline_config.clone())
1805            };
1806            let config = Arc::new(config);
1807            passes.push(dispatch_network!(&evm_opts, |Net| {
1808                let backend = Backend::<Net>::spawn(evm_opts.get_fork(
1809                    &config,
1810                    evm_opts.env.chain_id.unwrap_or_default(),
1811                    None,
1812                ))?;
1813                let runner = self
1814                    .build_runner::<Net>(
1815                        config,
1816                        evm_opts,
1817                        &output,
1818                        execution,
1819                        backend,
1820                        ExecutorBuilder::<Net>::new(),
1821                    )
1822                    .await?;
1823                fuzz_minimize_pass(runner, &filter)
1824            }));
1825        }
1826
1827        if passes.iter().all(|pass| pass.target_count == 0) {
1828            bail!("fuzz minimization requires at least one matched fuzz or invariant test");
1829        }
1830        Ok(FuzzMinimizeReplaySession { filter, passes })
1831    }
1832
1833    /// Executes all the tests in the project.
1834    ///
1835    /// See [`Self::compile_and_run`] for more details.
1836    pub(crate) async fn run_tests(
1837        &mut self,
1838        project_root: &Path,
1839        mut config: Config,
1840        mut evm_opts: EvmOpts,
1841        output: &ProjectCompileOutput,
1842        filter: &ProjectPathsAwareFilter,
1843        mut execution: TestExecutionOptions,
1844    ) -> Result<TestOutcome> {
1845        self.ensure_mutation_mode_compatible(execution.coverage)?;
1846
1847        if config.fuzz.run == Some(0) {
1848            bail!("`fuzz.run` must be greater than 0");
1849        }
1850
1851        if self.list {
1852            return list_from_output(
1853                output,
1854                &config,
1855                &execution.inline_config,
1856                filter,
1857                self.fuzz_only,
1858                execution.replay_symbolic_artifact.as_ref(),
1859            );
1860        }
1861
1862        execution.fuzz_input =
1863            self.load_fuzz_input(output, &config, &execution.inline_config, filter)?;
1864        self.warn_unsupported_engine_flags(
1865            output,
1866            &config,
1867            &execution.inline_config,
1868            filter,
1869            &execution.multi_network,
1870        )?;
1871
1872        let mut filter = filter.clone();
1873        self.apply_gas_report_overrides(&mut config, &mut evm_opts);
1874
1875        // Generate a random fuzz seed if none provided, for reproducibility.
1876        config.fuzz.seed = config
1877            .fuzz
1878            .seed
1879            .or_else(|| Some(U256::from_be_bytes(rand::rng().random::<[u8; 32]>())));
1880
1881        let trace_output = if self.flamegraph {
1882            Some(TraceOutputKind::Flamegraph)
1883        } else if self.flamechart {
1884            Some(TraceOutputKind::Flamechart)
1885        } else {
1886            self.evm_profile.map(TraceOutputKind::EvmProfile)
1887        };
1888
1889        // Determine executor verbosity.
1890        if evm_opts.verbosity < 3 && (self.gas_report || trace_output.is_some()) {
1891            evm_opts.verbosity = 3;
1892        }
1893
1894        // Enable internal tracing for more informative flamegraph/profile. Simple tracing is
1895        // upgraded to full tracing in `run_tests_inner` when exactly one test matches.
1896        config.tracing = self.tracing.resolve(&config.tracing, evm_opts.verbosity);
1897        let json_trace_depth = config.tracing.trace_depth;
1898        execution.decode_internal = if config.tracing.decode_internal || trace_output.is_some() {
1899            InternalTraceMode::Simple
1900        } else {
1901            InternalTraceMode::None
1902        };
1903
1904        // Auto-detect network from fork chain ID when not explicitly configured.
1905        evm_opts.infer_network_from_fork().await?;
1906        // Inline configuration starts from this base config. Materialize the inferred execution
1907        // network so unrelated inline overrides cannot erase the fork's EVM family.
1908        config.networks = evm_opts.networks;
1909        let verbosity = evm_opts.verbosity;
1910
1911        let build_info_dir = config.project_paths::<MultiCompilerLanguage>().build_infos;
1912        // Box each network's run so the dispatch arms' locals stay off this frame.
1913        dispatch_network!(&evm_opts, |Net| {
1914            Box::pin(async {
1915                let backend = Backend::<Net>::spawn(evm_opts.get_fork(
1916                    &config,
1917                    evm_opts.env.chain_id.unwrap_or_default(),
1918                    None,
1919                ))?;
1920                // Retain the baseline inputs for the mutation campaign.
1921                let config_for_mutation = config.clone();
1922                let evm_opts_for_mutation = evm_opts.clone();
1923
1924                // Run each distinct per-test network annotation as a separate pass and merge
1925                // results.
1926                let override_networks =
1927                    execution.inline_config.referenced_override_networks(&config.profile);
1928                let is_multi_pass = !override_networks.is_empty();
1929                let multi_pass_timer = Instant::now();
1930                let (default_pass, override_passes) =
1931                    network_passes(config, evm_opts, &override_networks);
1932                let default_config = Arc::new(default_pass.config);
1933                let default_verbosity = default_pass.evm_opts.verbosity;
1934                let runner = self
1935                    .build_runner::<Net>(
1936                        default_config.clone(),
1937                        default_pass.evm_opts,
1938                        output,
1939                        TestExecutionOptions {
1940                            multi_network: default_pass.multi_network,
1941                            ..execution.clone()
1942                        },
1943                        backend.clone(),
1944                        ExecutorBuilder::<Net>::new(),
1945                    )
1946                    .await?;
1947                let libraries = runner.libraries.clone();
1948                let mut outcome = self
1949                    .run_tests_inner(runner, default_config, default_verbosity, &mut filter, output)
1950                    .await?;
1951                for pass in override_passes {
1952                    let (_, pass_outcome) =
1953                        self.run_network_pass(pass, output, &mut filter, execution.clone()).await?;
1954                    merge_outcomes(&mut outcome, pass_outcome);
1955                }
1956                if is_multi_pass {
1957                    // Per-pass summaries are suppressed in `run_tests_inner`.
1958                    self.print_summary(&outcome, multi_pass_timer.elapsed())?;
1959                }
1960
1961                // Record failures once after merging all network passes, including successful runs.
1962                persist_run_failures(&config_for_mutation, &outcome);
1963
1964                if let Some(replay) = &execution.replay_symbolic_artifact {
1965                    let target = &replay.artifact.test;
1966                    match outcome.tests().count() {
1967                        0 => bail!(
1968                            "symbolic artifact target `{}::{}` was not found",
1969                            target.contract,
1970                            target.test
1971                        ),
1972                        1 => {}
1973                        replayed => bail!(
1974                            "symbolic artifact target `{}::{}` matched {replayed} tests; replay requires exactly one target",
1975                            target.contract,
1976                            target.test
1977                        ),
1978                    }
1979                }
1980
1981                if let Some(path) = &self.json_file {
1982                    let mut results =
1983                        outcome.json_file_results.take().unwrap_or_else(|| outcome.results.clone());
1984                    prepare_results_for_json(&mut results, verbosity, json_trace_depth);
1985                    fs::write_json_file(path, &results)?;
1986                }
1987
1988                if let Some(trace_output) = trace_output {
1989                    self.render_trace_output(trace_output, &mut outcome).await?;
1990                }
1991
1992                if self.debug {
1993                    // Get first non-empty suite result. We will have only one such entry.
1994                    let (_, _, test_result) =
1995                        outcome.remove_first().ok_or_eyre("no tests were executed")?;
1996                    let mut sources = ContractSources::from_project_output(
1997                        output,
1998                        project_root,
1999                        Some(&libraries),
2000                    )?;
2001                    sources.insert_compiled_sources(&build_info_dir);
2002
2003                    let mut builder = DebuggerBuilder::new()
2004                        .traces(test_result.traces)
2005                        .sources(sources)
2006                        .breakpoints(test_result.breakpoints);
2007                    if let Some(decoder) = &outcome.last_run_decoder {
2008                        builder = builder.decoder(decoder);
2009                    }
2010                    if let Some(known_contracts) = &outcome.known_contracts {
2011                        builder = builder.known_contracts(known_contracts);
2012                    }
2013                    builder.run(self.dump.as_deref())?;
2014                }
2015
2016                // All tests have been run once before reaching this point
2017                if let Some(mutate) = &self.mutate {
2018                    if outcome.failed() > 0 {
2019                        bail!(
2020                            "Mutation testing compiler profile failed its unmutated baseline run; \
2021                         adjust `--mutation-via-ir` / `--mutation-optimizer-runs` or fix the tests \
2022                         before running mutation testing"
2023                        );
2024                    }
2025                    // A green baseline that ran zero non-skipped tests would report every
2026                    // compileable mutant as `Alive`, so hard-error instead of producing a
2027                    // misleading report.
2028                    if outcome.successes().next().is_none() {
2029                        bail!(
2030                            "Mutation testing requires at least one passing baseline test; the \
2031                             current filter/path selection matched zero non-skipped tests. Loosen \
2032                             `--match-test` / `--match-contract` / `--match-path` or check the \
2033                             project layout."
2034                        );
2035                    }
2036                    // Clap can't express this conflict because `--mutate` takes an optional list of
2037                    // paths.
2038                    if !mutate.is_empty() && self.mutate_path.is_some() {
2039                        bail!(
2040                            "`--mutate-path <PATTERN>` cannot be combined with explicit paths passed to `--mutate`; pass either paths or a glob pattern, not both"
2041                        );
2042                    }
2043                    // The mutation runner builds a single-pass `MultiContractRunner` and does not
2044                    // honor inline per-test network annotations, which would silently run tests on
2045                    // the wrong network and produce false survivors / kills.
2046                    if is_multi_pass {
2047                        bail!(
2048                            "Mutation testing does not yet support inline per-test network \
2049                             overrides (found {} annotated network(s)). Re-run without `--mutate` \
2050                             or remove the per-test network annotations.",
2051                            override_networks.len()
2052                        );
2053                    }
2054                    ensure_mutation_workspace_safe(&config_for_mutation)?;
2055
2056                    let json_output = shell::is_json();
2057                    let selected_sources_relative = execution
2058                        .selected_sources
2059                        .iter()
2060                        .filter_map(|path| {
2061                            path.strip_prefix(&config_for_mutation.root).ok().map(PathBuf::from)
2062                        })
2063                        .collect::<Vec<_>>();
2064                    let mutation_config = MutationRunConfig {
2065                        mutate_paths: mutate.clone(),
2066                        mutate_path_pattern: self.mutate_path.clone(),
2067                        mutate_contract_pattern: self.mutate_contract.clone(),
2068                        num_workers: self.mutation_jobs.unwrap_or(0),
2069                        show_progress: self.show_progress,
2070                        json_output,
2071                        // Carry the filter the baseline actually used (positional path shorthand
2072                        // folded into `path_pattern`, `--rerun` failures injected into
2073                        // `test_pattern`) and its isolation flag so every mutant exercises the
2074                        // exact same test set.
2075                        filter_args: filter.args().clone(),
2076                        rerun_failures: filter.rerun_failures().map(<[RerunFailure]>::to_vec),
2077                        selected_sources_relative,
2078                        isolate: evm_opts_for_mutation.isolate,
2079                    };
2080                    let result = run_mutation_testing(
2081                        Arc::new(config_for_mutation),
2082                        output,
2083                        evm_opts_for_mutation,
2084                        backend,
2085                        ExecutorBuilder::<Net>::new(),
2086                        mutation_config,
2087                    )
2088                    .await?;
2089                    if result.cancelled {
2090                        std::process::exit(130);
2091                    }
2092                    if json_output {
2093                        let json_output = result.summary.to_json_output(result.duration_secs);
2094                        sh_println!("{}", serde_json::to_string(&json_output)?)?;
2095                    }
2096                    outcome = TestOutcome::empty(None, true);
2097                }
2098
2099                Ok::<_, eyre::Report>(outcome)
2100            })
2101            .await
2102        })
2103    }
2104
2105    /// Renders the flamegraph, flamechart or EVM profile of the single executed test.
2106    async fn render_trace_output(
2107        &self,
2108        trace_output: TraceOutputKind,
2109        outcome: &mut TestOutcome,
2110    ) -> Result<()> {
2111        let label = trace_output.label();
2112        let no_tests = match trace_output {
2113            TraceOutputKind::EvmProfile(_) => "cannot generate EVM profile: no tests were executed",
2114            TraceOutputKind::Flamegraph | TraceOutputKind::Flamechart => "no tests were executed",
2115        };
2116        if outcome.tests().next().is_none() {
2117            bail!("{no_tests}");
2118        }
2119        let decoder = outcome
2120            .last_run_decoder
2121            .clone()
2122            .ok_or_else(|| eyre::eyre!("cannot generate {label}: missing trace decoder"))?;
2123        let (suite_name, test_name, test_result) =
2124            outcome
2125                .results
2126                .iter_mut()
2127                .find_map(|(suite_name, suite)| {
2128                    suite.test_results.iter_mut().next().map(|(test_name, result)| {
2129                        (suite_name.as_str(), test_name.as_str(), result)
2130                    })
2131                })
2132                .ok_or_else(|| eyre::eyre!("{no_tests}"))?;
2133        let contract = suite_name.split(':').next_back().unwrap();
2134        let test_name = test_name.trim_end_matches("()");
2135        let (_, arena) =
2136            test_result.traces.iter_mut().find(|(kind, _)| kind.is_execution()).ok_or_else(
2137                || {
2138                    eyre::eyre!(
2139                        "cannot generate {label} for {contract}::{test_name}: no execution trace \
2140                     (test may have failed in setUp/constructor or been skipped)"
2141                    )
2142                },
2143            )?;
2144        decode_trace_arena(arena, &decoder).await;
2145
2146        match trace_output {
2147            TraceOutputKind::Flamegraph | TraceOutputKind::Flamechart => {
2148                let mut folded_stack_trace = folded_stack_trace::build(arena);
2149                let flame_chart = trace_output == TraceOutputKind::Flamechart;
2150                if flame_chart {
2151                    folded_stack_trace.reverse();
2152                }
2153                let file_name = format!("cache/{label}_{contract}_{test_name}.svg");
2154                let file = std::fs::File::create(&file_name).wrap_err("failed to create file")?;
2155                let mut options = inferno::flamegraph::Options::default();
2156                options.title = format!("{label} {contract}::{test_name}");
2157                options.count_name = "gas".to_string();
2158                options.flame_chart = flame_chart;
2159                inferno::flamegraph::from_lines(
2160                    &mut options,
2161                    folded_stack_trace.iter().map(String::as_str),
2162                    std::io::BufWriter::new(file),
2163                )
2164                .wrap_err("failed to write svg")?;
2165                sh_println!("Saved to {file_name}")?;
2166                if !self.no_open
2167                    && let Err(e) = opener::open(&file_name)
2168                {
2169                    sh_err!("Failed to open {file_name}; please open it manually: {e}")?;
2170                }
2171            }
2172            TraceOutputKind::EvmProfile(EvmProfileFormat::Speedscope) => {
2173                let profile = speedscope::builder::build(arena, test_name, contract);
2174                let profile_json = serde_json::to_vec(&profile)?;
2175                let profile_path = format!("cache/evm_profile_{contract}_{test_name}.json");
2176                fs::write(&profile_path, &profile_json)?;
2177                sh_println!("Profile saved to {profile_path}")?;
2178                if !self.no_open {
2179                    evm_profile_server::serve_and_open(profile_json, test_name, contract).await?;
2180                }
2181            }
2182        }
2183        Ok(())
2184    }
2185
2186    /// Builds the test runner for the network selected by `evm_opts`.
2187    async fn build_runner<FEN: FoundryEvmNetwork>(
2188        &self,
2189        config: Arc<Config>,
2190        evm_opts: EvmOpts,
2191        output: &ProjectCompileOutput,
2192        execution: TestExecutionOptions,
2193        backend: Backend<FEN>,
2194        executor_builder: ExecutorBuilder<FEN>,
2195    ) -> Result<MultiContractRunner<FEN>> {
2196        let (evm_env, tx_env) = backend.env(&evm_opts).await?;
2197        let create2_deployer_available =
2198            backend.can_use_create2_deployer(evm_opts.create2_deployer).await?;
2199
2200        MultiContractRunnerBuilder::new(config.clone(), execution.inline_config)
2201            .set_debug(self.debug)
2202            .set_decode_internal(execution.decode_internal)
2203            .set_record_all_steps(self.evm_profile.is_some())
2204            .initial_balance(evm_opts.initial_balance)
2205            .sender(evm_opts.sender)
2206            .enable_isolation(evm_opts.isolate)
2207            .fail_fast(self.fail_fast)
2208            .set_coverage(execution.coverage)
2209            .with_multi_network(execution.multi_network)
2210            .with_showmap(self.showmap_config()?)
2211            .with_fuzz_only(self.fuzz_only)
2212            .with_fuzz_failure_replay(self.fuzz_failure_replay)
2213            .with_fuzz_input(execution.fuzz_input)
2214            .with_symbolic_artifact_replay(execution.replay_symbolic_artifact)
2215            .with_create2_deployer_available(create2_deployer_available)
2216            .build::<FEN, MultiCompiler>(
2217                output,
2218                evm_env,
2219                tx_env,
2220                evm_opts,
2221                backend,
2222                executor_builder,
2223            )
2224    }
2225
2226    /// Builds the runner for one network pass and runs its tests.
2227    async fn run_network_pass(
2228        &self,
2229        pass: NetworkPass,
2230        output: &ProjectCompileOutput,
2231        filter: &mut ProjectPathsAwareFilter,
2232        execution: TestExecutionOptions,
2233    ) -> Result<(Libraries, TestOutcome)> {
2234        let NetworkPass { config, evm_opts, multi_network } = pass;
2235        let execution = TestExecutionOptions { multi_network, ..execution };
2236        let verbosity = evm_opts.verbosity;
2237        let config = Arc::new(config);
2238        dispatch_network!(&evm_opts, |Net| {
2239            let backend = Backend::<Net>::spawn(evm_opts.get_fork(
2240                &config,
2241                evm_opts.env.chain_id.unwrap_or_default(),
2242                None,
2243            ))?;
2244            let runner = self
2245                .build_runner::<Net>(
2246                    config.clone(),
2247                    evm_opts,
2248                    output,
2249                    execution,
2250                    backend,
2251                    ExecutorBuilder::<Net>::new(),
2252                )
2253                .await?;
2254            let libraries = runner.libraries.clone();
2255            let outcome = self.run_tests_inner(runner, config, verbosity, filter, output).await?;
2256            Ok((libraries, outcome))
2257        })
2258    }
2259
2260    /// Emits symbolic regression tests for the counterexample artifacts in `results` when
2261    /// `--emit-regression` is set, and attaches them to the results.
2262    fn emit_symbolic_regressions(
2263        &self,
2264        config: &Config,
2265        known_contracts: &ContractsByArtifact,
2266        results: &mut BTreeMap<String, SuiteResult>,
2267    ) -> Result<Vec<SymbolicRegression>> {
2268        if !self.emit_regression {
2269            return Ok(Vec::new());
2270        }
2271        let regression = SymbolicRegressionConfig {
2272            out: self
2273                .regression_out
2274                .clone()
2275                .map(|path| if path.is_relative() { config.root.join(path) } else { path }),
2276            overwrite: self.regression_overwrite,
2277        };
2278        let artifacts = collect_symbolic_artifacts_from_suites(results.values());
2279        let regressions =
2280            emit_symbolic_regressions(config, &regression, known_contracts, &artifacts)?;
2281        attach_symbolic_regressions_to_suites(results.values_mut(), &regressions);
2282        Ok(regressions)
2283    }
2284
2285    /// Prints the run summary, or the detailed summary table when `--summary` is set.
2286    fn print_summary(&self, outcome: &TestOutcome, duration: Duration) -> Result<()> {
2287        if !self.summary && !shell::is_json() {
2288            sh_println!("{}", outcome.summary(duration))?;
2289        }
2290        if self.summary && !outcome.results.is_empty() {
2291            sh_println!("{}", TestSummaryReport::new(self.detailed, outcome))?;
2292        }
2293        Ok(())
2294    }
2295
2296    /// Run all tests that matches the filter predicate from a test runner
2297    async fn run_tests_inner<FEN: FoundryEvmNetwork>(
2298        &self,
2299        mut runner: MultiContractRunner<FEN>,
2300        config: Arc<Config>,
2301        verbosity: u8,
2302        filter: &mut ProjectPathsAwareFilter,
2303        output: &ProjectCompileOutput,
2304    ) -> Result<TestOutcome> {
2305        let fuzz_seed = config.fuzz.seed;
2306
2307        trace!(target: "forge::test", "running all tests");
2308
2309        // If we need to render to a serialized format, we should not print anything else to stdout.
2310        let silent = shell::is_json() && (self.gas_report || self.summary || self.mutate.is_some());
2311        let tracing = &config.tracing;
2312        let trace_verbosity = tracing.verbosity;
2313
2314        let mut num_filtered = runner.matching_test_functions(filter).count();
2315
2316        if !self.opcodes.is_empty() && trace_verbosity < 5 {
2317            sh_eprintln!()?;
2318            bail!("Not enough verbosity. Use -vvvvv to show opcodes.");
2319        }
2320
2321        if num_filtered == 0 {
2322            let empty_filter = EmptyTestFilter::default();
2323            let mut has_tests = runner.matching_test_functions(&empty_filter).next().is_some();
2324            // Selective compilation omits unmatched contracts. Consult ABI discovery only
2325            // when diagnostics need the tests that the runner cannot see.
2326            let discovery = if filter.is_empty() {
2327                None
2328            } else {
2329                Some(self.compile_test_abis(&config, filter)?.1)
2330            };
2331            let mut candidates =
2332                runner.all_test_functions(filter).map(|f| &f.name).collect::<Vec<_>>();
2333            if let Some(output) = &discovery {
2334                let matcher = runner.test_function_matcher();
2335                for (id, artifact) in output.artifact_ids() {
2336                    let id = id.with_stripped_file_prefixes(&config.root);
2337                    if let Some(abi) = &artifact.abi
2338                        && matcher.matches_contract(&empty_filter, &id, abi)
2339                        && is_runnable_test_contract(output, &config, &id, artifact, abi)
2340                    {
2341                        has_tests = true;
2342                        if filter.matches_path(&id.source) && filter.matches_contract(&id.name) {
2343                            candidates.extend(
2344                                matcher
2345                                    .test_functions(id.identifier(), abi, |_, _, kind| {
2346                                        kind.is_any_test()
2347                                    })
2348                                    .map(|function| &function.name),
2349                            );
2350                        }
2351                    }
2352                }
2353            }
2354            if has_tests {
2355                let mut msg = format!("no tests match the provided pattern:\n{filter}");
2356                // Try to suggest a test when there's no match.
2357                if let Some(test_pattern) = &filter.args().test_pattern
2358                    && let Some(suggestion) =
2359                        utils::did_you_mean(test_pattern.as_str(), candidates).pop()
2360                {
2361                    write!(msg, "\nDid you mean `{suggestion}`?")?;
2362                }
2363                sh_warn!("{msg}")?;
2364            } else {
2365                sh_warn!(
2366                    "No tests found in project! Forge looks for functions that start with `test`"
2367                )?;
2368            }
2369            // Machine-readable modes still get a well-formed, empty document on stdout.
2370            if self.junit {
2371                sh_println!("{}", junit_xml_report(&BTreeMap::new(), verbosity).to_string()?)?;
2372            } else if self.mutate.is_none() && !self.gas_report && !self.summary && shell::is_json()
2373            {
2374                sh_println!("{}", serde_json::to_string(&BTreeMap::<String, SuiteResult>::new())?)?;
2375            }
2376            return Ok(TestOutcome::empty(Some(runner.known_contracts.clone()), false));
2377        }
2378
2379        let debug_selection_term = Term::stderr();
2380        let interactive_debug_selection = self.debug
2381            && num_filtered != 1
2382            && tui_mode().is_interactive()
2383            && debug_selection_term.is_term();
2384        let mut matching_debug_tests = if interactive_debug_selection {
2385            collect_matching_debug_tests(&runner.list_signatures(filter))
2386        } else if self.debug && num_filtered != 1 {
2387            collect_matching_debug_tests(&runner.list(filter))
2388        } else {
2389            Vec::new()
2390        };
2391        if interactive_debug_selection {
2392            ctrlc::set_handler(|| {
2393                let _ = Term::stderr().show_cursor();
2394                std::process::exit(130);
2395            })?;
2396
2397            let Some(selected) = Select::new()
2398                .with_prompt("Select a test to debug")
2399                .items(
2400                    matching_debug_tests
2401                        .iter()
2402                        .map(|test| format!("{}.{}", test.contract, test.test)),
2403                )
2404                .max_length(DEBUGGER_MATCHING_TESTS_DISPLAY_LIMIT)
2405                .interact_on_opt(&debug_selection_term)?
2406            else {
2407                bail!("Debugger test selection cancelled");
2408            };
2409
2410            filter.set_rerun_failures(vec![matching_debug_tests.swap_remove(selected)]);
2411            num_filtered = 1;
2412        }
2413
2414        if num_filtered != 1
2415            && (self.debug || self.flamegraph || self.flamechart || self.evm_profile.is_some())
2416        {
2417            let action = if self.flamegraph {
2418                "generate a flamegraph"
2419            } else if self.flamechart {
2420                "generate a flamechart"
2421            } else if self.evm_profile.is_some() {
2422                "generate an EVM profile"
2423            } else {
2424                "run the debugger"
2425            };
2426            let filter_hint = if filter.is_empty() {
2427                String::new()
2428            } else {
2429                format!("\n\nFilter used:\n{filter}")
2430            };
2431            let matching_tests_hint = if self.debug {
2432                format_matching_debug_tests(&matching_debug_tests)
2433            } else {
2434                String::new()
2435            };
2436            let narrowing_hint = if self.debug {
2437                "Use --match-test <TEST_NAME>, --match-contract, and --match-path to further limit the search."
2438            } else {
2439                "Use --match-contract and --match-path to further limit the search."
2440            };
2441            bail!(
2442                "{num_filtered} tests matched your criteria, but exactly 1 test must match in order to {action}.{matching_tests_hint}\n\n\
2443                 {narrowing_hint}{filter_hint}",
2444            );
2445        }
2446
2447        // If exactly one test matched, we enable full tracing.
2448        if num_filtered == 1 && runner.decode_internal != InternalTraceMode::None {
2449            runner.decode_internal = InternalTraceMode::Full;
2450        }
2451
2452        // Run tests in a non-streaming fashion and collect results for serialization.
2453        let serialize_json =
2454            self.mutate.is_none() && !self.gas_report && !self.summary && shell::is_json();
2455        if serialize_json || self.junit {
2456            let mut results = runner.test_collect(filter)?;
2457            if serialize_json {
2458                prepare_results_for_json(&mut results, verbosity, tracing.trace_depth);
2459            }
2460            self.emit_symbolic_regressions(&config, &runner.known_contracts, &mut results)?;
2461            let rendered = if serialize_json {
2462                serde_json::to_string(&results)?
2463            } else {
2464                junit_xml_report(&results, verbosity).to_string()?
2465            };
2466            sh_println!("{rendered}")?;
2467
2468            let mut gas_snapshots = BTreeMap::<String, BTreeMap<String, String>>::new();
2469            for result in results.values().flat_map(|suite| suite.test_results.values()) {
2470                for (group, new_snapshots) in &result.gas_snapshots {
2471                    gas_snapshots.entry(group.clone()).or_default().extend(new_snapshots.clone());
2472                }
2473            }
2474            if !gas_snapshots.is_empty() {
2475                self.check_and_write_gas_snapshots(&config, &gas_snapshots)?;
2476            }
2477
2478            return Ok(TestOutcome::new(
2479                Some(runner.known_contracts),
2480                results,
2481                self.allow_failure,
2482                fuzz_seed,
2483            ));
2484        }
2485
2486        let remote_chain = runner
2487            .backend
2488            .is_in_forking_mode()
2489            .then(|| runner.tcfg.fork_chain_id.or(runner.tx_env.chain_id()))
2490            .flatten()
2491            .map(Into::into);
2492        let known_contracts = runner.known_contracts.clone();
2493        let libraries = runner.libraries.clone();
2494
2495        // Capture multi-pass state before moving `runner` into the spawn task.
2496        // In multi-pass mode the per-pass summary is suppressed; the merged summary is
2497        // printed once by the caller after all passes complete.
2498        let is_multi_pass = !runner.tcfg.multi_network.all_override_networks.is_empty();
2499        let resolved_hardfork = runner.tcfg.hardfork;
2500        let networks = runner.tcfg.evm_opts.networks;
2501        let extra_cheatcode_addresses = runner.tcfg.executor_builder.extra_cheatcode_addresses();
2502        let decode_internal = runner.decode_internal != InternalTraceMode::None;
2503
2504        // Run tests in a streaming fashion.
2505        let (tx, rx) = channel::<(String, SuiteResult)>();
2506        let timer = Instant::now();
2507        let show_progress = config.show_progress;
2508        let handle = tokio::task::spawn_blocking({
2509            let filter = filter.clone();
2510            move || runner.test(&filter, tx, show_progress).map(|()| runner)
2511        });
2512
2513        // Set up trace identifiers.
2514        let mut identifier = TraceIdentifiers::new().with_local(&known_contracts);
2515
2516        // Avoid using external identifiers for gas report as we decode more traces and this will be
2517        // expensive. Also skip external identifiers for local tests (no remote chain) to avoid
2518        // unnecessary Etherscan API calls that significantly slow down test execution.
2519        if !self.gas_report && remote_chain.is_some() {
2520            identifier = identifier.with_external(&config, remote_chain)?;
2521        }
2522
2523        // Build the trace decoder.
2524        let mut builder = CallTraceDecoderBuilder::new()
2525            .with_tracing_config(tracing)
2526            .with_known_contracts(&known_contracts)
2527            .with_networks(networks)
2528            .with_chain_id(remote_chain.map(|c| c.id()))
2529            .with_hardfork(resolved_hardfork);
2530        // Signatures are of no value for gas reports.
2531        if !self.gas_report {
2532            builder =
2533                builder.with_signature_identifier(SignaturesIdentifier::from_config(&config)?);
2534        }
2535        // SolDB decodes internal calls from compiler sources.
2536        if decode_internal && !self.debug {
2537            let sources =
2538                ContractSources::from_project_output(output, &config.root, Some(&libraries))?;
2539            builder = builder.with_debug_identifier(DebugTraceIdentifier::new(sources));
2540        }
2541        let mut decoder = builder.build();
2542
2543        let mut gas_report = self.gas_report.then(|| {
2544            GasReport::new(
2545                config.gas_reports.clone(),
2546                config.gas_reports_ignore.clone(),
2547                config.gas_reports_include_tests,
2548                extra_cheatcode_addresses.iter().copied(),
2549            )
2550        });
2551
2552        let mut gas_snapshots = BTreeMap::<String, BTreeMap<String, String>>::new();
2553
2554        let mut outcome = TestOutcome::empty(None, self.allow_failure);
2555        outcome.fuzz_seed = fuzz_seed;
2556
2557        // Some outputs need trace identities even if the textual trace is not rendered.
2558        let always_identify_traces = self.gas_report
2559            || self.debug
2560            || self.flamegraph
2561            || self.flamechart
2562            || self.evm_profile.is_some();
2563
2564        let mut any_test_failed = false;
2565        let mut backtrace_builder = None;
2566        while let Ok((contract_name, mut suite_result)) = rx.recv() {
2567            let len = suite_result.len();
2568            let tests = &mut suite_result.test_results;
2569            let has_tests = !tests.is_empty();
2570
2571            // In multi-pass (per-test network override) mode, skip suites that contributed no
2572            // tests to this pass so we don't emit a stray blank line in the suite header or
2573            // pollute the outcome with empty entries.
2574            if is_multi_pass && !has_tests && suite_result.warnings.is_empty() {
2575                continue;
2576            }
2577
2578            // Clear the addresses and labels from previous test.
2579            decoder.clear_addresses();
2580
2581            // Print suite header.
2582            if !silent {
2583                sh_println!()?;
2584                for warning in &suite_result.warnings {
2585                    sh_warn!("{warning}")?;
2586                }
2587                if has_tests {
2588                    let tests = if len > 1 { "tests" } else { "test" };
2589                    sh_println!("Ran {len} {tests} for {contract_name}")?;
2590                }
2591            }
2592
2593            // Process individual test results, printing logs and traces when necessary.
2594            for (name, result) in tests {
2595                let test_failed = result.status.is_failure();
2596                let show_traces = !self.suppress_successful_traces || test_failed;
2597                // Trace verbosity.
2598                // - 0..3: nothing.
2599                // - 3: only display traces for failed tests.
2600                // - 4: also display the setup trace for failed tests.
2601                // - 5..: display all traces for all tests, including storage changes.
2602                let should_include_trace = |kind: &TraceKind| match kind {
2603                    TraceKind::Execution => {
2604                        (trace_verbosity == 3 && test_failed) || trace_verbosity >= 4
2605                    }
2606                    TraceKind::Setup => {
2607                        (trace_verbosity == 4 && test_failed) || trace_verbosity >= 5
2608                    }
2609                    TraceKind::Deployment => false,
2610                };
2611                let renders_trace = !silent
2612                    && show_traces
2613                    && result.traces.iter().any(|(kind, _)| should_include_trace(kind));
2614                let identify_addresses = always_identify_traces || renders_trace;
2615
2616                if !silent {
2617                    sh_println!("{}", result.short_result_with_suite(name, &contract_name))?;
2618                    for artifact in &result.counterexample_artifacts {
2619                        sh_warn!("Counterexample artifact: {}", artifact.path.display())?;
2620                    }
2621
2622                    if let TestKind::Invariant { metrics, .. } = &result.kind
2623                        && !metrics.is_empty()
2624                    {
2625                        let _ = sh_println!("\n{}\n", format_invariant_metrics_table(metrics));
2626                    }
2627
2628                    // We only display logs at level 2 and above
2629                    if verbosity >= 2 && show_traces {
2630                        // We only decode logs from Hardhat and DS-style console events
2631                        let console_logs = decode_console_logs(&result.logs);
2632                        if !console_logs.is_empty() {
2633                            sh_println!("Logs:")?;
2634                            for log in console_logs {
2635                                sh_println!("  {log}")?;
2636                            }
2637                            sh_println!()?;
2638                        }
2639                    }
2640                }
2641
2642                // We shouldn't break out of the outer loop directly here so that we finish
2643                // processing the remaining tests and print the suite summary.
2644                any_test_failed |= result.status.is_failure();
2645
2646                // Clear the addresses and labels from previous runs.
2647                decoder.clear_addresses();
2648                if identify_addresses {
2649                    decoder.labels.extend(result.labels.iter().map(|(k, v)| (*k, v.clone())));
2650                }
2651
2652                // Identify addresses and decode traces.
2653                let mut decoded_traces = Vec::new();
2654                if identify_addresses {
2655                    for (kind, arena) in &mut result.traces {
2656                        if self.debug && !result.debug_bytecodes.is_empty() {
2657                            let mut local_identifier = TraceIdentifiers::new()
2658                                .with_local_and_bytecodes(
2659                                    &known_contracts,
2660                                    &result.debug_bytecodes,
2661                                );
2662                            decoder.identify(arena, &mut local_identifier);
2663                        }
2664                        decoder.identify(arena, &mut identifier);
2665
2666                        if renders_trace && should_include_trace(kind) {
2667                            decoder.opcodes = self.opcodes.clone();
2668                            decode_trace_arena(arena, &decoder).await;
2669                            let rendered = match tracing.trace_depth {
2670                                Some(trace_depth) => {
2671                                    let mut arena = arena.clone();
2672                                    prune_trace_depth(&mut arena, trace_depth);
2673                                    render_trace_arena_inner(&arena, false, trace_verbosity > 4)
2674                                }
2675                                None => render_trace_arena_inner(arena, false, trace_verbosity > 4),
2676                            };
2677                            decoded_traces.push(rendered);
2678                        }
2679                    }
2680                }
2681
2682                if !silent && show_traces && !decoded_traces.is_empty() {
2683                    sh_println!("Traces:")?;
2684                    for trace in &decoded_traces {
2685                        sh_println!("{trace}")?;
2686                    }
2687                }
2688
2689                // Extract and display backtrace for failed tests when trace verbosity >= 3.
2690                // At trace verbosity 3-4 backtraces show contract/function names only.
2691                // At trace verbosity 5 backtraces include source file locations.
2692                if !silent
2693                    && test_failed
2694                    && trace_verbosity >= 3
2695                    && let Some((_, arena)) =
2696                        result.traces.iter().find(|(kind, _)| kind.is_execution())
2697                {
2698                    let builder = backtrace_builder.get_or_insert_with(|| {
2699                        BacktraceBuilder::new(
2700                            output,
2701                            config.root.clone(),
2702                            config.parsed_libraries().ok(),
2703                            config.via_ir,
2704                        )
2705                    });
2706                    let backtrace = builder.from_traces(arena);
2707                    if !backtrace.is_empty() {
2708                        sh_println!("{}", backtrace)?;
2709                    }
2710                }
2711
2712                if let Some(gas_report) = &mut gas_report {
2713                    gas_report.analyze(result.traces.iter().map(|(_, a)| &a.arena), &decoder).await;
2714
2715                    if !result.gas_report_traces.is_empty() {
2716                        decoder.clear_addresses();
2717
2718                        // Identify the setup and deployment traces once to collect identities
2719                        // created in setUp and constructor; every sampled run starts from them.
2720                        for (kind, arena) in &result.traces {
2721                            if !kind.is_execution() {
2722                                decoder.identify_scoped(arena, &mut identifier);
2723                            }
2724                        }
2725                        let identities = decoder.address_identities();
2726
2727                        for trace in &result.gas_report_traces {
2728                            decoder.restore_address_identities(&identities);
2729
2730                            for arena in trace {
2731                                decoder.identify_scoped(arena, &mut identifier);
2732                                gas_report.analyze([arena], &decoder).await;
2733                            }
2734                        }
2735                    }
2736                }
2737
2738                if shell::is_json()
2739                    && let Some(trace_depth) = tracing.trace_depth
2740                {
2741                    for (_, arena) in &mut result.traces {
2742                        *arena = trace_arena_at_depth(arena, trace_depth);
2743                    }
2744                }
2745                // Clear memory.
2746                result.gas_report_traces = Default::default();
2747
2748                // Collect and merge gas snapshots.
2749                for (group, new_snapshots) in &result.gas_snapshots {
2750                    gas_snapshots.entry(group.clone()).or_default().extend(new_snapshots.clone());
2751                }
2752            }
2753
2754            // Print suite summary.
2755            if !silent && has_tests {
2756                sh_println!("{}", suite_result.summary())?;
2757            }
2758
2759            // Add the suite result to the outcome.
2760            outcome.results.insert(contract_name, suite_result);
2761
2762            // Stop processing the remaining suites if any test failed and `fail_fast` is set.
2763            if self.fail_fast && any_test_failed {
2764                break;
2765            }
2766        }
2767
2768        // Check and write snapshots once all suites are in, since a group can span several suites.
2769        if !gas_snapshots.is_empty() {
2770            self.check_and_write_gas_snapshots(&config, &gas_snapshots)?;
2771        }
2772
2773        let regressions =
2774            self.emit_symbolic_regressions(&config, &known_contracts, &mut outcome.results)?;
2775        if !silent {
2776            for regression in regressions {
2777                sh_warn!(
2778                    "Regression test: {} (from {})",
2779                    regression.path.display(),
2780                    regression.artifact.display()
2781                )?;
2782            }
2783        }
2784        outcome.last_run_decoder = Some(decoder);
2785        let duration = timer.elapsed();
2786
2787        trace!(target: "forge::test", len=outcome.results.len(), %any_test_failed, "done with results");
2788
2789        if let Some(gas_report) = gas_report {
2790            let finalized = gas_report.finalize();
2791            sh_println!("{finalized}")?;
2792            outcome.gas_report = Some(finalized);
2793        }
2794
2795        if !is_multi_pass {
2796            self.print_summary(&outcome, duration)?;
2797        }
2798
2799        // Keep the receiver alive only when its queued results are needed for the JSON file.
2800        let json_results_rx = self.json_file.is_some().then_some(rx);
2801
2802        // Reattach the task.
2803        match handle.await {
2804            Ok(result) => {
2805                let runner = result?;
2806                outcome.known_contracts = Some(runner.known_contracts);
2807            }
2808            Err(e) => match e.try_into_panic() {
2809                Ok(payload) => std::panic::resume_unwind(payload),
2810                Err(e) => return Err(e.into()),
2811            },
2812        }
2813
2814        // Include suites that completed after fail-fast stopped console output in the JSON file.
2815        if let Some(rx) = json_results_rx {
2816            let mut results = outcome.results.clone();
2817            for (contract_name, suite_result) in rx.try_iter() {
2818                if is_multi_pass
2819                    && suite_result.test_results.is_empty()
2820                    && suite_result.warnings.is_empty()
2821                {
2822                    continue;
2823                }
2824                results.insert(contract_name, suite_result);
2825            }
2826            outcome.json_file_results = Some(results);
2827        }
2828
2829        Ok(outcome)
2830    }
2831
2832    /// Compares the collected gas snapshots against the ones on disk and writes them back,
2833    /// depending on `--gas-snapshot-check` / `--gas-snapshot-emit` and their config defaults.
2834    ///
2835    /// The CLI flags override the config and environment, so `--gas-snapshot-check=false` disables
2836    /// a check enabled in the config. Exits with code 1 if differences are found.
2837    fn check_and_write_gas_snapshots(
2838        &self,
2839        config: &Config,
2840        gas_snapshots: &BTreeMap<String, BTreeMap<String, String>>,
2841    ) -> Result<()> {
2842        if self.gas_snapshot_check.unwrap_or(config.gas_snapshot_check) {
2843            let mut differences_found = false;
2844            for (group, snapshots) in gas_snapshots {
2845                let path = config.snapshots.join(format!("{group}.json"));
2846                // If the snapshot file doesn't exist, we can't compare so we skip.
2847                if !path.exists() {
2848                    continue;
2849                }
2850                let previous_snapshots: BTreeMap<String, String> =
2851                    fs::read_json_file(&path).expect("Failed to read snapshots from disk");
2852                let diff = snapshots
2853                    .iter()
2854                    .filter_map(|(k, v)| {
2855                        previous_snapshots
2856                            .get(k)
2857                            .filter(|previous| *previous != v)
2858                            .map(|p| (k, p, v))
2859                    })
2860                    .collect::<Vec<_>>();
2861                if diff.is_empty() {
2862                    continue;
2863                }
2864                let _ = sh_eprintln!(
2865                    "{}",
2866                    format!("\n[{group}] Failed to match snapshots:").red().bold()
2867                );
2868                for (key, previous_snapshot, snapshot) in diff {
2869                    let _ = sh_eprintln!(
2870                        "{}",
2871                        format!("- [{key}] {previous_snapshot} → {snapshot}").red()
2872                    );
2873                }
2874                differences_found = true;
2875            }
2876            if differences_found {
2877                sh_eprintln!()?;
2878                bail!("Snapshots differ from previous run");
2879            }
2880        }
2881
2882        if self.gas_snapshot_emit.unwrap_or(config.gas_snapshot_emit) {
2883            fs::create_dir_all(&config.snapshots)?;
2884            for (group, snapshots) in gas_snapshots {
2885                fs::write_pretty_json_file(
2886                    &config.snapshots.join(format!("{group}.json")),
2887                    &snapshots,
2888                )
2889                .expect("Failed to write gas snapshots to disk");
2890            }
2891        }
2892        Ok(())
2893    }
2894
2895    /// Returns the flattened [`FilterArgs`] arguments merged with [`Config`].
2896    /// Loads and applies filter from file if only last test run failures performed.
2897    pub fn filter(&self, config: &Config) -> Result<ProjectPathsAwareFilter> {
2898        let mut filter = self.filter.clone();
2899        let rerun_failures = if self.rerun {
2900            let failures = last_run_failures(config);
2901            filter.test_pattern = failures.test_pattern;
2902            failures.failures
2903        } else {
2904            None
2905        };
2906        if filter.path_pattern.is_some() {
2907            if self.path.is_some() {
2908                bail!("Can not supply both --match-path and |path|");
2909            }
2910        } else {
2911            filter.path_pattern = self.path.clone();
2912        }
2913        let mut filter = filter.merge_with_config(config);
2914        if let Some(failures) = rerun_failures {
2915            filter.set_rerun_failures(failures);
2916        }
2917        Ok(filter)
2918    }
2919
2920    /// Returns whether `BuildArgs` was configured with `--watch`
2921    pub const fn is_watch(&self) -> bool {
2922        self.watch.watch.is_some()
2923    }
2924
2925    /// Returns the [`watchexec::Config`] necessary to bootstrap a new watch loop.
2926    pub(crate) fn watchexec_config(&self) -> Result<watchexec::Config> {
2927        self.watch.watchexec_config(|| {
2928            let config = self.load_config()?;
2929            Ok([config.src, config.test])
2930        })
2931    }
2932}
2933
2934/// Returns the names of the enabled flags.
2935fn enabled_flags<const N: usize>(flags: [(bool, &'static str); N]) -> Vec<&'static str> {
2936    flags.into_iter().filter_map(|(enabled, name)| enabled.then_some(name)).collect()
2937}
2938
2939fn prepare_results_for_json(
2940    results: &mut BTreeMap<String, SuiteResult>,
2941    verbosity: u8,
2942    trace_depth: Option<usize>,
2943) {
2944    for test_result in results.values_mut().flat_map(|suite| suite.test_results.values_mut()) {
2945        if verbosity >= 2 {
2946            test_result.decoded_logs = decode_console_logs(&test_result.logs);
2947        } else {
2948            test_result.logs = Vec::new();
2949        }
2950        for (_, arena) in &mut test_result.traces {
2951            // Discard presentation-only decoding populated by the streaming renderer.
2952            for node in arena.nodes_mut() {
2953                node.trace.decoded = None;
2954                for log in &mut node.logs {
2955                    log.decoded = None;
2956                }
2957                for step in &mut node.trace.steps {
2958                    step.decoded = None;
2959                }
2960            }
2961            if let Some(trace_depth) = trace_depth {
2962                *arena = trace_arena_at_depth(arena, trace_depth);
2963            }
2964        }
2965    }
2966}
2967
2968/// Bails if mutation testing could corrupt the real dependency trees.
2969///
2970/// The mutation runner symlinks dependency directories (`lib`, `node_modules`, `dependencies`)
2971/// into each per-mutant TempDir for performance (see `workspace::copy_project`). That isolation
2972/// breaks down if tests can write to those shared trees, either via `vm.writeFile` (broad
2973/// `fs_permissions`) or arbitrary `ffi` calls.
2974fn ensure_mutation_workspace_safe(config: &Config) -> Result<()> {
2975    if config.ffi {
2976        bail!(
2977            "Mutation testing is unsafe with `ffi = true`: per-mutant workspaces share \
2978             symlinked dependency directories, and arbitrary FFI commands run by tests \
2979             can race or corrupt the real `lib`/`node_modules`/`dependencies` trees. \
2980             Disable ffi in your foundry.toml to run mutation tests."
2981        );
2982    }
2983
2984    // Only refuse write-capable `fs_permissions` whose path can actually reach one of the
2985    // symlinked dependency trees. Scoped writes (e.g. `./out`, `./snapshots`) are safe.
2986    let root = &config.root;
2987    let canonicalize_through_existing_ancestor = |path: &Path| -> PathBuf {
2988        let resolved = if path.is_absolute() { path.to_path_buf() } else { root.join(path) };
2989        if let Ok(canon) = canonicalize_path(&resolved) {
2990            return canon;
2991        }
2992        let mut missing = Vec::new();
2993        let mut ancestor = resolved.as_path();
2994        while !ancestor.exists() {
2995            let Some(name) = ancestor.file_name() else { break };
2996            missing.push(name.to_owned());
2997            let Some(parent) = ancestor.parent() else { break };
2998            ancestor = parent;
2999        }
3000        let mut canon = canonicalize_path(ancestor).unwrap_or_else(|_| ancestor.into());
3001        canon.extend(missing.iter().rev());
3002        canon
3003    };
3004
3005    let shared_dep_dirs = config
3006        .libs
3007        .iter()
3008        .filter(|p| p.exists())
3009        .cloned()
3010        .chain(
3011            ["node_modules", "dependencies"]
3012                .into_iter()
3013                .map(|dep_dir| root.join(dep_dir))
3014                .filter(|dep_path| dep_path.is_dir()),
3015        )
3016        .map(|p| canonicalize_through_existing_ancestor(&p))
3017        .collect::<Vec<_>>();
3018
3019    let permissions = &config.fs_permissions.permissions;
3020    let effective_permission = |path: &Path| -> Option<FsAccessPermission> {
3021        let mut max_path_len = 0;
3022        let mut highest_permission = FsAccessPermission::None;
3023        for perm in permissions {
3024            let permission_path = canonicalize_through_existing_ancestor(&perm.path);
3025            if !path.starts_with(&permission_path) {
3026                continue;
3027            }
3028            let path_len = permission_path.components().count();
3029            if path_len > max_path_len {
3030                max_path_len = path_len;
3031                highest_permission = perm.access;
3032            } else if path_len == max_path_len {
3033                highest_permission = match (highest_permission, perm.access) {
3034                    (FsAccessPermission::ReadWrite, _)
3035                    | (FsAccessPermission::Read, FsAccessPermission::Write)
3036                    | (FsAccessPermission::Write, FsAccessPermission::Read) => {
3037                        FsAccessPermission::ReadWrite
3038                    }
3039                    (FsAccessPermission::None, perm) => perm,
3040                    (existing_perm, _) => existing_perm,
3041                };
3042            }
3043        }
3044        (max_path_len > 0).then_some(highest_permission)
3045    };
3046    let grants_write = |path: &Path| {
3047        matches!(
3048            effective_permission(path),
3049            Some(FsAccessPermission::Write | FsAccessPermission::ReadWrite)
3050        )
3051    };
3052
3053    let unsafe_write_paths = permissions
3054        .iter()
3055        .filter(|perm| {
3056            matches!(perm.access, FsAccessPermission::Write | FsAccessPermission::ReadWrite)
3057        })
3058        .filter(|perm| {
3059            let perm_path = canonicalize_through_existing_ancestor(&perm.path);
3060            shared_dep_dirs.iter().any(|dep| {
3061                if perm_path.starts_with(dep) {
3062                    grants_write(&perm_path)
3063                } else if dep.starts_with(&perm_path) {
3064                    grants_write(dep)
3065                } else {
3066                    false
3067                }
3068            })
3069        })
3070        .map(|perm| format!("  - {}", perm.path.display()))
3071        .collect::<Vec<_>>();
3072    if !unsafe_write_paths.is_empty() {
3073        bail!(
3074            "Mutation testing is unsafe with write-capable `fs_permissions` that can \
3075             reach the symlinked dependency trees (`lib`/`node_modules`/`dependencies`); \
3076             per-mutant workspaces share those trees, so `vm.writeFile` calls would race \
3077             against or corrupt your real dependencies. Restrict the following \
3078             `fs_permissions` entries to read-only or scope them away from dependency \
3079             paths:\n{}",
3080            unsafe_write_paths.join("\n")
3081        );
3082    }
3083    Ok(())
3084}
3085
3086/// Builds a figment dictionary from `key => Option<value>` pairs, skipping unset values.
3087macro_rules! dict {
3088    ($($key:literal => $value:expr),* $(,)?) => {{
3089        let mut dict = Dict::default();
3090        $(if let Some(value) = $value {
3091            dict.insert($key.to_string(), Value::from(value));
3092        })*
3093        dict
3094    }};
3095}
3096
3097/// Renders an optional path for the figment provider.
3098fn path_string(path: &Option<PathBuf>) -> Option<String> {
3099    path.as_ref().map(|path| path.to_string_lossy().to_string())
3100}
3101
3102impl Provider for TestArgs {
3103    fn metadata(&self) -> Metadata {
3104        Metadata::named("Core Build Args Provider")
3105    }
3106
3107    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
3108        let fuzz = dict! {
3109            "seed" => self.fuzz_seed.map(|seed| seed.to_string()),
3110            "runs" => self.fuzz_runs,
3111            "run" => self.fuzz_run,
3112            "worker" => self.fuzz_worker,
3113            "timeout" => self.fuzz_timeout,
3114            "dictionary_weight" => self.fuzz_dictionary_weight,
3115            "max_fuzz_dictionary_addresses" => self.fuzz_dictionary_addresses.clone(),
3116            "max_fuzz_dictionary_values" => self.fuzz_dictionary_values.clone(),
3117            "max_fuzz_dictionary_literals" => self.fuzz_dictionary_literals.clone(),
3118            "corpus_random_sequence_weight" => self.fuzz_corpus_random_sequence_weight,
3119            "corpus_dir" => path_string(&self.fuzz_corpus_dir),
3120            "frontier_dir" => path_string(&self.fuzz_frontier_dir),
3121            "frontier_limit" => self.fuzz_frontier_limit,
3122            "payable_value_weight" => self.fuzz_payable_value_weight,
3123            "mutation_weight_splice" => self.fuzz_mutation_weight_splice,
3124            "mutation_weight_repeat" => self.fuzz_mutation_weight_repeat,
3125            "mutation_weight_interleave" => self.fuzz_mutation_weight_interleave,
3126            "mutation_weight_prefix" => self.fuzz_mutation_weight_prefix,
3127            "mutation_weight_suffix" => self.fuzz_mutation_weight_suffix,
3128            "mutation_weight_abi" => self.fuzz_mutation_weight_abi,
3129            "mutation_weight_cmp" => self.fuzz_mutation_weight_cmp,
3130        };
3131        let invariant = dict! {
3132            "runs" => self.invariant_runs_override,
3133            "depth" => self.invariant_depth,
3134            "min_depth" => self.invariant_min_depth,
3135            "depth_mode" => self.invariant_depth_mode.map(Value::serialize).transpose()?,
3136            "workers" => self.invariant_workers.map(Value::serialize).transpose()?,
3137            "dictionary_weight" => self.invariant_dictionary_weight,
3138            "max_fuzz_dictionary_addresses" => self.invariant_dictionary_addresses.clone(),
3139            "max_fuzz_dictionary_values" => self.invariant_dictionary_values.clone(),
3140            "max_fuzz_dictionary_literals" => self.invariant_dictionary_literals.clone(),
3141            "corpus_random_sequence_weight" => self.invariant_corpus_random_sequence_weight,
3142            "corpus_random_sequence_weight_configured" =>
3143                self.invariant_corpus_random_sequence_weight.map(|_| true),
3144            "corpus_dir" => path_string(&self.invariant_corpus_dir),
3145            "frontier_dir" => path_string(&self.invariant_frontier_dir),
3146            "frontier_limit" => self.invariant_frontier_limit,
3147            "payable_value_weight" => self.invariant_payable_value_weight,
3148            "timeout" => self.invariant_timeout_override,
3149            "mutation_weight_splice" => self.invariant_mutation_weight_splice,
3150            "mutation_weight_repeat" => self.invariant_mutation_weight_repeat,
3151            "mutation_weight_interleave" => self.invariant_mutation_weight_interleave,
3152            "mutation_weight_prefix" => self.invariant_mutation_weight_prefix,
3153            "mutation_weight_suffix" => self.invariant_mutation_weight_suffix,
3154            "mutation_weight_abi" => self.invariant_mutation_weight_abi,
3155            "mutation_weight_cmp" => self.invariant_mutation_weight_cmp,
3156        };
3157        let symbolic = dict! {
3158            "enabled" => self.symbolic.then_some(true),
3159            "seed_corpus" => self.symbolic_seed_corpus.then_some(true),
3160            "use_fuzz_corpus" => self.symbolic_use_fuzz_corpus.then_some(true),
3161            "corpus_seed_limit" => self.symbolic_corpus_seed_limit,
3162            "use_fuzz_frontiers" => self.symbolic_use_fuzz_frontiers.then_some(true),
3163            "live" => self.symbolic_live.then_some(true),
3164            "check_invariant_frontiers" =>
3165                self.symbolic_check_invariant_frontiers.then_some(true),
3166            "frontier_limit" => self.symbolic_frontier_limit,
3167            "frontier_ids" => self.symbolic_frontier_ids.clone(),
3168            "frontier_pcs" => self.symbolic_frontier_pcs.clone(),
3169            "frontier_selectors" => self.symbolic_frontier_selectors.clone(),
3170            "solver" => self.symbolic_solver.clone(),
3171            "solver_command" => self.symbolic_solver_command.clone(),
3172            "solver_portfolio" => self.symbolic_solver_portfolio.clone(),
3173            "timeout" => self.symbolic_timeout,
3174            "loop" => self.symbolic_loop,
3175            "depth" => self.symbolic_depth,
3176            "width" => self.symbolic_width,
3177            "max_depth" => self.symbolic_max_depth,
3178            "max_paths" => self.symbolic_max_paths,
3179            "invariant_depth" => self.symbolic_invariant_depth,
3180            "max_solver_queries" => self.symbolic_max_solver_queries,
3181            "default_dynamic_length" => self.symbolic_default_dynamic_length,
3182            "max_dynamic_length" => self.symbolic_max_dynamic_length,
3183            "array_lengths" => self.symbolic_array_lengths.clone(),
3184            "max_calldata_bytes" => self.symbolic_max_calldata_bytes,
3185            "symbolic_call_targets" => self.symbolic_call_targets.then_some(true),
3186            "dump_smt" => self.symbolic_dump_smt.then_some(true),
3187            "storage_layout" => self.symbolic_storage_layout.clone(),
3188        };
3189        let mutation = dict! {
3190            "timeout" => self.mutation_timeout,
3191            "optimizer_runs" => self.mutation_optimizer_runs,
3192            "via_ir" => self.mutation_via_ir,
3193        };
3194
3195        let mut dict = dict! {
3196            "fuzz" => Some(fuzz),
3197            "invariant" => (!invariant.is_empty()).then_some(invariant),
3198            "symbolic" => Some(symbolic),
3199            "etherscan_api_key" =>
3200                self.etherscan_api_key.as_ref().filter(|s| !s.trim().is_empty()).cloned(),
3201            "show_progress" => self.show_progress.then_some(true),
3202            "decode_external_storage" => self.decode_external_storage.then_some(true),
3203        };
3204        // Mutation-testing CLI overrides
3205        if !mutation.is_empty() {
3206            dict.insert("mutation".to_string(), mutation.into());
3207        }
3208        Ok(Map::from([(Config::selected_profile(), dict)]))
3209    }
3210}
3211
3212fn parse_opcode(s: &str) -> Result<OpCode, String> {
3213    static OPCODES: LazyLock<HashMap<&str, OpCode>> = LazyLock::new(|| {
3214        (0..=u8::MAX).filter_map(OpCode::new).map(|op| (op.as_str(), op)).collect()
3215    });
3216    OPCODES.get(s).copied().ok_or_else(|| format!("invalid opcode: {s}"))
3217}
3218
3219const fn apply_mutation_compiler_overrides(config: &mut Config) {
3220    if let Some(optimizer_runs) = config.mutation.optimizer_runs {
3221        let default_optimizer_settings =
3222            matches!(config.optimizer, Some(false)) && matches!(config.optimizer_runs, Some(200));
3223        config.optimizer_runs = Some(optimizer_runs as usize);
3224        if default_optimizer_settings {
3225            config.optimizer = None;
3226        }
3227        config.normalize_optimizer_settings();
3228    }
3229    if let Some(via_ir) = config.mutation.via_ir {
3230        config.via_ir = via_ir;
3231    }
3232}
3233
3234/// Returns whether an ABI-discovered contract could be included in the test runner.
3235fn is_runnable_test_contract(
3236    output: &ProjectCompileOutput,
3237    config: &Config,
3238    id: &ArtifactId,
3239    artifact: &ConfigurableContractArtifact,
3240    abi: &JsonAbi,
3241) -> bool {
3242    if abi.constructor.as_ref().is_some_and(|constructor| !constructor.inputs.is_empty())
3243        || is_external_artifact(&id.build_id)
3244            && artifact.get_bytecode_bytes().is_none_or(|bytecode| bytecode.is_empty())
3245    {
3246        return false;
3247    }
3248
3249    let contract_name = id.name.split('.').next().unwrap_or(&id.name);
3250    let path = config.root.join(&id.source);
3251    let compiler = output.parser().solc().compiler();
3252    compiler.enter_sequential(|compiler| {
3253        if let Some((_, source)) = compiler.gcx().get_ast_source(&path)
3254            && let Some(ast) = &source.ast
3255            && let Some(contract) = ast.items.iter().find_map(|item| match &item.kind {
3256                ItemKind::Contract(contract) if contract.name.as_str() == contract_name => {
3257                    Some(contract)
3258                }
3259                _ => None,
3260            })
3261        {
3262            return matches!(
3263                contract.kind,
3264                SolarContractKind::Contract | SolarContractKind::Library
3265            );
3266        }
3267        true
3268    })
3269}
3270
3271/// Returns the deployable contracts in `output` that match `filter`, with project-relative ids.
3272fn matching_test_contracts<'a>(
3273    output: &'a ProjectCompileOutput,
3274    config: &'a Config,
3275    matcher: &'a TestFunctionMatcher<'a>,
3276    filter: &'a ProjectPathsAwareFilter,
3277) -> impl Iterator<Item = (ArtifactId, &'a ConfigurableContractArtifact, &'a JsonAbi)> + 'a {
3278    output.artifact_ids().filter_map(move |(id, artifact)| {
3279        let abi = artifact.abi.as_ref()?;
3280        let id = id.with_stripped_file_prefixes(&config.root);
3281        let deployable = abi.constructor.as_ref().is_none_or(|c| c.inputs.is_empty());
3282        (deployable && matcher.matches_contract(filter, &id, abi)).then_some((id, artifact, abi))
3283    })
3284}
3285
3286/// Lists all matching tests without building a runner.
3287fn list_from_output(
3288    output: &ProjectCompileOutput,
3289    config: &Config,
3290    inline_config: &InlineConfig,
3291    filter: &ProjectPathsAwareFilter,
3292    fuzz_only: bool,
3293    symbolic_artifact_replay: Option<&SymbolicArtifactReplayConfig>,
3294) -> Result<TestOutcome> {
3295    let matcher = TestFunctionMatcher::new(config, inline_config, symbolic_artifact_replay);
3296    let mut results = BTreeMap::<String, BTreeMap<String, Vec<String>>>::new();
3297    for (id, _, abi) in matching_test_contracts(output, config, &matcher, filter) {
3298        let identifier = id.identifier();
3299        let generated_symbolic_regression = is_generated_symbolic_regression_contract(abi);
3300        let tests = abi
3301            .functions()
3302            .filter(|func| {
3303                let kind =
3304                    matcher.test_function_kind(&identifier, func, generated_symbolic_regression);
3305                (!fuzz_only
3306                    || matches!(
3307                        kind,
3308                        TestFunctionKind::FuzzTest { .. } | TestFunctionKind::InvariantTest
3309                    ))
3310                    && filter.matches_test_function_kind_in_contract(&identifier, func, kind)
3311            })
3312            .map(|func| func.name.clone())
3313            .collect::<Vec<_>>();
3314        if !tests.is_empty() {
3315            results.entry(id.source.display().to_string()).or_default().insert(id.name, tests);
3316        }
3317    }
3318
3319    if shell::is_json() {
3320        sh_println!("{}", serde_json::to_string(&results)?)?;
3321    } else {
3322        for (file, contracts) in &results {
3323            sh_println!("{file}")?;
3324            for (contract, tests) in contracts {
3325                sh_println!("  {contract}")?;
3326                sh_println!("    {}\n", tests.join("\n    "))?;
3327            }
3328        }
3329    }
3330    Ok(TestOutcome::empty(None, false))
3331}
3332
3333fn matching_fuzz_replay_targets(
3334    output: &ProjectCompileOutput,
3335    config: &Config,
3336    inline_config: &InlineConfig,
3337    filter: &ProjectPathsAwareFilter,
3338    selector: &[u8],
3339) -> Result<Vec<(String, String)>> {
3340    let matcher = TestFunctionMatcher::new(config, inline_config, None);
3341    let mut targets = Vec::new();
3342    for (id, artifact, abi) in matching_test_contracts(output, config, &matcher, filter) {
3343        let has_creation_code =
3344            artifact.get_bytecode_object().is_some_and(|object| match object.as_ref() {
3345                BytecodeObject::Bytecode(bytecode) => !bytecode.is_empty(),
3346                BytecodeObject::Unlinked(_) => true,
3347            });
3348        if !has_creation_code {
3349            continue;
3350        }
3351        let contract = id.identifier();
3352        let generated_symbolic_regression = is_generated_symbolic_regression_contract(abi);
3353        for func in abi.functions() {
3354            let kind = matcher.test_function_kind(&contract, func, generated_symbolic_regression);
3355            if !kind.is_fuzz_test()
3356                || !filter.matches_test_function_kind_in_contract(&contract, func, kind)
3357            {
3358                continue;
3359            }
3360            let function_config = inline_config_for(config, inline_config, &contract, Some(func))?;
3361            if effective_test_function_kind(kind, &function_config, func).is_fuzz_test()
3362                && func.selector() == selector
3363            {
3364                targets.push((contract.clone(), func.signature()));
3365            }
3366        }
3367    }
3368    Ok(targets)
3369}
3370
3371/// Merges `other` into `base` by extending suite results.
3372///
3373/// For suites that appear in both, test results are combined (function-level pass routing ensures
3374/// each function appears in exactly one pass, so there are no key conflicts in practice).
3375fn merge_outcomes(base: &mut TestOutcome, mut other: TestOutcome) {
3376    if let Some(other_results) = other.json_file_results.take() {
3377        let base_results = base.json_file_results.get_or_insert_with(|| base.results.clone());
3378        merge_suite_results(base_results, other_results);
3379    }
3380    merge_suite_results(&mut base.results, other.results);
3381    if let Some(decoder) = other.last_run_decoder {
3382        base.last_run_decoder = Some(decoder);
3383    }
3384}
3385
3386fn merge_suite_results(
3387    base: &mut BTreeMap<String, SuiteResult>,
3388    other: BTreeMap<String, SuiteResult>,
3389) {
3390    for (suite_id, other_suite) in other {
3391        if let Some(base_suite) = base.get_mut(&suite_id) {
3392            base_suite.test_results.extend(other_suite.test_results);
3393            base_suite.warnings.extend(other_suite.warnings);
3394            base_suite.duration = base_suite.duration.max(other_suite.duration);
3395        } else {
3396            base.insert(suite_id, other_suite);
3397        }
3398    }
3399}
3400
3401fn collect_matching_debug_tests(
3402    matching_tests: &BTreeMap<String, BTreeMap<String, Vec<String>>>,
3403) -> Vec<RerunFailure> {
3404    matching_tests
3405        .iter()
3406        .flat_map(|(source, contracts)| {
3407            contracts.iter().flat_map(move |(contract, tests)| {
3408                tests.iter().map(move |test| RerunFailure {
3409                    contract: format!("{source}:{contract}"),
3410                    test: test.clone(),
3411                })
3412            })
3413        })
3414        .collect()
3415}
3416
3417fn format_matching_debug_tests(matching_tests: &[RerunFailure]) -> String {
3418    if matching_tests.is_empty() {
3419        return String::new();
3420    }
3421    let mut output = String::from("\n\nMatching tests:");
3422    for test in matching_tests.iter().take(DEBUGGER_MATCHING_TESTS_DISPLAY_LIMIT) {
3423        write!(output, "\n  {}.{}", test.contract, test.test).unwrap();
3424    }
3425    if matching_tests.len() > DEBUGGER_MATCHING_TESTS_DISPLAY_LIMIT {
3426        write!(
3427            output,
3428            "\n  ... and {} more",
3429            matching_tests.len() - DEBUGGER_MATCHING_TESTS_DISPLAY_LIMIT
3430        )
3431        .unwrap();
3432    }
3433    output
3434}
3435
3436struct LastRunFailures {
3437    test_pattern: Option<Regex>,
3438    failures: Option<Vec<RerunFailure>>,
3439}
3440
3441/// Load persisted filter (with last test run failures) from file.
3442fn last_run_failures(config: &Config) -> LastRunFailures {
3443    let Ok(filter) = fs::read_to_string(&config.test_failures_file) else {
3444        return LastRunFailures { test_pattern: None, failures: None };
3445    };
3446
3447    if let Ok(failures) = serde_json::from_str::<RerunFailures>(&filter) {
3448        if failures.failures.is_empty() {
3449            return LastRunFailures { test_pattern: None, failures: None };
3450        }
3451        let test_pattern = failures
3452            .failures
3453            .iter()
3454            .map(|failure| regex::escape(&failure.test))
3455            .collect::<Vec<_>>()
3456            .join("|");
3457        let test_pattern = Regex::new(&test_pattern).ok();
3458        return LastRunFailures { test_pattern, failures: Some(failures.failures) };
3459    }
3460
3461    // Legacy format: a plain regex.
3462    let test_pattern = Regex::new(&filter)
3463        .inspect_err(|e| {
3464            _ = sh_warn!("failed to parse test filter from {:?}: {e}", config.test_failures_file)
3465        })
3466        .ok();
3467    LastRunFailures { test_pattern, failures: None }
3468}
3469
3470/// Replace the last run failures, clearing the record when the run succeeds.
3471fn persist_run_failures(config: &Config, outcome: &TestOutcome) {
3472    if outcome.failed() == 0 {
3473        let _ = fs::remove_file(&config.test_failures_file);
3474    } else if fs::create_file(&config.test_failures_file).is_ok() {
3475        let failures = outcome
3476            .results
3477            .iter()
3478            .flat_map(|(contract, suite)| {
3479                suite.test_results.iter().filter(|(_, result)| result.status.is_failure()).flat_map(
3480                    move |(test_name, test_result)| {
3481                        rerun_filter_matches(test_name, test_result)
3482                            .map(move |test| RerunFailure { contract: contract.clone(), test })
3483                    },
3484                )
3485            })
3486            .collect::<Vec<_>>();
3487
3488        if let Ok(output) = serde_json::to_string(&RerunFailures { version: 1, failures }) {
3489            let _ = fs::write(&config.test_failures_file, output);
3490        }
3491    }
3492}
3493
3494/// Returns the rerun keys of a failed test: its failed invariant predicates, or the test name when
3495/// no predicate failed.
3496fn rerun_filter_matches<'a>(
3497    test_name: &'a str,
3498    test_result: &'a TestResult,
3499) -> impl Iterator<Item = String> + 'a {
3500    let predicate_failures =
3501        test_result.invariant_failures.iter().filter_map(|failure| failure.predicate_name());
3502    let has_predicate_failures = predicate_failures.clone().next().is_some();
3503    let fallback = test_name.is_any_test().then(|| test_name.split('(').next()).flatten();
3504    predicate_failures
3505        .chain(fallback.into_iter().filter(move |_| !has_predicate_failures))
3506        .map(str::to_owned)
3507}
3508
3509/// Generate test report in JUnit XML report format.
3510fn junit_xml_report(results: &BTreeMap<String, SuiteResult>, verbosity: u8) -> Report {
3511    let mut total_duration = Duration::default();
3512    let mut junit_report = Report::new("Test run");
3513    junit_report.set_timestamp(Utc::now());
3514    for (suite_name, suite_result) in results {
3515        let mut test_suite = TestSuite::new(suite_name);
3516        total_duration += suite_result.duration;
3517        test_suite.set_time(suite_result.duration);
3518        test_suite.set_system_out(suite_result.summary());
3519        for (test_name, test_result) in &suite_result.test_results {
3520            add_junit_test_cases(&mut test_suite, test_name, test_result, verbosity);
3521        }
3522        junit_report.add_test_suite(test_suite);
3523    }
3524    junit_report.set_time(total_duration);
3525    junit_report
3526}
3527
3528/// Adds JUnit test cases for a test result.
3529///
3530/// Invariant campaigns are expanded into per-predicate and per-handler cases so CI can report
3531/// contract-level execution without losing failure attribution.
3532fn add_junit_test_cases(
3533    test_suite: &mut TestSuite,
3534    test_name: &str,
3535    test_result: &TestResult,
3536    verbosity: u8,
3537) {
3538    let output = JunitOutput::new(test_result, verbosity);
3539    let expanded_invariant = test_result.kind.is_invariant()
3540        && (!test_result.invariant_predicate_results.is_empty()
3541            || !test_result.invariant_handler_failures.is_empty());
3542
3543    if !expanded_invariant {
3544        add_junit_test_case(
3545            test_suite,
3546            test_name,
3547            test_result.status,
3548            test_result.reason.as_deref(),
3549            test_result.duration,
3550            output.system_out(test_result, test_name),
3551        );
3552        return;
3553    }
3554
3555    let mut add_expanded_case =
3556        |name: &str,
3557         status: TestStatus,
3558         reason: Option<&str>,
3559         counterexample: Option<&CounterExample>| {
3560            add_junit_test_case(
3561                test_suite,
3562                name,
3563                status,
3564                reason,
3565                test_result.duration,
3566                output.case_system_out(status, reason, name, counterexample),
3567            );
3568        };
3569
3570    if test_result.invariant_predicate_results.is_empty() {
3571        let failure = test_result.invariant_failures.first();
3572        let status = if failure.is_some() { TestStatus::Failure } else { TestStatus::Success };
3573        add_expanded_case(
3574            test_name,
3575            status,
3576            failure.map(|failure| failure.reason()),
3577            failure.and_then(|failure| failure.counterexample()),
3578        );
3579    } else {
3580        for predicate in &test_result.invariant_predicate_results {
3581            let failure = test_result
3582                .invariant_failures
3583                .iter()
3584                .find(|failure| failure.name() == predicate.name.as_str());
3585            add_expanded_case(
3586                &format!("{}()", predicate.name),
3587                predicate.status,
3588                predicate.reason.as_deref(),
3589                failure.and_then(|failure| failure.counterexample()),
3590            );
3591        }
3592    }
3593
3594    for failure in &test_result.invariant_handler_failures {
3595        add_expanded_case(
3596            &format!("handler {}", failure.name()),
3597            TestStatus::Failure,
3598            Some(failure.reason()),
3599            failure.counterexample(),
3600        );
3601    }
3602}
3603
3604/// Adds a single JUnit test case to the suite.
3605fn add_junit_test_case(
3606    test_suite: &mut TestSuite,
3607    test_name: &str,
3608    status: TestStatus,
3609    message: Option<&str>,
3610    duration: Duration,
3611    system_out: String,
3612) {
3613    let mut test_status = match status {
3614        TestStatus::Success => TestCaseStatus::success(),
3615        TestStatus::Failure => TestCaseStatus::non_success(NonSuccessKind::Failure),
3616        TestStatus::Skipped => TestCaseStatus::skipped(),
3617    };
3618    if let Some(message) = message {
3619        test_status.set_message(message);
3620    }
3621    let mut test_case = TestCase::new(test_name, test_status);
3622    test_case.set_time(duration);
3623    test_case.set_system_out(system_out);
3624    test_suite.add_test_case(test_case);
3625}
3626
3627/// Helper for assembling JUnit output strings.
3628struct JunitOutput {
3629    result_report: TestKindReport,
3630    logs: Option<Vec<String>>,
3631}
3632
3633impl JunitOutput {
3634    fn new(test_result: &TestResult, verbosity: u8) -> Self {
3635        Self {
3636            result_report: test_result.kind.report(),
3637            logs: (verbosity >= 2 && !test_result.logs.is_empty())
3638                .then(|| decode_console_logs(&test_result.logs)),
3639        }
3640    }
3641
3642    /// Renders the suite-level `system-out` payload.
3643    fn system_out(&self, test_result: &TestResult, test_name: &str) -> String {
3644        let mut sys_out = format!("{test_result} {test_name} {}", self.result_report);
3645        self.append_logs(&mut sys_out);
3646        sys_out
3647    }
3648
3649    /// Renders the case-level `system-out` payload.
3650    fn case_system_out(
3651        &self,
3652        status: TestStatus,
3653        message: Option<&str>,
3654        test_name: &str,
3655        counterexample: Option<&CounterExample>,
3656    ) -> String {
3657        let mut sys_out = match (status, message) {
3658            (TestStatus::Success, _) => "[PASS]".to_string(),
3659            (TestStatus::Failure, message) => format!("[FAIL: {}]", message.unwrap_or_default()),
3660            (TestStatus::Skipped, Some(message)) => format!("[SKIP: {message}]"),
3661            (TestStatus::Skipped, None) => "[SKIP]".to_string(),
3662        };
3663        write!(sys_out, " {test_name} {}", self.result_report).unwrap();
3664        if let Some(CounterExample::Sequence(original, sequence)) = counterexample {
3665            writeln!(sys_out, "\n\t[Sequence] (original: {original}, shrunk: {})", sequence.len())
3666                .unwrap();
3667            for ex in sequence {
3668                writeln!(sys_out, "{ex}").unwrap();
3669            }
3670        }
3671        self.append_logs(&mut sys_out);
3672        sys_out
3673    }
3674
3675    /// Appends captured console logs to the output payload.
3676    fn append_logs(&self, sys_out: &mut String) {
3677        if let Some(logs) = &self.logs {
3678            write!(sys_out, "\\nLogs:\\n").unwrap();
3679            for log in logs {
3680                write!(sys_out, "  {log}\\n").unwrap();
3681            }
3682        }
3683    }
3684}
3685
3686#[cfg(test)]
3687mod tests {
3688    use super::*;
3689
3690    #[test]
3691    fn parses_opcode_names_exactly() {
3692        assert_eq!(parse_opcode("SSTORE"), Ok(OpCode::SSTORE));
3693        assert_eq!(parse_opcode("PUSH32"), Ok(OpCode::PUSH32));
3694        assert_eq!(parse_opcode("sstore"), Err("invalid opcode: sstore".to_string()));
3695        assert_eq!(parse_opcode("NOPE"), Err("invalid opcode: NOPE".to_string()));
3696    }
3697
3698    /// Parses `args` with the given environment variables set, restoring the previous values.
3699    fn parse_with_env(vars: &[(&str, &str)], args: &[&str]) -> TestArgs {
3700        static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
3701        let _guard = ENV_LOCK.lock().unwrap();
3702        let previous = vars.iter().map(|(name, _)| std::env::var_os(name)).collect::<Vec<_>>();
3703        for (name, value) in vars {
3704            unsafe { std::env::set_var(name, value) };
3705        }
3706        let parsed =
3707            TestArgs::try_parse_from(["foundry-cli"].into_iter().chain(args.iter().copied()));
3708        for ((name, _), previous) in vars.iter().zip(previous) {
3709            match previous {
3710                Some(previous) => unsafe { std::env::set_var(name, previous) },
3711                None => unsafe { std::env::remove_var(name) },
3712            }
3713        }
3714        parsed.unwrap()
3715    }
3716
3717    #[test]
3718    fn parses_flags_without_cli_coverage() {
3719        assert!(TestArgs::parse_from(["foundry-cli", "-vw"]).watch.watch.is_some());
3720        assert!(TestArgs::parse_from(["foundry-cli", "--compact-labels"]).tracing.compact_labels);
3721        // <https://github.com/foundry-rs/foundry/issues/5913>
3722        let args =
3723            TestArgs::parse_from(["foundry-cli", "-vvv", "--gas-report", "--fuzz-seed", "0x10"]);
3724        assert!(args.fuzz_seed.is_some());
3725        let args = TestArgs::parse_from(["foundry-cli", "--invariant-workers", "auto"]);
3726        assert_eq!(args.invariant_workers, Some(InvariantWorkers::Auto));
3727        assert_eq!(
3728            figment::Figment::from(&args)
3729                .extract_inner::<InvariantWorkers>("invariant.workers")
3730                .unwrap(),
3731            InvariantWorkers::Auto
3732        );
3733    }
3734
3735    #[test]
3736    fn parses_env_vars() {
3737        let args = parse_with_env(
3738            &[
3739                ("FOUNDRY_INVARIANT_WORKERS", "auto"),
3740                ("FOUNDRY_FUZZ_CORPUS_DIR", "env_fuzz_corpus"),
3741                ("FOUNDRY_INVARIANT_CORPUS_DIR", "env_invariant_corpus"),
3742            ],
3743            &[],
3744        );
3745        assert_eq!(args.invariant_workers, Some(InvariantWorkers::Auto));
3746        assert_eq!(args.fuzz_corpus_dir, Some(PathBuf::from("env_fuzz_corpus")));
3747        assert_eq!(args.invariant_corpus_dir, Some(PathBuf::from("env_invariant_corpus")));
3748    }
3749
3750    #[test]
3751    fn showmap_override_validates_path_component_names() {
3752        let mut args = TestArgs::parse_from(["foundry-cli"]);
3753        args.set_showmap_override(ShowmapConfig {
3754            out_dir: PathBuf::from("showmap"),
3755            approach: "../outside".to_string(),
3756            trial: "trial".to_string(),
3757            per_input: false,
3758            domain: ShowmapDomain::Evm,
3759            corpus_dir: None,
3760            emit_files: false,
3761        });
3762
3763        let err = args.showmap_config().unwrap_err().to_string();
3764        assert!(err.contains("expected a single file-name component"), "{err}");
3765    }
3766
3767    #[test]
3768    fn debugger_test_candidates_preserve_exact_suite_ids() {
3769        let matching = BTreeMap::from([(
3770            "test/Counter.t.sol".to_string(),
3771            BTreeMap::from([(
3772                "CounterTest".to_string(),
3773                vec!["testFuzz_SetNumber(uint256)".to_string(), "test_Increment()".to_string()],
3774            )]),
3775        )]);
3776
3777        let candidates = collect_matching_debug_tests(&matching);
3778
3779        assert_eq!(candidates[0].contract, "test/Counter.t.sol:CounterTest");
3780        assert_eq!(candidates[0].test, "testFuzz_SetNumber(uint256)");
3781        assert_eq!(candidates[1].test, "test_Increment()");
3782        assert_eq!(
3783            format_matching_debug_tests(&candidates),
3784            "\n\nMatching tests:\n  test/Counter.t.sol:CounterTest.testFuzz_SetNumber(uint256)\n  test/Counter.t.sol:CounterTest.test_Increment()"
3785        );
3786    }
3787
3788    #[test]
3789    fn fuzz_run_adapter_writes_unified_campaign_dials_sparsely() {
3790        let args = FuzzRunArgs::parse_from([
3791            "foundry-cli",
3792            "--runs",
3793            "9",
3794            "--timeout",
3795            "3",
3796            "--seed",
3797            "0x10",
3798            "--depth",
3799            "7",
3800            "--workers",
3801            "2",
3802            "--frontier-dir",
3803            "frontiers",
3804            "--frontier-limit",
3805            "17",
3806        ]);
3807        let args = TestArgs::from_fuzz_run(args);
3808        let figment = figment::Figment::from(&args);
3809
3810        assert_eq!(figment.extract_inner::<u64>("fuzz.runs").unwrap(), 9);
3811        assert_eq!(figment.extract_inner::<u64>("fuzz.timeout").unwrap(), 3);
3812        assert_eq!(figment.extract_inner::<String>("fuzz.seed").unwrap(), "16");
3813        assert_eq!(figment.extract_inner::<u64>("invariant.runs").unwrap(), 9);
3814        assert_eq!(figment.extract_inner::<u32>("invariant.timeout").unwrap(), 3);
3815        assert_eq!(figment.extract_inner::<u32>("invariant.depth").unwrap(), 7);
3816        assert_eq!(
3817            figment.extract_inner::<PathBuf>("fuzz.frontier_dir").unwrap(),
3818            PathBuf::from("frontiers")
3819        );
3820        assert_eq!(figment.extract_inner::<usize>("fuzz.frontier_limit").unwrap(), 17);
3821        assert_eq!(
3822            figment.extract_inner::<PathBuf>("invariant.frontier_dir").unwrap(),
3823            PathBuf::from("frontiers")
3824        );
3825        assert_eq!(figment.extract_inner::<usize>("invariant.frontier_limit").unwrap(), 17);
3826        assert_eq!(
3827            figment.extract_inner::<InvariantWorkers>("invariant.workers").unwrap(),
3828            InvariantWorkers::Fixed(std::num::NonZeroUsize::new(2).unwrap())
3829        );
3830    }
3831
3832    #[test]
3833    fn fuzz_run_adapter_writes_invariant_workers_sparsely() {
3834        let args = TestArgs::from_fuzz_run(FuzzRunArgs::parse_from(["foundry-cli"]));
3835        let figment = figment::Figment::from(&args);
3836
3837        assert_eq!(args.invariant_workers, None);
3838        assert!(figment.extract_inner::<InvariantWorkers>("invariant.workers").is_err());
3839    }
3840
3841    #[test]
3842    fn mutation_compiler_overrides_are_extracted() {
3843        let args = TestArgs::parse_from([
3844            "foundry-cli",
3845            "--mutate",
3846            "--mutation-optimizer-runs",
3847            "1",
3848            "--mutation-via-ir",
3849            "false",
3850        ]);
3851        let figment = figment::Figment::from(&args);
3852        assert_eq!(figment.extract_inner::<u32>("mutation.optimizer_runs").unwrap(), 1);
3853        assert!(!figment.extract_inner::<bool>("mutation.via_ir").unwrap());
3854    }
3855
3856    #[test]
3857    fn mutation_compiler_overrides_update_only_mutation_config_clone() {
3858        let mut config = Config {
3859            optimizer_runs: Some(999),
3860            via_ir: true,
3861            mutation: foundry_config::MutationConfig {
3862                optimizer_runs: Some(1),
3863                via_ir: Some(false),
3864                ..Default::default()
3865            },
3866            ..Default::default()
3867        };
3868
3869        apply_mutation_compiler_overrides(&mut config);
3870
3871        assert_eq!(config.optimizer_runs, Some(1));
3872        assert!(!config.via_ir);
3873    }
3874
3875    #[test]
3876    fn mutation_optimizer_runs_normalize_default_optimizer_settings() {
3877        let mut config = Config {
3878            optimizer: Some(false),
3879            optimizer_runs: Some(200),
3880            mutation: foundry_config::MutationConfig {
3881                optimizer_runs: Some(1),
3882                ..Default::default()
3883            },
3884            ..Default::default()
3885        };
3886
3887        apply_mutation_compiler_overrides(&mut config);
3888
3889        assert_eq!(config.optimizer, Some(true));
3890        assert_eq!(config.optimizer_runs, Some(1));
3891    }
3892
3893    #[test]
3894    fn auto_fuzz_corpus_defaults_to_cache_failure_layout() {
3895        let mut args = TestArgs::parse_from(["foundry-cli"]);
3896        args.enable_fuzz_only_with_auto_fuzz_corpus();
3897        let mut config = Config::default();
3898
3899        args.apply_test_config_overrides(&mut config);
3900
3901        assert_eq!(
3902            config.fuzz.corpus.corpus_dir,
3903            Some(config.cache_path.join(AUTO_FUZZ_FAILURE_DIR).join(AUTO_CORPUS_DIR))
3904        );
3905        assert_eq!(config.invariant.corpus.corpus_dir, None);
3906    }
3907
3908    #[test]
3909    fn auto_fuzz_corpus_uses_configured_failure_persist_dirs() {
3910        let mut args = TestArgs::parse_from(["foundry-cli"]);
3911        args.enable_fuzz_only_with_auto_fuzz_corpus();
3912        let mut config = Config::default();
3913        config.fuzz.failure_persist_dir = Some(PathBuf::from("custom_fuzz_failures"));
3914
3915        args.apply_test_config_overrides(&mut config);
3916
3917        assert_eq!(
3918            config.fuzz.corpus.corpus_dir,
3919            Some(PathBuf::from("custom_fuzz_failures").join(AUTO_CORPUS_DIR))
3920        );
3921        assert_eq!(config.invariant.corpus.corpus_dir, None);
3922    }
3923
3924    #[test]
3925    fn auto_fuzz_corpus_preserves_configured_corpus_dirs() {
3926        let mut args = TestArgs::parse_from(["foundry-cli"]);
3927        args.enable_fuzz_only_with_auto_fuzz_corpus();
3928        let mut config = Config::default();
3929        config.fuzz.corpus.corpus_dir = Some(PathBuf::from("configured_fuzz_corpus"));
3930        config.invariant.corpus.corpus_dir = Some(PathBuf::from("configured_invariant_corpus"));
3931
3932        args.apply_test_config_overrides(&mut config);
3933
3934        assert_eq!(config.fuzz.corpus.corpus_dir, Some(PathBuf::from("configured_fuzz_corpus")));
3935        assert_eq!(
3936            config.invariant.corpus.corpus_dir,
3937            Some(PathBuf::from("configured_invariant_corpus"))
3938        );
3939    }
3940
3941    #[test]
3942    fn fuzz_only_does_not_enable_auto_fuzz_corpus() {
3943        let mut args = TestArgs::parse_from(["foundry-cli"]);
3944        args.enable_fuzz_only();
3945        let mut config = Config::default();
3946
3947        args.apply_test_config_overrides(&mut config);
3948
3949        assert_eq!(config.fuzz.corpus.corpus_dir, None);
3950        assert_eq!(config.invariant.corpus.corpus_dir, None);
3951    }
3952
3953    #[test]
3954    fn debug_brutalize_includes_storage_layout_output() {
3955        let args = TestArgs::parse_from(["foundry-cli", "--debug", "--brutalize"]);
3956        let mut config = Config::default();
3957
3958        args.apply_test_config_overrides(&mut config);
3959
3960        assert_eq!(config.extra_output, vec![ContractOutputSelection::StorageLayout]);
3961        assert!(config.build_info);
3962    }
3963
3964    #[test]
3965    fn fuzz_and_invariant_config_flags() {
3966        let args = TestArgs::parse_from([
3967            "foundry-cli",
3968            "--fuzz-dictionary-weight",
3969            "35",
3970            "--fuzz-dictionary-addresses",
3971            "max",
3972            "--fuzz-dictionary-values",
3973            "1234",
3974            "--fuzz-dictionary-literals",
3975            "4321",
3976            "--fuzz-corpus-random-sequence-weight",
3977            "55",
3978            "--fuzz-corpus-dir",
3979            "fuzz_corpus",
3980            "--fuzz-frontier-dir",
3981            "fuzz_frontiers",
3982            "--fuzz-frontier-limit",
3983            "7",
3984            "--fuzz-payable-value-weight",
3985            "12",
3986            "--fuzz-mutation-weight-splice",
3987            "4",
3988            "--fuzz-mutation-weight-abi",
3989            "3",
3990            "--fuzz-mutation-weight-cmp",
3991            "5",
3992            "--symbolic-use-fuzz-frontiers",
3993            "--symbolic-check-invariant-frontiers",
3994            "--symbolic-frontier-limit",
3995            "3",
3996            "--symbolic-frontier-ids",
3997            "4,9",
3998            "--symbolic-frontier-pcs",
3999            "123,456",
4000            "--symbolic-frontier-selectors",
4001            "0x12345678,deadbeef",
4002            "--invariant-depth",
4003            "300",
4004            "--invariant-min-depth",
4005            "20",
4006            "--invariant-depth-mode",
4007            "random",
4008            "--invariant-workers",
4009            "4",
4010            "--invariant-dictionary-weight",
4011            "45",
4012            "--invariant-dictionary-addresses",
4013            "8765",
4014            "--invariant-dictionary-values",
4015            "max",
4016            "--invariant-dictionary-literals",
4017            "6789",
4018            "--invariant-corpus-random-sequence-weight",
4019            "25",
4020            "--invariant-corpus-dir",
4021            "invariant_corpus",
4022            "--invariant-payable-value-weight",
4023            "34",
4024            "--invariant-mutation-weight-splice",
4025            "2",
4026            "--invariant-mutation-weight-cmp",
4027            "7",
4028        ]);
4029
4030        let config = Config::default().merge_inline_provider(&args).unwrap();
4031        assert_eq!(config.fuzz.dictionary.dictionary_weight, 35);
4032        assert_eq!(config.fuzz.dictionary.max_fuzz_dictionary_addresses, usize::MAX);
4033        assert_eq!(config.fuzz.dictionary.max_fuzz_dictionary_values, 1234);
4034        assert_eq!(config.fuzz.dictionary.max_fuzz_dictionary_literals, 4321);
4035        assert_eq!(config.fuzz.corpus.corpus_random_sequence_weight, 55);
4036        assert_eq!(config.fuzz.corpus.corpus_dir, Some(PathBuf::from("fuzz_corpus")));
4037        assert_eq!(config.fuzz.corpus.frontier_dir, Some(PathBuf::from("fuzz_frontiers")));
4038        assert_eq!(config.fuzz.corpus.frontier_limit, 7);
4039        assert_eq!(config.fuzz.corpus.payable_value_weight, 12);
4040        assert_eq!(config.fuzz.corpus.mutation_weights.mutation_weight_splice, 4);
4041        assert_eq!(config.fuzz.corpus.mutation_weights.mutation_weight_abi, 3);
4042        assert_eq!(config.fuzz.corpus.mutation_weights.mutation_weight_cmp, 5);
4043        assert!(config.symbolic.use_fuzz_frontiers);
4044        assert!(config.symbolic.check_invariant_frontiers);
4045        assert_eq!(config.symbolic.frontier_limit, 3);
4046        assert_eq!(config.symbolic.frontier_ids, vec![4, 9]);
4047        assert_eq!(config.symbolic.frontier_pcs, vec![123, 456]);
4048        assert_eq!(config.symbolic.frontier_selectors, vec!["0x12345678", "deadbeef"]);
4049        assert_eq!(config.invariant.depth, 300);
4050        assert_eq!(config.invariant.min_depth, 20);
4051        assert_eq!(config.invariant.depth_mode, InvariantDepthMode::Random);
4052        assert_eq!(config.invariant.dictionary.dictionary_weight, 45);
4053        assert_eq!(config.invariant.dictionary.max_fuzz_dictionary_addresses, 8765);
4054        assert_eq!(config.invariant.dictionary.max_fuzz_dictionary_values, usize::MAX);
4055        assert_eq!(config.invariant.dictionary.max_fuzz_dictionary_literals, 6789);
4056        assert_eq!(config.invariant.corpus.corpus_random_sequence_weight, 25);
4057        assert_eq!(config.invariant.corpus.corpus_dir, Some(PathBuf::from("invariant_corpus")));
4058        assert!(config.invariant.corpus_random_sequence_weight_configured);
4059        assert_eq!(
4060            config.invariant.workers,
4061            InvariantWorkers::Fixed(std::num::NonZeroUsize::new(4).unwrap())
4062        );
4063        assert!(config.invariant.workers_configured);
4064        assert_eq!(config.invariant.corpus.payable_value_weight, 34);
4065        assert_eq!(config.invariant.corpus.mutation_weights.mutation_weight_splice, 2);
4066        assert_eq!(config.invariant.corpus.mutation_weights.mutation_weight_cmp, 7);
4067    }
4068}