Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(forge): forge build --sizes collapses non uniques #9962

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 44 additions & 25 deletions crates/common/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ use std::{
/// settings.
#[must_use = "ProjectCompiler does nothing unless you call a `compile*` method"]
pub struct ProjectCompiler {
/// The root of the project.
project_root: PathBuf,

/// Whether we are going to verify the contracts after compilation.
verify: Option<bool>,

Expand Down Expand Up @@ -70,6 +73,7 @@ impl ProjectCompiler {
#[inline]
pub fn new() -> Self {
Self {
project_root: PathBuf::new(),
verify: None,
print_names: None,
print_sizes: None,
Expand Down Expand Up @@ -135,6 +139,8 @@ impl ProjectCompiler {
mut self,
project: &Project<C>,
) -> Result<ProjectCompileOutput<C>> {
self.project_root = project.root().clone();

// TODO: Avoid process::exit
if !project.paths.has_input_files() && self.files.is_empty() {
sh_println!("Nothing to compile")?;
Expand Down Expand Up @@ -250,32 +256,45 @@ impl ProjectCompiler {
let mut size_report =
SizeReport { report_kind: report_kind(), contracts: BTreeMap::new() };

let artifacts: BTreeMap<_, _> = output
.artifact_ids()
.filter(|(id, _)| {
// filter out forge-std specific contracts
!id.source.to_string_lossy().contains("/forge-std/src/")
})
.map(|(id, artifact)| (id.name, artifact))
.collect();

for (name, artifact) in artifacts {
let runtime_size = contract_size(artifact, false).unwrap_or_default();
let init_size = contract_size(artifact, true).unwrap_or_default();

let is_dev_contract = artifact
.abi
.as_ref()
.map(|abi| {
abi.functions().any(|f| {
f.test_function_kind().is_known() ||
matches!(f.name.as_str(), "IS_TEST" | "IS_SCRIPT")
let mut artifacts: BTreeMap<String, Vec<_>> = BTreeMap::new();
for (id, artifact) in output.artifact_ids().filter(|(id, _)| {
// filter out forge-std specific contracts
!id.source.to_string_lossy().contains("/forge-std/src/")
}) {
artifacts.entry(id.name.clone()).or_default().push((id.source.clone(), artifact));
}

for (name, artifact_list) in artifacts {
for (path, artifact) in &artifact_list {
let runtime_size = contract_size(*artifact, false).unwrap_or_default();
let init_size = contract_size(*artifact, true).unwrap_or_default();

let is_dev_contract = artifact
.abi
.as_ref()
.map(|abi| {
abi.functions().any(|f| {
f.test_function_kind().is_known() ||
matches!(f.name.as_str(), "IS_TEST" | "IS_SCRIPT")
})
})
})
.unwrap_or(false);
size_report
.contracts
.insert(name, ContractInfo { runtime_size, init_size, is_dev_contract });
.unwrap_or(false);

let unique_name = if artifact_list.len() > 1 {
format!(
"{} ({})",
name,
path.strip_prefix(&self.project_root).unwrap_or(path).display()
)
} else {
name.clone()
};

size_report.contracts.insert(
unique_name,
ContractInfo { runtime_size, init_size, is_dev_contract },
);
}
}

let _ = sh_println!("{size_report}");
Expand Down
126 changes: 126 additions & 0 deletions crates/forge/tests/cli/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,132 @@ forgetest_init!(build_sizes_no_forge_std, |prj, cmd| {
);
});

// tests build output --sizes handles multiple contracts with the same name
forgetest_init!(build_sizes_multiple_contracts, |prj, cmd| {
prj.add_source(
"Foo",
r"
contract Foo {
}
",
)
.unwrap();

prj.add_source(
"a/Counter",
r"
contract Counter {
uint256 public count;
function increment() public {
count++;
}
}
",
)
.unwrap();

prj.add_source(
"b/Counter",
r"
contract Counter {
uint256 public count;
function decrement() public {
count--;
}
}
",
)
.unwrap();

cmd.args(["build", "--sizes"]).assert_success().stdout_eq(str![[r#"
...

╭-----------------------------+------------------+-------------------+--------------------+---------------------╮
| Contract | Runtime Size (B) | Initcode Size (B) | Runtime Margin (B) | Initcode Margin (B) |
+===============================================================================================================+
| Counter (src/Counter.sol) | 481 | 509 | 24,095 | 48,643 |
|-----------------------------+------------------+-------------------+--------------------+---------------------|
| Counter (src/a/Counter.sol) | 344 | 372 | 24,232 | 48,780 |
|-----------------------------+------------------+-------------------+--------------------+---------------------|
| Counter (src/b/Counter.sol) | 291 | 319 | 24,285 | 48,833 |
|-----------------------------+------------------+-------------------+--------------------+---------------------|
| Foo | 62 | 88 | 24,514 | 49,064 |
╰-----------------------------+------------------+-------------------+--------------------+---------------------╯


"#]]);
});

// tests build output --sizes --json handles multiple contracts with the same name
forgetest_init!(build_sizes_multiple_contracts_json, |prj, cmd| {
prj.add_source(
"Foo",
r"
contract Foo {
}
",
)
.unwrap();

prj.add_source(
"a/Counter",
r"
contract Counter {
uint256 public count;
function increment() public {
count++;
}
}
",
)
.unwrap();

prj.add_source(
"b/Counter",
r"
contract Counter {
uint256 public count;
function decrement() public {
count--;
}
}
",
)
.unwrap();

cmd.args(["build", "--sizes", "--json"]).assert_success().stdout_eq(
str![[r#"
{
"Counter (src/Counter.sol)":{
"runtime_size":481,
"init_size":509,
"runtime_margin":24095,
"init_margin":48643
},
"Counter (src/a/Counter.sol)":{
"runtime_size":344,
"init_size":372,
"runtime_margin":24232,
"init_margin":48780
},
"Counter (src/b/Counter.sol)":{
"runtime_size":291,
"init_size":319,
"runtime_margin":24285,
"init_margin":48833
},
"Foo":{
"runtime_size":62,
"init_size":88,
"runtime_margin":24514,
"init_margin":49064
}
}
"#]]
.is_json(),
);
});

// tests that skip key in config can be used to skip non-compilable contract
forgetest_init!(test_can_skip_contract, |prj, cmd| {
prj.add_source(
Expand Down