matter-labs / foundry-zksync

Fork of Foundry tailored for zkSync environment
Apache License 2.0
299 stars 130 forks source link

Support for `forge coverage` Command #673

Open Karrq opened 2 weeks ago

Karrq commented 2 weeks ago

Currently Blocked by: https://github.com/matter-labs/era-compiler-solidity/issues/160

How it works

2 steps, prepare and collect

prepare:

  1. map source ids to paths, skip libraries if opt is set
  2. Get artifact data/ id + bytecodes
  3. Analyze sources and asts using the SourceAnalyzer, this walks the ast and creates CoverageItems which are elements that need to be analyzed in coverage paired with a SourceLocation, which indicates where in the source code they are. 4 Look at source maps and create anchors which map bytecode instructions to CoverageItems

collect:

  1. Create a contract runner with some options and coverage set to "true"
  2. Run tests
  3. Collect hit data (in TestResult.coverage, collected by the CoverageCollector), with artifact id and wether it comes from creation code or runtime code
  4. Do the corresponding analysis depending on the options

How hit map is built:

There's a CoverageCollector inspector which collects hit maps This is a mapping of bytecode hash -> HitMap

pub struct HitMap {
    pub bytecode: Bytes,
    pub hits: BTreeMap<usize, u64>, // usize is program counter, u64 is number of hits
}

On each step it will add a hit to the program counter of the instruction

What we would need:

🔗 Useful Links

https://book.getfoundry.sh/reference/forge/forge-coverage?highlight=cforge coverage#examples