Skip to content

Commit

Permalink
feat(forge): prettify ir and irOptimized inspect outputs (#8272)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Jun 27, 2024
1 parent f9674c3 commit c4a984f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
2 changes: 1 addition & 1 deletion crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ pub struct Config {
pub block_difficulty: u64,
/// Before merge the `block.max_hash`, after merge it is `block.prevrandao`.
pub block_prevrandao: B256,
/// the `block.gaslimit` value during EVM execution
/// The `block.gaslimit` value during EVM execution.
pub block_gas_limit: Option<GasLimit>,
/// The memory limit per EVM execution in bytes.
/// If this limit is exceeded, a `MemoryLimitOOG` result is thrown.
Expand Down
38 changes: 31 additions & 7 deletions crates/forge/bin/cmd/inspect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use foundry_compilers::{
info::ContractInfo,
utils::canonicalize,
};
use once_cell::sync::Lazy;
use regex::Regex;
use std::fmt;

/// CLI arguments for `forge inspect`.
Expand Down Expand Up @@ -111,10 +113,10 @@ impl InspectArgs {
print_json(&artifact.devdoc)?;
}
ContractArtifactField::Ir => {
print_json_str(&artifact.ir, None)?;
print_yul(artifact.ir.as_deref(), self.pretty)?;
}
ContractArtifactField::IrOptimized => {
print_json_str(&artifact.ir_optimized, None)?;
print_yul(artifact.ir_optimized.as_deref(), self.pretty)?;
}
ContractArtifactField::Metadata => {
print_json(&artifact.metadata)?;
Expand Down Expand Up @@ -369,18 +371,40 @@ fn print_json(obj: &impl serde::Serialize) -> Result<()> {
}

fn print_json_str(obj: &impl serde::Serialize, key: Option<&str>) -> Result<()> {
println!("{}", get_json_str(obj, key)?);
Ok(())
}

fn print_yul(yul: Option<&str>, pretty: bool) -> Result<()> {
let Some(yul) = yul else {
eyre::bail!("Could not get IR output");
};

static YUL_COMMENTS: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(///.*\n\s*)|(\s*/\*\*.*\*/)").unwrap());

if pretty {
println!("{}", YUL_COMMENTS.replace_all(yul, ""));
} else {
println!("{yul}");
}

Ok(())
}

fn get_json_str(obj: &impl serde::Serialize, key: Option<&str>) -> Result<String> {
let value = serde_json::to_value(obj)?;
let mut value_ref = &value;
if let Some(key) = key {
if let Some(value2) = value.get(key) {
value_ref = value2;
}
}
match value_ref.as_str() {
Some(s) => println!("{s}"),
None => println!("{value_ref:#}"),
}
Ok(())
let s = match value_ref.as_str() {
Some(s) => s.to_string(),
None => format!("{value_ref:#}"),
};
Ok(s)
}

#[cfg(test)]
Expand Down

0 comments on commit c4a984f

Please sign in to comment.