Skip to main content

forge/cmd/
coverage.rs

1use super::{install, test::TestArgs, watch::WatchArgs};
2use crate::coverage::{
3    BytecodeReporter, ContractId, CoverageReport, CoverageReporter, CoverageSummaryReporter,
4    DebugReporter, ItemAnchor, LcovReporter,
5    analysis::{SourceAnalysis, SourceFiles},
6    anchors::find_anchors,
7};
8use alloy_primitives::{Address, Bytes, U256, map::HashMap};
9use clap::{Parser, ValueEnum, ValueHint};
10use eyre::Result;
11use foundry_cli::utils::{LoadConfig, STATIC_FUZZ_SEED};
12use foundry_common::{compile::ProjectCompiler, errors::convert_solar_errors};
13use foundry_compilers::{
14    Artifact, ArtifactId, Project, ProjectCompileOutput, ProjectPathsConfig, VYPER_EXTENSIONS,
15    artifacts::{CompactBytecode, CompactDeployedBytecode, sourcemap::SourceMap},
16};
17use foundry_config::Config;
18use foundry_evm::{core::ic::IcPcMap, opts::EvmOpts};
19use rayon::prelude::*;
20use semver::{Version, VersionReq};
21use std::path::{Path, PathBuf};
22
23// Loads project's figment and merges the build cli arguments into it
24foundry_config::impl_figment_convert!(CoverageArgs, test);
25
26/// CLI arguments for `forge coverage`.
27#[derive(Parser)]
28pub struct CoverageArgs {
29    /// The report type to use for coverage.
30    ///
31    /// This flag can be used multiple times.
32    #[arg(long, value_enum, default_value = "summary")]
33    report: Vec<CoverageReportKind>,
34
35    /// The version of the LCOV "tracefile" format to use.
36    ///
37    /// Format: `MAJOR[.MINOR]`.
38    ///
39    /// Main differences:
40    /// - `1.x`: The original v1 format.
41    /// - `2.0`: Adds support for "line end" numbers for functions.
42    /// - `2.2`: Changes the format of functions.
43    #[arg(long, default_value = "1", value_parser = parse_lcov_version)]
44    lcov_version: Version,
45
46    /// Enable viaIR with minimum optimization
47    ///
48    /// This can fix most of the "stack too deep" errors while resulting a
49    /// relatively accurate source map.
50    #[arg(long)]
51    ir_minimum: bool,
52
53    /// The path to output the report.
54    ///
55    /// If not specified, the report will be stored in the root of the project.
56    #[arg(
57        long,
58        short,
59        value_hint = ValueHint::FilePath,
60        value_name = "PATH"
61    )]
62    report_file: Option<PathBuf>,
63
64    /// Whether to include libraries in the coverage report.
65    #[arg(long)]
66    include_libs: bool,
67
68    /// Whether to exclude tests from the coverage report.
69    #[arg(long)]
70    exclude_tests: bool,
71
72    /// The coverage reporters to use. Constructed from the other fields.
73    #[arg(skip)]
74    reporters: Vec<Box<dyn CoverageReporter>>,
75
76    #[command(flatten)]
77    test: TestArgs,
78}
79
80impl CoverageArgs {
81    pub async fn run(mut self) -> Result<()> {
82        let (mut config, evm_opts) = self.load_config_and_evm_opts()?;
83
84        // install missing dependencies
85        if install::install_missing_dependencies(&mut config).await && config.auto_detect_remappings
86        {
87            // need to re-configure here to also catch additional remappings
88            config = self.load_config()?;
89        }
90
91        // Set fuzz seed so coverage reports are deterministic
92        config.fuzz.seed = Some(U256::from_be_bytes(STATIC_FUZZ_SEED));
93
94        let (paths, mut output) = {
95            let (project, output) = self.build(&config)?;
96            (project.paths, output)
97        };
98
99        self.populate_reporters(&paths.root);
100
101        sh_println!("Analysing contracts...")?;
102        let report = self.prepare(&paths, &mut output)?;
103
104        sh_println!("Running tests...")?;
105        self.collect(&paths.root, &output, report, config, evm_opts).await
106    }
107
108    fn populate_reporters(&mut self, root: &Path) {
109        self.reporters = self
110            .report
111            .iter()
112            .map(|report_kind| match report_kind {
113                CoverageReportKind::Summary => {
114                    Box::<CoverageSummaryReporter>::default() as Box<dyn CoverageReporter>
115                }
116                CoverageReportKind::Lcov => {
117                    let path =
118                        root.join(self.report_file.as_deref().unwrap_or("lcov.info".as_ref()));
119                    Box::new(LcovReporter::new(path, self.lcov_version.clone()))
120                }
121                CoverageReportKind::Bytecode => Box::new(BytecodeReporter::new(
122                    root.to_path_buf(),
123                    root.join("bytecode-coverage"),
124                )),
125                CoverageReportKind::Debug => Box::new(DebugReporter),
126            })
127            .collect::<Vec<_>>();
128    }
129
130    /// Builds the project.
131    fn build(&self, config: &Config) -> Result<(Project, ProjectCompileOutput)> {
132        let mut project = config.ephemeral_project()?;
133
134        if self.ir_minimum {
135            sh_warn!(
136                "`--ir-minimum` enables `viaIR` with minimum optimization, \
137                 which can result in inaccurate source mappings.\n\
138                 Only use this flag as a workaround if you are experiencing \"stack too deep\" errors.\n\
139                 Note that `viaIR` is production ready since Solidity 0.8.13 and above.\n\
140                 See more: https://book.getfoundry.sh/guides/best-practices/stack-too-deep"
141            )?;
142        } else {
143            sh_warn!(
144                "optimizer settings and `viaIR` have been disabled for accurate coverage reports.\n\
145                 If you encounter \"stack too deep\" errors, consider using `--ir-minimum` which \
146                 enables `viaIR` with minimum optimization resolving most of the errors.\n\
147                 See more: https://book.getfoundry.sh/guides/best-practices/stack-too-deep"
148            )?;
149        }
150
151        config.disable_optimizations(&mut project, self.ir_minimum);
152
153        let output = ProjectCompiler::default()
154            .compile(&project)?
155            .with_stripped_file_prefixes(project.root());
156
157        Ok((project, output))
158    }
159
160    /// Builds the coverage report.
161    #[instrument(name = "Coverage::prepare", skip_all)]
162    fn prepare(
163        &self,
164        project_paths: &ProjectPathsConfig,
165        output: &mut ProjectCompileOutput,
166    ) -> Result<CoverageReport> {
167        let mut report = CoverageReport::default();
168
169        output.parser_mut().solc_mut().compiler_mut().enter_mut(|compiler| {
170            if compiler.gcx().stage() < Some(solar::config::CompilerStage::Lowering) {
171                let _ = compiler.lower_asts();
172            }
173            convert_solar_errors(compiler.dcx())
174        })?;
175        let output = &*output;
176
177        // Collect source files.
178        let mut versioned_sources = HashMap::<Version, SourceFiles>::default();
179        for (path, source_file, version) in output.output().sources.sources_with_version() {
180            // Filter out vyper sources.
181            if path
182                .extension()
183                .and_then(|s| s.to_str())
184                .is_some_and(|ext| VYPER_EXTENSIONS.contains(&ext))
185            {
186                continue;
187            }
188
189            report.add_source(version.clone(), source_file.id as usize, path.clone());
190
191            // Filter out libs dependencies and tests.
192            if (!self.include_libs && project_paths.has_library_ancestor(path))
193                || (self.exclude_tests && project_paths.is_test(path))
194            {
195                continue;
196            }
197
198            let path = project_paths.root.join(path);
199            versioned_sources
200                .entry(version.clone())
201                .or_default()
202                .sources
203                .insert(source_file.id, path);
204        }
205
206        // Get source maps and bytecodes.
207        let artifacts: Vec<ArtifactData> = output
208            .artifact_ids()
209            .par_bridge() // This parses source maps, so we want to run it in parallel.
210            .filter_map(|(id, artifact)| {
211                let source_id = report.get_source_id(id.version.clone(), id.source.clone())?;
212                ArtifactData::new(&id, source_id, artifact)
213            })
214            .collect();
215
216        // Add coverage items.
217        for (version, sources) in &versioned_sources {
218            let source_analysis = SourceAnalysis::new(sources, output)?;
219            let anchors = artifacts
220                .par_iter()
221                .filter(|artifact| artifact.contract_id.version == *version)
222                .map(|artifact| {
223                    let creation_code_anchors = artifact.creation.find_anchors(&source_analysis);
224                    let deployed_code_anchors = artifact.deployed.find_anchors(&source_analysis);
225                    (artifact.contract_id.clone(), (creation_code_anchors, deployed_code_anchors))
226                })
227                .collect_vec_list();
228            report.add_anchors(anchors.into_iter().flatten());
229            report.add_analysis(version.clone(), source_analysis);
230        }
231
232        if self.reporters.iter().any(|reporter| reporter.needs_source_maps()) {
233            report.add_source_maps(artifacts.into_iter().map(|artifact| {
234                (artifact.contract_id, (artifact.creation.source_map, artifact.deployed.source_map))
235            }));
236        }
237
238        Ok(report)
239    }
240
241    /// Runs tests, collects coverage data and generates the final report.
242    #[instrument(name = "Coverage::collect", skip_all)]
243    async fn collect(
244        mut self,
245        project_root: &Path,
246        output: &ProjectCompileOutput,
247        mut report: CoverageReport,
248        config: Config,
249        evm_opts: EvmOpts,
250    ) -> Result<()> {
251        let filter = self.test.filter(&config)?;
252        let outcome =
253            self.test.run_tests(project_root, config, evm_opts, output, &filter, true).await?;
254
255        let known_contracts = outcome.runner.as_ref().unwrap().known_contracts.clone();
256
257        // Add hit data to the coverage report
258        let data = outcome.results.iter().flat_map(|(_, suite)| {
259            let mut hits = Vec::new();
260            for result in suite.test_results.values() {
261                let Some(hit_maps) = result.line_coverage.as_ref() else { continue };
262                for map in hit_maps.0.values() {
263                    if let Some((id, _)) = known_contracts.find_by_deployed_code(map.bytecode()) {
264                        hits.push((id, map, true));
265                    } else if let Some((id, _)) =
266                        known_contracts.find_by_creation_code(map.bytecode())
267                    {
268                        hits.push((id, map, false));
269                    }
270                }
271            }
272            hits
273        });
274
275        for (artifact_id, map, is_deployed_code) in data {
276            if let Some(source_id) =
277                report.get_source_id(artifact_id.version.clone(), artifact_id.source.clone())
278            {
279                report.add_hit_map(
280                    &ContractId {
281                        version: artifact_id.version.clone(),
282                        source_id,
283                        contract_name: artifact_id.name.as_str().into(),
284                    },
285                    map,
286                    is_deployed_code,
287                )?;
288            }
289        }
290
291        // Filter out ignored sources from the report.
292        if let Some(not_re) = &filter.args().coverage_pattern_inverse {
293            let file_root = filter.paths().root.as_path();
294            report.retain_sources(|path: &Path| {
295                let path = path.strip_prefix(file_root).unwrap_or(path);
296                !not_re.is_match(&path.to_string_lossy())
297            });
298        }
299
300        // Output final reports.
301        self.report(&report)?;
302
303        // Check for test failures after generating coverage report.
304        // This ensures coverage data is written even when tests fail.
305        outcome.ensure_ok(false)?;
306
307        Ok(())
308    }
309
310    #[instrument(name = "Coverage::report", skip_all)]
311    fn report(&mut self, report: &CoverageReport) -> Result<()> {
312        for reporter in &mut self.reporters {
313            let _guard = debug_span!("reporter.report", kind=%reporter.name()).entered();
314            reporter.report(report)?;
315        }
316        Ok(())
317    }
318
319    pub fn is_watch(&self) -> bool {
320        self.test.is_watch()
321    }
322
323    pub fn watch(&self) -> &WatchArgs {
324        &self.test.watch
325    }
326}
327
328/// Coverage reports to generate.
329#[derive(Clone, Debug, Default, ValueEnum)]
330pub enum CoverageReportKind {
331    #[default]
332    Summary,
333    Lcov,
334    Debug,
335    Bytecode,
336}
337
338/// Helper function that will link references in unlinked bytecode to the 0 address.
339///
340/// This is needed in order to analyze the bytecode for contracts that use libraries.
341fn dummy_link_bytecode(mut obj: CompactBytecode) -> Option<Bytes> {
342    let link_references = obj.link_references.clone();
343    for (file, libraries) in link_references {
344        for library in libraries.keys() {
345            obj.link(&file, library, Address::ZERO);
346        }
347    }
348
349    obj.object.resolve();
350    obj.object.into_bytes()
351}
352
353/// Helper function that will link references in unlinked bytecode to the 0 address.
354///
355/// This is needed in order to analyze the bytecode for contracts that use libraries.
356fn dummy_link_deployed_bytecode(obj: CompactDeployedBytecode) -> Option<Bytes> {
357    obj.bytecode.and_then(dummy_link_bytecode)
358}
359
360pub struct ArtifactData {
361    pub contract_id: ContractId,
362    pub creation: BytecodeData,
363    pub deployed: BytecodeData,
364}
365
366impl ArtifactData {
367    pub fn new(id: &ArtifactId, source_id: usize, artifact: &impl Artifact) -> Option<Self> {
368        Some(Self {
369            contract_id: ContractId {
370                version: id.version.clone(),
371                source_id,
372                contract_name: id.name.as_str().into(),
373            },
374            creation: BytecodeData::new(
375                artifact.get_source_map()?.ok()?,
376                artifact
377                    .get_bytecode()
378                    .and_then(|bytecode| dummy_link_bytecode(bytecode.into_owned()))?,
379            ),
380            deployed: BytecodeData::new(
381                artifact.get_source_map_deployed()?.ok()?,
382                artifact
383                    .get_deployed_bytecode()
384                    .and_then(|bytecode| dummy_link_deployed_bytecode(bytecode.into_owned()))?,
385            ),
386        })
387    }
388}
389
390pub struct BytecodeData {
391    source_map: SourceMap,
392    bytecode: Bytes,
393    /// The instruction counter to program counter mapping.
394    ///
395    /// The source maps are indexed by *instruction counters*, which are the indexes of
396    /// instructions in the bytecode *minus any push bytes*.
397    ///
398    /// Since our line coverage inspector collects hit data using program counters, the anchors
399    /// also need to be based on program counters.
400    ic_pc_map: IcPcMap,
401}
402
403impl BytecodeData {
404    fn new(source_map: SourceMap, bytecode: Bytes) -> Self {
405        let ic_pc_map = IcPcMap::new(&bytecode);
406        Self { source_map, bytecode, ic_pc_map }
407    }
408
409    pub fn find_anchors(&self, source_analysis: &SourceAnalysis) -> Vec<ItemAnchor> {
410        find_anchors(&self.bytecode, &self.source_map, &self.ic_pc_map, source_analysis)
411    }
412}
413
414fn parse_lcov_version(s: &str) -> Result<Version, String> {
415    let vr = VersionReq::parse(&format!("={s}")).map_err(|e| e.to_string())?;
416    let [c] = &vr.comparators[..] else {
417        return Err("invalid version".to_string());
418    };
419    if c.op != semver::Op::Exact {
420        return Err("invalid version".to_string());
421    }
422    if !c.pre.is_empty() {
423        return Err("pre-releases are not supported".to_string());
424    }
425    Ok(Version::new(c.major, c.minor.unwrap_or(0), c.patch.unwrap_or(0)))
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn lcov_version() {
434        assert_eq!(parse_lcov_version("0").unwrap(), Version::new(0, 0, 0));
435        assert_eq!(parse_lcov_version("1").unwrap(), Version::new(1, 0, 0));
436        assert_eq!(parse_lcov_version("1.0").unwrap(), Version::new(1, 0, 0));
437        assert_eq!(parse_lcov_version("1.1").unwrap(), Version::new(1, 1, 0));
438        assert_eq!(parse_lcov_version("1.11").unwrap(), Version::new(1, 11, 0));
439    }
440}