Skip to main content

forge/cmd/
coverage.rs

1use super::{
2    test::{ProjectPathsAwareFilter, TestArgs, TestExecutionOptions},
3    watch::WatchArgs,
4};
5use crate::coverage::{
6    BytecodeReporter, ContractId, CoverageAttributionReporter, CoverageReport, CoverageReporter,
7    CoverageSummaryReporter, DebugReporter, GapsReporter, ItemAnchors, LcovReporter,
8    ResolvedHitMap, ResolvedHitMaps,
9    analysis::{SourceAnalysis, SourceFiles},
10    anchors::{find_anchors, find_execution_anchors},
11};
12use alloy_json_abi::StateMutability;
13use alloy_primitives::{
14    Address, B256, Bytes, U256, keccak256,
15    map::{HashMap, HashSet},
16};
17use clap::{Parser, ValueHint};
18use eyre::Result;
19use foundry_cli::utils::{FoundryPathExt, LoadConfig, STATIC_FUZZ_SEED};
20use foundry_common::{
21    ContractsByArtifactBuilder, TestFilter, compile::ProjectCompiler, errors::convert_solar_errors,
22    version::SHORT_VERSION,
23};
24use foundry_compilers::{
25    Artifact, ArtifactId, Graph, Project, ProjectCompileOutput, ProjectPathsConfig,
26    VYPER_EXTENSIONS,
27    artifacts::{
28        CompactBytecode, CompactDeployedBytecode, Source,
29        sourcemap::{self, SourceMap},
30    },
31    buildinfo::SourceEdit,
32    cache::SOLIDITY_FILES_CACHE_FILENAME,
33    compilers::{
34        Language,
35        multi::{MultiCompilerLanguage, MultiCompilerParser},
36    },
37    error::SolcError,
38    utils::source_files_iter,
39};
40use foundry_config::{
41    Config, CoverageConfig, CoverageReportKind, InlineConfig, parse_lcov_version,
42};
43use foundry_evm::{core::ic::IcPcMap, opts::EvmOpts};
44use globset::{Glob, GlobSetBuilder};
45use rayon::prelude::*;
46use semver::Version;
47use std::{
48    collections::{BTreeMap, BTreeSet},
49    fs,
50    ops::Range,
51    path::{Path, PathBuf},
52    sync::Arc,
53};
54
55// Loads project's figment and merges the build cli arguments into it
56foundry_config::impl_figment_convert!(CoverageArgs, test);
57
58/// CLI arguments for `forge coverage`.
59///
60/// Most flags here have a corresponding `[profile.<name>.coverage]` config
61/// option in `foundry.toml`. CLI flags take precedence over config; the helper
62/// `resolve` merges them after the config is loaded.
63#[derive(Parser)]
64#[command(after_long_help = r#"Source attribution:
65  Coverage follows compiler source maps. Inherited modifier code is reported under the
66  source where the modifier is declared. Dependency sources are excluded by default;
67  use `--include-libs` to include their coverage.
68
69Compatibility:
70  `forge coverage` supports test filters and `--watch`, but not test-only output or
71  execution modes such as `--json`, `--junit`, `--list`, `--debug`, flame profiles,
72  symbolic artifact replay, showmap replay, brutalization, or mutation testing. Use
73  `--report lcov` for interoperable coverage data, `--report attribution` for
74  Foundry's per-test JSON attribution report, or `--report gaps` for a JSON list of
75  uncovered source items."#)]
76pub struct CoverageArgs {
77    /// The report type to use for coverage.
78    ///
79    /// This flag can be used multiple times. Falls back to the
80    /// `[profile.<name>.coverage] report` config value when not provided
81    /// (default: `summary`).
82    #[arg(long, value_enum)]
83    report: Vec<CoverageReportKind>,
84
85    /// The version of the LCOV "tracefile" format to use.
86    ///
87    /// Format: `MAJOR[.MINOR]`.
88    ///
89    /// Main differences:
90    /// - `1.x`: The original v1 format.
91    /// - `2.0`: Adds support for "line end" numbers for functions.
92    /// - `2.2`: Changes the format of functions.
93    ///
94    /// Falls back to the `[profile.<name>.coverage] lcov_version` config value
95    /// when not provided.
96    #[arg(long = "lcov-version", value_parser = parse_lcov_version)]
97    lcov_version_cli: Option<Version>,
98
99    /// Enable viaIR with minimum optimization
100    ///
101    /// This can fix most of the "stack too deep" errors while resulting a
102    /// relatively accurate source map.
103    #[arg(long)]
104    ir_minimum: bool,
105
106    /// Keep the project's optimizer and viaIR settings instead of disabling them.
107    ///
108    /// Optimized builds can miss or merge coverage items. Cannot be combined with
109    /// `--ir-minimum`, including when either is enabled in config, where it can only be turned
110    /// off. Falls back to the `[profile.<name>.coverage] keep_optimizer` config value.
111    #[arg(long)]
112    keep_optimizer: bool,
113
114    /// The path to output the report.
115    ///
116    /// Used only when a single file report is requested. If not specified, the
117    /// report will be stored in the root of the project.
118    #[arg(
119        long,
120        value_hint = ValueHint::FilePath,
121        value_name = "PATH"
122    )]
123    report_file: Option<PathBuf>,
124
125    /// Include dependency sources in the coverage report.
126    #[arg(long)]
127    include_libs: bool,
128
129    /// Whether to exclude tests from the coverage report.
130    #[arg(long)]
131    exclude_tests: bool,
132
133    #[command(flatten)]
134    test: TestArgs,
135}
136
137/// The coverage settings of a run: the CLI flags merged with the
138/// `[profile.<name>.coverage]` config values by [`CoverageArgs::resolve`].
139#[derive(Debug)]
140struct CoverageSettings {
141    /// The report types to generate. Never empty.
142    report: Vec<CoverageReportKind>,
143    /// The version of the LCOV "tracefile" format to use.
144    lcov_version: Version,
145    /// Whether to enable viaIR with minimum optimization.
146    ir_minimum: bool,
147    /// Whether to keep the project's optimizer and viaIR settings.
148    keep_optimizer: bool,
149    /// The path to output a single file report to.
150    report_file: Option<PathBuf>,
151    /// Whether to include dependency sources in the coverage report.
152    include_libs: bool,
153    /// Whether to exclude tests from the coverage report.
154    exclude_tests: bool,
155    /// Glob patterns of source files to exclude from the coverage report.
156    skip_files: Vec<String>,
157}
158
159impl CoverageSettings {
160    fn report_path(&self, root: &Path, default_file_name: &str) -> PathBuf {
161        let report_file =
162            (self.file_report_count() == 1).then_some(self.report_file.as_deref()).flatten();
163        root.join(report_file.unwrap_or_else(|| Path::new(default_file_name)))
164    }
165
166    fn file_report_count(&self) -> usize {
167        let has_lcov = self.report.iter().any(|kind| matches!(kind, CoverageReportKind::Lcov));
168        let has_attribution =
169            self.report.iter().any(|kind| matches!(kind, CoverageReportKind::Attribution));
170        let has_gaps = self.report.iter().any(|kind| matches!(kind, CoverageReportKind::Gaps));
171        usize::from(has_lcov) + usize::from(has_attribution) + usize::from(has_gaps)
172    }
173
174    /// The reporters that write the requested reports, except the attribution report, which
175    /// needs the test outcome.
176    fn reporters(&self, root: &Path) -> Vec<Box<dyn CoverageReporter>> {
177        self.report
178            .iter()
179            .filter_map(|report_kind| match report_kind {
180                CoverageReportKind::Summary => {
181                    Some(Box::<CoverageSummaryReporter>::default() as Box<dyn CoverageReporter>)
182                }
183                CoverageReportKind::Lcov => {
184                    let path = self.report_path(root, "lcov.info");
185                    Some(Box::new(LcovReporter::new(path, self.lcov_version.clone())))
186                }
187                CoverageReportKind::Bytecode => Some(Box::new(BytecodeReporter::new(
188                    root.to_path_buf(),
189                    root.join("bytecode-coverage"),
190                ))),
191                CoverageReportKind::Debug => Some(Box::new(DebugReporter)),
192                CoverageReportKind::Attribution => None,
193                CoverageReportKind::Gaps => {
194                    let path = self.report_path(root, "coverage-gaps.json");
195                    Some(Box::new(GapsReporter::new(root.to_path_buf(), path)))
196                }
197            })
198            .collect()
199    }
200}
201
202impl CoverageArgs {
203    pub(crate) fn ensure_mode_compatible(&self) -> Result<()> {
204        self.test.ensure_coverage_mode_compatible()?;
205        let settings = self.resolve(&self.load_config_no_warnings()?.coverage);
206        eyre::ensure!(
207            !(settings.ir_minimum && settings.keep_optimizer),
208            "`ir_minimum` (`--ir-minimum`) and `keep_optimizer` (`--keep-optimizer`) cannot both be enabled"
209        );
210        Ok(())
211    }
212
213    pub async fn run(self) -> Result<()> {
214        self.ensure_mode_compatible()?;
215
216        let (mut config, evm_opts) = self.load_config_and_evm_opts()?;
217
218        // install missing dependencies
219        self.install_missing_dependencies(&mut config)?;
220
221        // Default to a static fuzz seed so coverage reports are deterministic,
222        // but allow the user to override it via `--fuzz-seed` or `[fuzz] seed` in config.
223        if config.fuzz.seed.is_none() {
224            config.fuzz.seed = Some(U256::from_be_bytes(STATIC_FUZZ_SEED));
225        }
226
227        // Merge CLI args with `[profile.<name>.coverage]` config values. CLI
228        // flags take precedence; unset CLI flags fall back to the config.
229        let settings = self.resolve(&config.coverage);
230        let filter = self.test.filter(&config)?;
231
232        let (paths, mut output) = {
233            let (project, output) = Self::build(&config, &filter, &settings)?;
234            (project.paths, output)
235        };
236
237        if settings.report_file.is_some() && settings.file_report_count() > 1 {
238            sh_warn!(
239                "`--report-file` is ignored when multiple file reports are requested; \
240                 each report will use its default output path"
241            )?;
242        }
243
244        let mut reporters = settings.reporters(&paths.root);
245
246        sh_println!("Analysing contracts...")?;
247        let report = Self::prepare(&settings, &reporters, &paths, &mut output)?;
248
249        sh_println!("Running tests...")?;
250        self.collect(
251            &settings,
252            &mut reporters,
253            &paths.root,
254            &output,
255            report,
256            config,
257            evm_opts,
258            filter,
259        )
260        .await
261    }
262
263    /// Merges `[profile.<name>.coverage]` config values with the CLI flags. CLI
264    /// flags that are set win; unset/false flags inherit from `config`.
265    ///
266    /// In the result:
267    /// - `report` is non-empty.
268    /// - boolean flags reflect `cli || config` (CLI cannot disable a flag set to `true` in config;
269    ///   this matches the pre-existing flag-only semantics where booleans defaulted to `false`).
270    fn resolve(&self, config: &CoverageConfig) -> CoverageSettings {
271        CoverageSettings {
272            report: if self.report.is_empty() {
273                config.report.clone()
274            } else {
275                self.report.clone()
276            },
277            lcov_version: self
278                .lcov_version_cli
279                .clone()
280                .unwrap_or_else(|| config.lcov_version.clone()),
281            ir_minimum: self.ir_minimum || config.ir_minimum,
282            keep_optimizer: self.keep_optimizer || config.keep_optimizer,
283            report_file: self.report_file.clone().or_else(|| config.report_file.clone()),
284            include_libs: self.include_libs || config.include_libs,
285            exclude_tests: self.exclude_tests || config.exclude_tests,
286            // Glob filters are additive — there's no CLI flag for these, so always
287            // take from config.
288            skip_files: config.skip_files.clone(),
289        }
290    }
291
292    /// Builds the project.
293    fn build(
294        config: &Config,
295        filter: &ProjectPathsAwareFilter,
296        settings: &CoverageSettings,
297    ) -> Result<(Project, ProjectCompileOutput)> {
298        let mut project = config.ephemeral_project()?;
299        // A contended or unavailable cache retains ephemeral compilation. Keep the lock until
300        // artifacts and build contexts have been loaded or published together.
301        let cache = (config.cache && !config.deny.warnings())
302            .then(|| config.coverage_cache_path())
303            .flatten()
304            .and_then(|path| {
305                fs::create_dir_all(path.parent()?).ok()?;
306                let lock = Config::lock_coverage_cache(&path).ok()?;
307                match fs::create_dir(&path) {
308                    Ok(()) => {
309                        if fs::File::create_new(path.join(Config::COVERAGE_CACHE_MARKER)).is_err() {
310                            let _ = fs::remove_dir(&path);
311                            return None;
312                        }
313                    }
314                    Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
315                        if !path.join(Config::COVERAGE_CACHE_MARKER).is_file() {
316                            return None;
317                        }
318                    }
319                    Err(_) => return None,
320                }
321                Some((path, lock))
322            });
323        let original_paths = project.paths.clone();
324        if let Some((path, _)) = &cache {
325            project.cached = true;
326            project.no_artifacts = false;
327            project.paths.cache = path.join(SOLIDITY_FILES_CACHE_FILENAME);
328            project.paths.artifacts = path.join("artifacts");
329            project.paths.build_infos = path.join("build-info");
330            project.paths.slash_paths();
331        }
332
333        let solar = config.is_solar();
334        if settings.ir_minimum && solar {
335            sh_warn!("`--ir-minimum` has no effect with Solar, so coverage runs unoptimized.")?;
336        } else if settings.ir_minimum {
337            sh_warn!(
338                "`--ir-minimum` enables `viaIR` with minimum optimization, \
339                 which can result in inaccurate source mappings.\n\
340                 Only use this flag as a workaround if you are experiencing \"stack too deep\" errors.\n\
341                 Note that `viaIR` is production ready since Solidity 0.8.13 and above.\n\
342                 See more: https://book.getfoundry.sh/guides/best-practices/stack-too-deep"
343            )?;
344        } else if settings.keep_optimizer {
345            sh_warn!(
346                "`--keep-optimizer` keeps the optimizer and `viaIR` settings, so coverage can miss \
347                 or merge items that the optimizer removes or combines."
348            )?;
349        } else {
350            sh_warn!(
351                "optimizer settings and `viaIR` have been disabled for accurate coverage reports.\n\
352                 If you encounter \"stack too deep\" errors, consider using `--ir-minimum` which \
353                 enables `viaIR` with minimum optimization resolving most of the errors.\n\
354                 See more: https://book.getfoundry.sh/guides/best-practices/stack-too-deep"
355            )?;
356        }
357
358        if !settings.keep_optimizer {
359            config.disable_optimizations(&mut project, settings.ir_minimum && !solar);
360        }
361
362        let files = (filter.args().path_pattern.is_some()
363            || filter.args().path_pattern_inverse.is_some())
364        .then(|| {
365            source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS)
366                .chain(
367                    source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS)
368                        // Preserve path-filter behavior for conventional test files while still
369                        // scanning non-test fixtures under the test root.
370                        .filter(|path| !path.is_sol_test() || filter.matches_path(path)),
371                )
372                // Coverage reports include scripts even though they are not test targets.
373                .chain(source_files_iter(&config.script, MultiCompilerLanguage::FILE_EXTENSIONS))
374                .collect::<BTreeSet<_>>()
375        });
376        let compile = |project: &Project| {
377            let mut compiler = ProjectCompiler::new()
378                .allow_linked_libraries(config.allow_linked_libraries)
379                .external_compilers(config)
380                .external_artifacts(false)
381                .dynamic_test_linking(config.dynamic_test_linking);
382            if let Some(files) = &files {
383                compiler = compiler.files(files.iter().cloned());
384            }
385            compiler.compile(project)
386        };
387        // Coverage needs complete build contexts, including sources without contract artifacts.
388        // Invalidate the owned cache as a whole on edits so source IDs, artifact names, and
389        // build-info files all belong to the same compilation.
390        let cached_output = (|| -> Result<Option<ProjectCompileOutput>> {
391            let Some((path, _)) = &cache else { return Ok(None) };
392            let mut sources = if let Some(files) = &files
393                && !files.is_empty()
394            {
395                Source::read_all(files)?
396            } else {
397                project.paths.read_input_files()?
398            };
399            if let Some(filter) = &project.sparse_output {
400                sources.retain(|path, _| filter.is_match(path));
401            }
402            let graph = Graph::<MultiCompilerParser>::resolve_sources(&project.paths, sources)?;
403            let resolved = graph.into_sources_by_version(&project)?;
404            let mut jobs = resolved
405                .sources
406                .iter()
407                .flat_map(|(language, jobs)| {
408                    jobs.iter().map(move |(version, sources, (profile, settings))| {
409                        let sources = sources
410                            .iter()
411                            .map(|(path, source)| {
412                                (path, source.content_hash(), source.kind.is_dirty())
413                            })
414                            .collect::<Vec<_>>();
415                        serde_json::to_value((language, version, profile, settings, sources))
416                    })
417                })
418                .collect::<Result<Vec<_>, _>>()?;
419            jobs.sort_unstable_by_key(serde_json::Value::to_string);
420            let primary_profiles = resolved.primary_profiles.iter().collect::<BTreeMap<_, _>>();
421            let mut identity = serde_json::to_value((
422                SHORT_VERSION,
423                &project.paths,
424                (&config.solc, &config.vyper, &config.extra_args),
425                (&config.extra_output, &config.extra_output_files),
426                config.dynamic_test_linking,
427                jobs,
428                primary_profiles,
429            ))?;
430            identity.sort_all_objects();
431            let fingerprint = keccak256(serde_json::to_vec(&identity)?).to_string();
432            let marker = path.join(Config::COVERAGE_CACHE_MARKER);
433            if fs::read_to_string(&marker).ok().as_deref() != Some(&fingerprint) {
434                // Retain ownership even if compilation fails before the new fingerprint is saved.
435                fs::write(&marker, "")?;
436                for entry in fs::read_dir(path)? {
437                    let entry = entry?;
438                    if entry.file_name() == Config::COVERAGE_CACHE_MARKER {
439                        continue;
440                    }
441                    if entry.file_type()?.is_dir() {
442                        fs::remove_dir_all(entry.path())?;
443                    } else {
444                        fs::remove_file(entry.path())?;
445                    }
446                }
447            }
448            let output = compile(&project)?;
449            // Compiler builds with no artifacts can be pruned from the cache. Coverage still
450            // reports their free functions, so recover their source IDs with a fresh compilation.
451            let mapped_sources = output
452                .builds()
453                .flat_map(|(_, build)| build.source_id_to_path.values().map(PathBuf::as_path))
454                .collect::<HashSet<_>>();
455            if output
456                .graph()
457                .files()
458                .any(|idx| !mapped_sources.contains(output.graph().node_path(idx)))
459            {
460                return Ok(None);
461            }
462            // Publication is optional once the compiler has returned a complete output.
463            if let Err(err) = fs::write(marker, fingerprint) {
464                debug!(%err, "failed to publish coverage cache fingerprint");
465            }
466            Ok(Some(output))
467        })();
468        let output = match cached_output {
469            Ok(Some(output)) => output,
470            Err(err)
471                if !err.chain().any(|cause| {
472                    cause.is::<std::io::Error>()
473                        || matches!(cause.downcast_ref(), Some(SolcError::Io(_)))
474                }) =>
475            {
476                return Err(err);
477            }
478            result => {
479                if let Err(err) = result {
480                    debug!(%err, "coverage cache unavailable; compiling without persistence");
481                }
482                project.cached = false;
483                project.no_artifacts = true;
484                project.paths = original_paths;
485                compile(&project)?
486            }
487        };
488        let output = output.with_stripped_file_prefixes(project.root());
489
490        Ok((project, output))
491    }
492
493    /// Builds the coverage report.
494    #[instrument(name = "Coverage::prepare", skip_all)]
495    fn prepare(
496        settings: &CoverageSettings,
497        reporters: &[Box<dyn CoverageReporter>],
498        project_paths: &ProjectPathsConfig,
499        output: &mut ProjectCompileOutput,
500    ) -> Result<CoverageReport> {
501        let mut report = CoverageReport::default();
502
503        output.parser_mut().solc_mut().compiler_mut().enter_mut(|compiler| {
504            if compiler.gcx().stage() < Some(solar::config::CompilerStage::Lowering) {
505                let _ = compiler.lower_asts();
506            }
507            convert_solar_errors(compiler.dcx())
508        })?;
509        let output = &*output;
510
511        // Collect source files.
512        let mut sources_by_build = HashMap::<String, SourceFiles>::default();
513        for (build_id, build) in output.builds() {
514            for (source_id, path) in &build.source_id_to_path {
515                if output.graph().get_parsed_source(path).is_none()
516                    || path
517                        .extension()
518                        .and_then(|s| s.to_str())
519                        .is_some_and(|ext| VYPER_EXTENSIONS.contains(&ext))
520                {
521                    continue;
522                }
523                let path = path.strip_prefix(&project_paths.root).unwrap_or(path);
524                report.add_source(build_id.clone(), *source_id as usize, path.to_path_buf());
525
526                if (!settings.include_libs && project_paths.has_library_ancestor(path))
527                    || (settings.exclude_tests && project_paths.is_test(path))
528                {
529                    continue;
530                }
531
532                sources_by_build
533                    .entry(build_id.clone())
534                    .or_default()
535                    .sources
536                    .insert(*source_id, project_paths.root.join(path));
537            }
538        }
539
540        // Get source maps and bytecodes.
541        let source_edits = output
542            .builds()
543            .map(|(build_id, build)| (build_id.as_str(), &build.source_edits))
544            .collect::<HashMap<_, _>>();
545        let artifacts: Vec<ArtifactData> = output
546            .artifact_ids()
547            .par_bridge() // This parses source maps, so we want to run it in parallel.
548            .filter_map(|(id, artifact)| {
549                let source_id = report.get_source_id(&id.build_id, &id.source)?;
550                let edits = source_edits.get(id.build_id.as_str()).copied();
551                ArtifactData::new(&id, source_id, artifact, edits)
552            })
553            .collect();
554
555        // Add coverage items.
556        for (build_id, sources) in &sources_by_build {
557            let source_analysis = SourceAnalysis::new(sources, output)?;
558            let anchors = artifacts
559                .par_iter()
560                .filter(|artifact| artifact.contract_id.build_id == *build_id)
561                .map(|artifact| {
562                    let creation_code_anchors = artifact.creation.find_anchors(&source_analysis);
563                    let deployed_code_anchors = artifact.deployed.find_anchors(&source_analysis);
564                    (artifact.contract_id.clone(), (creation_code_anchors, deployed_code_anchors))
565                })
566                .collect_vec_list();
567            report.add_anchors(anchors.into_iter().flatten());
568            for artifact in
569                artifacts.iter().filter(|artifact| artifact.contract_id.build_id == *build_id)
570            {
571                let execution_anchors = find_execution_anchors(
572                    artifact.contract_id.source_id as u32,
573                    &artifact.contract_id.contract_name,
574                    &source_analysis,
575                );
576                report.add_execution_anchors(
577                    artifact.contract_id.clone(),
578                    execution_anchors,
579                    artifact.function_selectors.iter().copied(),
580                    artifact.has_receive,
581                    artifact.fallback_payable,
582                );
583            }
584            report.add_analysis(build_id.clone(), source_analysis);
585        }
586
587        if reporters.iter().any(|reporter| reporter.needs_source_maps()) {
588            report.add_source_maps(artifacts.into_iter().map(|artifact| {
589                (artifact.contract_id, (artifact.creation.source_map, artifact.deployed.source_map))
590            }));
591        }
592
593        Ok(report)
594    }
595
596    /// Runs tests, collects coverage data and generates the final report.
597    #[instrument(name = "Coverage::collect", skip_all)]
598    #[allow(clippy::too_many_arguments)]
599    async fn collect(
600        mut self,
601        settings: &CoverageSettings,
602        reporters: &mut [Box<dyn CoverageReporter>],
603        project_root: &Path,
604        output: &ProjectCompileOutput,
605        mut report: CoverageReport,
606        config: Config,
607        evm_opts: EvmOpts,
608        filter: ProjectPathsAwareFilter,
609    ) -> Result<()> {
610        let inline_config = Arc::new(InlineConfig::new_parsed(output, &config)?);
611        let outcome = self
612            .test
613            .run_tests(
614                project_root,
615                config,
616                evm_opts,
617                output,
618                &filter,
619                TestExecutionOptions::coverage(inline_config),
620            )
621            .await?;
622
623        let known_contracts = outcome.known_contracts.as_ref().unwrap();
624        // Linking removes library references. Match runtime against the compiler artifacts to
625        // retain those offsets, while keeping linked bytecode for creation matching.
626        let runtime_contracts = ContractsByArtifactBuilder::new(
627            output.artifact_ids().map(|(id, artifact)| (id, artifact.into())),
628        )
629        .build();
630        let mut resolved_hit_maps = ResolvedHitMaps::default();
631        let mut unresolved_hit_maps = HashSet::<B256>::default();
632
633        // Add hit data to the coverage report
634        for suite in outcome.results.values() {
635            for result in suite.test_results.values() {
636                let Some(hit_maps) = result.line_coverage.as_ref() else { continue };
637
638                for (code_hash, map) in &hit_maps.0 {
639                    if let Some(resolved) = resolved_hit_maps.get(code_hash) {
640                        report.add_hit_map(
641                            &resolved.contract_id,
642                            map,
643                            resolved.is_deployed_code,
644                        )?;
645                        continue;
646                    }
647                    if unresolved_hit_maps.contains(code_hash) {
648                        continue;
649                    }
650
651                    // Only exact matches are credited: source maps of a merely similar artifact
652                    // would attribute hits to code that never ran. Creation code may be followed
653                    // by any constructor data, which leaves the artifact's instructions unchanged.
654                    let Some((artifact_id, is_deployed_code)) = runtime_contracts
655                        .find_by_deployed_code_exact(map.bytecode())
656                        .map(|(id, _)| (id, true))
657                        .or_else(|| {
658                            known_contracts
659                                .iter()
660                                .find(|(_, contract)| {
661                                    contract
662                                        .bytecode()
663                                        .is_some_and(|code| map.bytecode().starts_with(code))
664                                })
665                                .map(|(id, _)| (id, false))
666                        })
667                    else {
668                        if let Some((similar, kind)) = known_contracts
669                            .find_by_deployed_code(map.bytecode())
670                            .map(|(id, _)| (id, "runtime"))
671                            .or_else(|| {
672                                known_contracts
673                                    .find_by_creation_code(map.bytecode())
674                                    .map(|(id, _)| (id, "creation"))
675                            })
676                        {
677                            sh_warn!(
678                                "excluding executed {kind} code from coverage: it resembles `{}` but does not match it exactly",
679                                similar.identifier()
680                            )?;
681                        }
682                        unresolved_hit_maps.insert(*code_hash);
683                        continue;
684                    };
685
686                    let Some(source_id) =
687                        report.get_source_id(&artifact_id.build_id, &artifact_id.source)
688                    else {
689                        continue;
690                    };
691                    let contract_id = ContractId {
692                        version: artifact_id.version.clone(),
693                        build_id: artifact_id.build_id.clone(),
694                        source_id,
695                        contract_name: artifact_id.name.as_str().into(),
696                    };
697
698                    report.add_hit_map(&contract_id, map, is_deployed_code)?;
699
700                    resolved_hit_maps
701                        .entry(*code_hash)
702                        .or_insert(ResolvedHitMap { contract_id, is_deployed_code });
703                }
704            }
705        }
706
707        // Filter out ignored sources from the report.
708        let file_root = filter.paths().root.as_path();
709        if let Some(not_re) = &filter.args().coverage_pattern_inverse {
710            report.retain_sources(|path: &Path| {
711                let path = path.strip_prefix(file_root).unwrap_or(path);
712                !not_re.is_match(&path.to_string_lossy())
713            });
714        }
715        if !settings.skip_files.is_empty() {
716            let mut builder = GlobSetBuilder::new();
717            for pattern in &settings.skip_files {
718                let glob = Glob::new(pattern).map_err(|e| {
719                    eyre::eyre!("invalid glob in coverage.skip_files: '{pattern}': {e}")
720                })?;
721                builder.add(glob);
722            }
723            let set = builder
724                .build()
725                .map_err(|e| eyre::eyre!("failed to build coverage.skip_files glob set: {e}"))?;
726            report.retain_sources(|path: &Path| {
727                let path = path.strip_prefix(file_root).unwrap_or(path);
728                !set.is_match(path)
729            });
730        }
731
732        // Output final reports.
733        Self::report(reporters, &report)?;
734
735        if settings.report.iter().any(|kind| matches!(kind, CoverageReportKind::Attribution)) {
736            let reporter = CoverageAttributionReporter::new(
737                settings.report_path(project_root, "coverage-attribution.json"),
738            );
739            reporter.report(&report, &outcome, &resolved_hit_maps)?;
740        }
741
742        // Check for test failures after generating coverage report.
743        // This ensures coverage data is written even when tests fail.
744        outcome.ensure_ok(false)?;
745
746        Ok(())
747    }
748
749    #[instrument(name = "Coverage::report", skip_all)]
750    fn report(reporters: &mut [Box<dyn CoverageReporter>], report: &CoverageReport) -> Result<()> {
751        for reporter in reporters {
752            let _guard = debug_span!("reporter.report", kind=%reporter.name()).entered();
753            reporter.report(report)?;
754        }
755        Ok(())
756    }
757
758    pub const fn is_watch(&self) -> bool {
759        self.test.is_watch()
760    }
761
762    pub const fn watch(&self) -> &WatchArgs {
763        &self.test.watch
764    }
765}
766
767/// Helper function that will link references in unlinked bytecode to the 0 address.
768///
769/// This is needed in order to analyze the bytecode for contracts that use libraries.
770fn dummy_link_bytecode(mut obj: CompactBytecode) -> Option<Bytes> {
771    let link_references = obj.link_references.clone();
772    for (file, libraries) in link_references {
773        for library in libraries.keys() {
774            obj.link(&file, library, Address::ZERO);
775        }
776    }
777
778    obj.object.resolve();
779    obj.object.into_bytes()
780}
781
782/// Helper function that will link references in unlinked bytecode to the 0 address.
783///
784/// This is needed in order to analyze the bytecode for contracts that use libraries.
785fn dummy_link_deployed_bytecode(obj: CompactDeployedBytecode) -> Option<Bytes> {
786    obj.bytecode.and_then(dummy_link_bytecode)
787}
788
789pub struct ArtifactData {
790    pub contract_id: ContractId,
791    pub creation: BytecodeData,
792    pub deployed: BytecodeData,
793    pub function_selectors: Vec<[u8; 4]>,
794    pub has_receive: bool,
795    pub fallback_payable: bool,
796}
797
798impl ArtifactData {
799    pub fn new(
800        id: &ArtifactId,
801        source_id: usize,
802        artifact: &impl Artifact,
803        source_edits: Option<&BTreeMap<u32, Vec<SourceEdit>>>,
804    ) -> Option<Self> {
805        let abi = artifact.get_abi();
806        let function_selectors = abi
807            .as_ref()
808            .map(|abi| abi.functions().map(|function| function.selector().into()).collect())
809            .unwrap_or_default();
810        let has_receive = abi.as_ref().is_some_and(|abi| abi.receive.is_some());
811        let fallback_payable = abi
812            .as_ref()
813            .and_then(|abi| abi.fallback)
814            .is_some_and(|fallback| fallback.state_mutability == StateMutability::Payable);
815        Some(Self {
816            contract_id: ContractId {
817                version: id.version.clone(),
818                build_id: id.build_id.clone(),
819                source_id,
820                contract_name: id.name.as_str().into(),
821            },
822            creation: BytecodeData::new(
823                to_original_source_map(artifact.get_source_map()?.ok()?, source_edits),
824                artifact
825                    .get_bytecode()
826                    .and_then(|bytecode| dummy_link_bytecode(bytecode.into_owned()))?,
827            ),
828            deployed: BytecodeData::new(
829                to_original_source_map(artifact.get_source_map_deployed()?.ok()?, source_edits),
830                artifact
831                    .get_deployed_bytecode()
832                    .and_then(|bytecode| dummy_link_deployed_bytecode(bytecode.into_owned()))?,
833            ),
834            function_selectors,
835            has_receive,
836            fallback_payable,
837        })
838    }
839}
840
841/// Maps the ranges of a source map from the sources the compiler read back to the sources on
842/// disk, which coverage items refer to.
843///
844/// Preprocessing, such as dynamic test linking, rewrites sources before compilation, so the
845/// compiler reports offsets in the edited text. A range inside a replacement maps to the whole
846/// replaced range.
847fn to_original_source_map(
848    mut source_map: SourceMap,
849    source_edits: Option<&BTreeMap<u32, Vec<SourceEdit>>>,
850) -> SourceMap {
851    let Some(source_edits) = source_edits else { return source_map };
852    for element in &mut source_map {
853        let Some(edits) = element.index().and_then(|source| source_edits.get(&source)) else {
854            continue;
855        };
856        let offset = element.offset() as usize;
857        let length = element.length() as usize;
858        let (start, end) = original_range(edits, offset..offset + length);
859        if (start, end) == (offset, offset + length) {
860            continue;
861        }
862        // Source maps have no setters, so rebuild the element from its textual form.
863        let mapped = format!(
864            "{start}:{}:{}:{}:{}",
865            end - start,
866            element.index_i32(),
867            element.jump(),
868            element.modifier_depth()
869        );
870        *element = sourcemap::parse(&mapped)
871            .ok()
872            .and_then(|map| map.into_iter().next())
873            .expect("source element should round-trip through its textual form");
874    }
875    source_map
876}
877
878/// Maps a byte range of an edited source back to the original source.
879///
880/// `edits` must be sorted by start offset.
881fn original_range(edits: &[SourceEdit], range: Range<usize>) -> (usize, usize) {
882    let start = SourceEdit::original_offset(edits, range.start);
883    let mut shift = 0isize;
884    for edit in edits {
885        let edited_start = edit.start.saturating_add_signed(shift);
886        if range.end <= edited_start {
887            break;
888        }
889        if range.end < edited_start + edit.len {
890            return (start, edit.end);
891        }
892        shift += edit.len as isize - (edit.end - edit.start) as isize;
893    }
894    (start, range.end.saturating_add_signed(-shift).max(start))
895}
896
897pub struct BytecodeData {
898    source_map: SourceMap,
899    bytecode: Bytes,
900    /// The instruction counter to program counter mapping.
901    ///
902    /// The source maps are indexed by *instruction counters*, which are the indexes of
903    /// instructions in the bytecode *minus any push bytes*.
904    ///
905    /// Since our line coverage inspector collects hit data using program counters, the anchors
906    /// also need to be based on program counters.
907    ic_pc_map: IcPcMap,
908}
909
910impl BytecodeData {
911    fn new(source_map: SourceMap, bytecode: Bytes) -> Self {
912        let ic_pc_map = IcPcMap::new(&bytecode);
913        Self { source_map, bytecode, ic_pc_map }
914    }
915
916    pub fn find_anchors(&self, source_analysis: &SourceAnalysis) -> ItemAnchors {
917        find_anchors(&self.bytecode, &self.source_map, &self.ic_pc_map, source_analysis)
918    }
919}
920
921#[cfg(test)]
922mod tests {
923    use super::*;
924
925    #[test]
926    fn lcov_version() {
927        assert_eq!(parse_lcov_version("0").unwrap(), Version::new(0, 0, 0));
928        assert_eq!(parse_lcov_version("1").unwrap(), Version::new(1, 0, 0));
929        assert_eq!(parse_lcov_version("1.0").unwrap(), Version::new(1, 0, 0));
930        assert_eq!(parse_lcov_version("1.1").unwrap(), Version::new(1, 1, 0));
931        assert_eq!(parse_lcov_version("1.11").unwrap(), Version::new(1, 11, 0));
932    }
933
934    #[test]
935    fn resolve_lcov_version_uses_config_when_cli_absent() {
936        let args = CoverageArgs::parse_from(["coverage"]);
937        let config = CoverageConfig { lcov_version: Version::new(2, 2, 0), ..Default::default() };
938
939        let settings = args.resolve(&config);
940
941        assert_eq!(settings.lcov_version, Version::new(2, 2, 0));
942    }
943
944    #[test]
945    fn resolve_lcov_version_keeps_explicit_cli_default() {
946        let args = CoverageArgs::parse_from(["coverage", "--lcov-version", "1"]);
947        let config = CoverageConfig { lcov_version: Version::new(2, 2, 0), ..Default::default() };
948
949        let settings = args.resolve(&config);
950
951        assert_eq!(settings.lcov_version, Version::new(1, 0, 0));
952    }
953
954    #[test]
955    fn resolve_lcov_version_keeps_explicit_cli_value() {
956        let args = CoverageArgs::parse_from(["coverage", "--lcov-version", "2"]);
957        let config = CoverageConfig { lcov_version: Version::new(2, 2, 0), ..Default::default() };
958
959        let settings = args.resolve(&config);
960
961        assert_eq!(settings.lcov_version, Version::new(2, 0, 0));
962    }
963
964    #[test]
965    fn maps_edited_ranges_to_original() {
966        // "new C()" at 10..17 grows to 30 bytes, 50..60 is removed, and 5 bytes are inserted at
967        // 100.
968        let edits = [
969            SourceEdit { start: 10, end: 17, len: 30 },
970            SourceEdit { start: 50, end: 60, len: 0 },
971            SourceEdit { start: 100, end: 100, len: 5 },
972        ];
973        for (edited, original) in [
974            // Before the first edit.
975            (0..10, (0, 10)),
976            // The replacement itself, and ranges inside it, map to the replaced range.
977            (10..40, (10, 17)),
978            (15..20, (10, 17)),
979            (39..40, (10, 17)),
980            // A range that straddles one boundary of the replacement.
981            (5..20, (5, 17)),
982            (20..45, (10, 22)),
983            // Containing the replacement.
984            (5..45, (5, 22)),
985            // After the replacement, before and around the removal.
986            (40..43, (17, 20)),
987            (43..90, (20, 77)),
988            (90..95, (77, 82)),
989            // Around the insertion, which starts at 113 in the edited source.
990            (110..113, (97, 100)),
991            (113..118, (100, 100)),
992            (115..116, (100, 100)),
993            (118..120, (100, 102)),
994            // Empty ranges.
995            (10..10, (10, 10)),
996            (40..40, (17, 17)),
997            (12..12, (10, 17)),
998        ] {
999            assert_eq!(original_range(&edits, edited.clone()), original, "{edited:?}");
1000        }
1001        assert_eq!(original_range(&[], 7..9), (7, 9));
1002    }
1003
1004    #[test]
1005    fn converts_source_map_per_source() {
1006        let edits = BTreeMap::from([(1, vec![SourceEdit { start: 10, end: 17, len: 30 }])]);
1007        let map = sourcemap::parse(
1008            "0:5:1:-:0;45:3:1:i:2;12:2:1:o:1;45:3:0:-:0;-1:0:-1:-:0;40:0:1:-:0;12:0:1:o:0",
1009        )
1010        .unwrap();
1011        // Elements of unedited sources and without a source are unchanged.
1012        assert_eq!(to_original_source_map(map.clone(), None), map);
1013        let converted = to_original_source_map(map, Some(&edits));
1014        assert_eq!(
1015            converted,
1016            sourcemap::parse(
1017                "0:5:1:-:0;22:3:1:i:2;10:7:1:o:1;45:3:0:-:0;-1:0:-1:-:0;17:0:1:-:0;10:7:1:o:0"
1018            )
1019            .unwrap()
1020        );
1021    }
1022}