Skip to content

Commit c4a984f

Browse files
authored
feat(forge): prettify ir and irOptimized inspect outputs (#8272)
1 parent f9674c3 commit c4a984f

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

crates/config/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ pub struct Config {
294294
pub block_difficulty: u64,
295295
/// Before merge the `block.max_hash`, after merge it is `block.prevrandao`.
296296
pub block_prevrandao: B256,
297-
/// the `block.gaslimit` value during EVM execution
297+
/// The `block.gaslimit` value during EVM execution.
298298
pub block_gas_limit: Option<GasLimit>,
299299
/// The memory limit per EVM execution in bytes.
300300
/// If this limit is exceeded, a `MemoryLimitOOG` result is thrown.

crates/forge/bin/cmd/inspect.rs

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ use foundry_compilers::{
1414
info::ContractInfo,
1515
utils::canonicalize,
1616
};
17+
use once_cell::sync::Lazy;
18+
use regex::Regex;
1719
use std::fmt;
1820

1921
/// CLI arguments for `forge inspect`.
@@ -111,10 +113,10 @@ impl InspectArgs {
111113
print_json(&artifact.devdoc)?;
112114
}
113115
ContractArtifactField::Ir => {
114-
print_json_str(&artifact.ir, None)?;
116+
print_yul(artifact.ir.as_deref(), self.pretty)?;
115117
}
116118
ContractArtifactField::IrOptimized => {
117-
print_json_str(&artifact.ir_optimized, None)?;
119+
print_yul(artifact.ir_optimized.as_deref(), self.pretty)?;
118120
}
119121
ContractArtifactField::Metadata => {
120122
print_json(&artifact.metadata)?;
@@ -369,18 +371,40 @@ fn print_json(obj: &impl serde::Serialize) -> Result<()> {
369371
}
370372

371373
fn print_json_str(obj: &impl serde::Serialize, key: Option<&str>) -> Result<()> {
374+
println!("{}", get_json_str(obj, key)?);
375+
Ok(())
376+
}
377+
378+
fn print_yul(yul: Option<&str>, pretty: bool) -> Result<()> {
379+
let Some(yul) = yul else {
380+
eyre::bail!("Could not get IR output");
381+
};
382+
383+
static YUL_COMMENTS: Lazy<Regex> =
384+
Lazy::new(|| Regex::new(r"(///.*\n\s*)|(\s*/\*\*.*\*/)").unwrap());
385+
386+
if pretty {
387+
println!("{}", YUL_COMMENTS.replace_all(yul, ""));
388+
} else {
389+
println!("{yul}");
390+
}
391+
392+
Ok(())
393+
}
394+
395+
fn get_json_str(obj: &impl serde::Serialize, key: Option<&str>) -> Result<String> {
372396
let value = serde_json::to_value(obj)?;
373397
let mut value_ref = &value;
374398
if let Some(key) = key {
375399
if let Some(value2) = value.get(key) {
376400
value_ref = value2;
377401
}
378402
}
379-
match value_ref.as_str() {
380-
Some(s) => println!("{s}"),
381-
None => println!("{value_ref:#}"),
382-
}
383-
Ok(())
403+
let s = match value_ref.as_str() {
404+
Some(s) => s.to_string(),
405+
None => format!("{value_ref:#}"),
406+
};
407+
Ok(s)
384408
}
385409

386410
#[cfg(test)]

0 commit comments

Comments
 (0)