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://github.com/foundry-rs/foundry/issues/3357"
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"
147            )?;
148        }
149
150        config.disable_optimizations(&mut project, self.ir_minimum);
151
152        let output = ProjectCompiler::default()
153            .compile(&project)?
154            .with_stripped_file_prefixes(project.root());
155
156        Ok((project, output))
157    }
158
159    /// Builds the coverage report.
160    #[instrument(name = "Coverage::prepare", skip_all)]
161    fn prepare(
162        &self,
163        project_paths: &ProjectPathsConfig,
164        output: &mut ProjectCompileOutput,
165    ) -> Result<CoverageReport> {
166        let mut report = CoverageReport::default();
167
168        output.parser_mut().solc_mut().compiler_mut().enter_mut(|compiler| {
169            if compiler.gcx().stage() < Some(solar::config::CompilerStage::Lowering) {
170                let _ = compiler.lower_asts();
171            }
172            convert_solar_errors(compiler.dcx())
173        })?;
174        let output = &*output;
175
176        // Collect source files.
177        let mut versioned_sources = HashMap::<Version, SourceFiles>::default();
178        for (path, source_file, version) in output.output().sources.sources_with_version() {
179            // Filter out vyper sources.
180            if path
181                .extension()
182                .and_then(|s| s.to_str())
183                .is_some_and(|ext| VYPER_EXTENSIONS.contains(&ext))
184            {
185                continue;
186            }
187
188            report.add_source(version.clone(), source_file.id as usize, path.clone());
189
190            // Filter out libs dependencies and tests.
191            if (!self.include_libs && project_paths.has_library_ancestor(path))
192                || (self.exclude_tests && project_paths.is_test(path))
193            {
194                continue;
195            }
196
197            let path = project_paths.root.join(path);
198            versioned_sources
199                .entry(version.clone())
200                .or_default()
201                .sources
202                .insert(source_file.id, path);
203        }
204
205        // Get source maps and bytecodes.
206        let artifacts: Vec<ArtifactData> = output
207            .artifact_ids()
208            .par_bridge() // This parses source maps, so we want to run it in parallel.
209            .filter_map(|(id, artifact)| {
210                let source_id = report.get_source_id(id.version.clone(), id.source.clone())?;
211                ArtifactData::new(&id, source_id, artifact)
212            })
213            .collect();
214
215        // Add coverage items.
216        for (version, sources) in &versioned_sources {
217            let source_analysis = SourceAnalysis::new(sources, output)?;
218            let anchors = artifacts
219                .par_iter()
220                .filter(|artifact| artifact.contract_id.version == *version)
221                .map(|artifact| {
222                    let creation_code_anchors = artifact.creation.find_anchors(&source_analysis);
223                    let deployed_code_anchors = artifact.deployed.find_anchors(&source_analysis);
224                    (artifact.contract_id.clone(), (creation_code_anchors, deployed_code_anchors))
225                })
226                .collect_vec_list();
227            report.add_anchors(anchors.into_iter().flatten());
228            report.add_analysis(version.clone(), source_analysis);
229        }
230
231        if self.reporters.iter().any(|reporter| reporter.needs_source_maps()) {
232            report.add_source_maps(artifacts.into_iter().map(|artifact| {
233                (artifact.contract_id, (artifact.creation.source_map, artifact.deployed.source_map))
234            }));
235        }
236
237        Ok(report)
238    }
239
240    /// Runs tests, collects coverage data and generates the final report.
241    #[instrument(name = "Coverage::collect", skip_all)]
242    async fn collect(
243        mut self,
244        project_root: &Path,
245        output: &ProjectCompileOutput,
246        mut report: CoverageReport,
247        config: Config,
248        evm_opts: EvmOpts,
249    ) -> Result<()> {
250        let filter = self.test.filter(&config)?;
251        let outcome =
252            self.test.run_tests(project_root, config, evm_opts, output, &filter, true).await?;
253        outcome.ensure_ok(false)?;
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        Ok(())
304    }
305
306    #[instrument(name = "Coverage::report", skip_all)]
307    fn report(&mut self, report: &CoverageReport) -> Result<()> {
308        for reporter in &mut self.reporters {
309            let _guard = debug_span!("reporter.report", kind=%reporter.name()).entered();
310            reporter.report(report)?;
311        }
312        Ok(())
313    }
314
315    pub fn is_watch(&self) -> bool {
316        self.test.is_watch()
317    }
318
319    pub fn watch(&self) -> &WatchArgs {
320        &self.test.watch
321    }
322}
323
324/// Coverage reports to generate.
325#[derive(Clone, Debug, Default, ValueEnum)]
326pub enum CoverageReportKind {
327    #[default]
328    Summary,
329    Lcov,
330    Debug,
331    Bytecode,
332}
333
334/// Helper function that will link references in unlinked bytecode to the 0 address.
335///
336/// This is needed in order to analyze the bytecode for contracts that use libraries.
337fn dummy_link_bytecode(mut obj: CompactBytecode) -> Option<Bytes> {
338    let link_references = obj.link_references.clone();
339    for (file, libraries) in link_references {
340        for library in libraries.keys() {
341            obj.link(&file, library, Address::ZERO);
342        }
343    }
344
345    obj.object.resolve();
346    obj.object.into_bytes()
347}
348
349/// Helper function that will link references in unlinked bytecode to the 0 address.
350///
351/// This is needed in order to analyze the bytecode for contracts that use libraries.
352fn dummy_link_deployed_bytecode(obj: CompactDeployedBytecode) -> Option<Bytes> {
353    obj.bytecode.and_then(dummy_link_bytecode)
354}
355
356pub struct ArtifactData {
357    pub contract_id: ContractId,
358    pub creation: BytecodeData,
359    pub deployed: BytecodeData,
360}
361
362impl ArtifactData {
363    pub fn new(id: &ArtifactId, source_id: usize, artifact: &impl Artifact) -> Option<Self> {
364        Some(Self {
365            contract_id: ContractId {
366                version: id.version.clone(),
367                source_id,
368                contract_name: id.name.as_str().into(),
369            },
370            creation: BytecodeData::new(
371                artifact.get_source_map()?.ok()?,
372                artifact
373                    .get_bytecode()
374                    .and_then(|bytecode| dummy_link_bytecode(bytecode.into_owned()))?,
375            ),
376            deployed: BytecodeData::new(
377                artifact.get_source_map_deployed()?.ok()?,
378                artifact
379                    .get_deployed_bytecode()
380                    .and_then(|bytecode| dummy_link_deployed_bytecode(bytecode.into_owned()))?,
381            ),
382        })
383    }
384}
385
386pub struct BytecodeData {
387    source_map: SourceMap,
388    bytecode: Bytes,
389    /// The instruction counter to program counter mapping.
390    ///
391    /// The source maps are indexed by *instruction counters*, which are the indexes of
392    /// instructions in the bytecode *minus any push bytes*.
393    ///
394    /// Since our line coverage inspector collects hit data using program counters, the anchors
395    /// also need to be based on program counters.
396    ic_pc_map: IcPcMap,
397}
398
399impl BytecodeData {
400    fn new(source_map: SourceMap, bytecode: Bytes) -> Self {
401        let ic_pc_map = IcPcMap::new(&bytecode);
402        Self { source_map, bytecode, ic_pc_map }
403    }
404
405    pub fn find_anchors(&self, source_analysis: &SourceAnalysis) -> Vec<ItemAnchor> {
406        find_anchors(&self.bytecode, &self.source_map, &self.ic_pc_map, source_analysis)
407    }
408}
409
410fn parse_lcov_version(s: &str) -> Result<Version, String> {
411    let vr = VersionReq::parse(&format!("={s}")).map_err(|e| e.to_string())?;
412    let [c] = &vr.comparators[..] else {
413        return Err("invalid version".to_string());
414    };
415    if c.op != semver::Op::Exact {
416        return Err("invalid version".to_string());
417    }
418    if !c.pre.is_empty() {
419        return Err("pre-releases are not supported".to_string());
420    }
421    Ok(Version::new(c.major, c.minor.unwrap_or(0), c.patch.unwrap_or(0)))
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    #[test]
429    fn lcov_version() {
430        assert_eq!(parse_lcov_version("0").unwrap(), Version::new(0, 0, 0));
431        assert_eq!(parse_lcov_version("1").unwrap(), Version::new(1, 0, 0));
432        assert_eq!(parse_lcov_version("1.0").unwrap(), Version::new(1, 0, 0));
433        assert_eq!(parse_lcov_version("1.1").unwrap(), Version::new(1, 1, 0));
434        assert_eq!(parse_lcov_version("1.11").unwrap(), Version::new(1, 11, 0));
435    }
436}