Skip to content
Draft
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
22 changes: 21 additions & 1 deletion crates/compilers/crates/artifacts/solc/src/bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ pub struct Bytecode {
/// If given, this is an unlinked object.
#[serde(default)]
pub link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>,
/// ETHDebug program for this bytecode.
///
/// Present only if `evm.bytecode.ethdebug` or `evm.deployedBytecode.ethdebug` was selected.
/// See <https://ethdebug.github.io/format/spec/program>.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ethdebug: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand All @@ -45,13 +51,24 @@ pub struct CompactBytecode {
/// If given, this is an unlinked object.
#[serde(default)]
pub link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>,
/// ETHDebug program for this bytecode.
///
/// Present only if `evm.bytecode.ethdebug` or `evm.deployedBytecode.ethdebug` was selected.
/// See <https://ethdebug.github.io/format/spec/program>.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ethdebug: Option<serde_json::Value>,
}

impl CompactBytecode {
/// Returns a new `CompactBytecode` object that contains nothing, as it's the case for
/// interfaces and standalone solidity files that don't contain any contract definitions
pub fn empty() -> Self {
Self { object: Default::default(), source_map: None, link_references: Default::default() }
Self {
object: Default::default(),
source_map: None,
link_references: Default::default(),
ethdebug: None,
}
}

/// Returns the parsed source map
Expand Down Expand Up @@ -102,6 +119,7 @@ impl From<Bytecode> for CompactBytecode {
object: bcode.object,
source_map: bcode.source_map,
link_references: bcode.link_references,
ethdebug: bcode.ethdebug,
}
}
}
Expand All @@ -112,6 +130,7 @@ impl From<CompactBytecode> for Bytecode {
object: bcode.object,
source_map: bcode.source_map,
link_references: bcode.link_references,
ethdebug: bcode.ethdebug,
function_debug_data: Default::default(),
opcodes: Default::default(),
generated_sources: Default::default(),
Expand All @@ -128,6 +147,7 @@ impl From<BytecodeObject> for Bytecode {
source_map: Default::default(),
generated_sources: Default::default(),
link_references: Default::default(),
ethdebug: Default::default(),
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions crates/compilers/crates/artifacts/solc/src/configurable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ impl<'de> Deserialize<'de> for DirectDeployed {
link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>,
#[serde(default)]
immutable_references: BTreeMap<String, Vec<Offsets>>,
#[serde(default)]
ethdebug: Option<serde_json::Value>,
}

struct MapVisitor;
Expand All @@ -201,6 +203,7 @@ impl<'de> Deserialize<'de> for DirectDeployed {
object: fields.object,
source_map: fields.source_map,
link_references: fields.link_references,
ethdebug: fields.ethdebug,
}),
immutable_references: fields.immutable_references,
}))
Expand Down Expand Up @@ -422,6 +425,8 @@ mod tests {
r#"{"object":"0x12","object":"0x34"}"#,
r#"{"object":"0x12","sourceMap":null,"sourceMap":null}"#,
r#"{"object":"0x12","immutableReferences":null}"#,
r#"{"object":"0x12","ethdebug":{"instructions":[{"offset":0,"operation":{"mnemonic":"STOP"}}]}}"#,
r#"{"object":"0x12","ethdebug":null}"#,
r#"{"immutableReferences":{"1":[{"start":0,"length":32}]}}"#,
r#"["0x12",null,{},{}]"#,
"true",
Expand Down
76 changes: 75 additions & 1 deletion crates/compilers/crates/artifacts/solc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,9 @@ pub struct DebuggingSettings {
// - `<end>` is the index of the first byte after that location.
// - `snippet`: A single-line code snippet from the location indicated by `@src`. The snippet is
// quoted and follows the corresponding `@src` annotation.
// - `*`: Wildcard value that can be used to request everything.
// - `ethdebug`: ETHDebug annotations. Experimental, since solc 0.8.29. Solc enables it when an
// ETHDebug program is selected and `debugInfo` is not set.
// - `*`: Wildcard value that can be used to request everything except `ethdebug`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub debug_info: Vec<String>,
}
Expand Down Expand Up @@ -1637,6 +1639,13 @@ pub struct CompilerOutput {
pub sources: BTreeMap<SourceUnitName, SourceFile>,
#[serde(default)]
pub contracts: Contracts,
/// Global ETHDebug output.
///
/// Solar and solc 0.8.35 or later put the selected `resources` and `compilation` records
/// here. Solc 0.8.29 to 0.8.34 put the resources record here whenever an ETHDebug program was
/// selected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ethdebug: Option<serde_json::Value>,
}

impl CompilerOutput {
Expand Down Expand Up @@ -1998,6 +2007,7 @@ impl SourceFiles {
#[cfg(test)]
mod tests {
use super::*;
use crate::output_selection::{BytecodeOutputSelection, DeployedBytecodeOutputSelection};
use alloy_primitives::Address;

use std::fs;
Expand Down Expand Up @@ -2035,6 +2045,7 @@ mod tests {
"lib2.sol".to_string(),
BTreeMap::from([("L".to_string(), vec![])]),
)]),
ethdebug: None,
};

assert!(!code.link("lib2.sol", "Y", Address::random()));
Expand Down Expand Up @@ -2313,6 +2324,40 @@ mod tests {
assert!(i.settings.via_ssa_cfg.is_none());
}

#[test]
fn can_serialize_ethdebug_settings() {
let mut settings =
Settings::new(OutputSelection::empty()).with_via_ir().with_experimental();
settings.debug =
Some(DebuggingSettings { revert_strings: None, debug_info: vec!["ethdebug".into()] });
settings.push_all([
BytecodeOutputSelection::Ethdebug.into(),
DeployedBytecodeOutputSelection::Ethdebug.into(),
ContractOutputSelection::EthdebugResources,
ContractOutputSelection::EthdebugCompilation,
]);

let value = serde_json::to_value(&settings).unwrap();
assert_eq!(value["viaIR"], true);
assert_eq!(value["experimental"], true);
assert_eq!(value["optimizer"]["enabled"], false);
assert_eq!(value["debug"], serde_json::json!({ "debugInfo": ["ethdebug"] }));
assert_eq!(
value["outputSelection"],
serde_json::json!({
"*": {
"*": [
"evm.bytecode.ethdebug",
"evm.deployedBytecode.ethdebug",
"ethdebug.resources",
"ethdebug.compilation"
]
}
})
);
assert_eq!(serde_json::from_value::<Settings>(value).unwrap(), settings);
}

#[test]
fn can_parse_libraries() {
let libraries = ["./src/lib/LibraryContract.sol:Library:0xaddress".to_string()];
Expand Down Expand Up @@ -2576,6 +2621,35 @@ mod tests {
let _output: CompilerOutput = serde_json::from_str(&content).unwrap();
}

// Recorded with solc 0.8.37, `viaIR`, `experimental`, the optimizer disabled, and all
// ETHDebug outputs selected.
#[test]
fn can_parse_ethdebug_compiler_output() {
let output: CompilerOutput =
serde_json::from_str(include_str!("../../../../test-data/ethdebug-0.8.37-output.json"))
.unwrap();

let ethdebug = output.ethdebug.as_ref().unwrap();
assert_eq!(ethdebug["resources"]["compilation"], ethdebug["compilation"]);
assert_eq!(ethdebug["compilation"]["sources"][0]["path"], "Counter.sol");

let evm = output.contracts["Counter.sol"]["Counter"].evm.as_ref().unwrap();
let creation = evm.bytecode.as_ref().unwrap().ethdebug.as_ref().unwrap();
let deployed = evm.deployed_bytecode.as_ref().unwrap().bytecode.as_ref().unwrap();
let runtime = deployed.ethdebug.as_ref().unwrap();
assert_eq!(creation["environment"], "create");
assert_eq!(runtime["environment"], "call");
assert_eq!(runtime["contract"]["name"], "Counter");
assert_eq!(runtime["instructions"][0]["offset"], 0);
assert_eq!(runtime["instructions"][0]["operation"]["mnemonic"], "PUSH1");

let value = serde_json::to_value(&output).unwrap();
assert_eq!(&value["ethdebug"], ethdebug);
let evm = &value["contracts"]["Counter.sol"]["Counter"]["evm"];
assert_eq!(&evm["bytecode"]["ethdebug"], creation);
assert_eq!(&evm["deployedBytecode"]["ethdebug"], runtime);
}

// <https://github.com/foundry-rs/foundry/issues/9322>
#[test]
fn can_sanitize_optimizer_inliner() {
Expand Down
63 changes: 59 additions & 4 deletions crates/compilers/crates/artifacts/solc/src/output_selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub type FileOutputSelection = BTreeMap<String, Vec<String>>;
/// evm.bytecode.sourceMap - Source mapping (useful for debugging)
/// evm.bytecode.linkReferences - Link references (if unlinked object)
/// evm.bytecode.generatedSources - Sources generated by the compiler
/// evm.bytecode.ethdebug - ETHDebug program (experimental, solc needs viaIR)
/// evm.deployedBytecode* - Deployed bytecode (has all the options that
/// evm.bytecode has)
/// evm.deployedBytecode.immutableReferences - Map from AST ids to
Expand All @@ -47,10 +48,16 @@ pub type FileOutputSelection = BTreeMap<String, Vec<String>>;
/// evm.gasEstimates - Function gas estimates
/// ewasm.wast - Ewasm in WebAssembly S-expressions format
/// ewasm.wasm - Ewasm in WebAssembly binary format
/// ethdebug.resources - ETHDebug resources of the compilation
/// (experimental, since solc 0.8.35, only for "*" files and contracts)
/// ethdebug.compilation - ETHDebug compilation record, the `compilation`
/// key of the resources (experimental, since solc 0.8.35, only for "*"
/// files and contracts)
///
/// Note that using a using `evm`, `evm.bytecode`, `ewasm`, etc. will select
/// every target part of that output. Additionally, `*` can be used as a
/// wildcard to request everything.
/// wildcard to request everything. Solc and Solar never match ETHDebug outputs
/// with these selections, so they must be requested by their exact names.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct OutputSelection(pub BTreeMap<String, FileOutputSelection>);
Expand Down Expand Up @@ -190,14 +197,20 @@ impl OutputSelection {
/// parts balanced. A `*` file key is expanded over `sources`.
///
/// Returns `None` when the selection requests file-level outputs such as the AST, whose node
/// ids depend on the compilation unit, or when fewer than `2 * MIN_FILES_PER_PART` files
/// request outputs.
/// ids depend on the compilation unit, when it requests ETHDebug outputs, which describe the
/// whole compiler run, or when fewer than `2 * MIN_FILES_PER_PART` files request outputs.
pub fn split(
&self,
sources: impl IntoIterator<Item = (String, usize)>,
max_parts: usize,
) -> Option<Vec<Self>> {
if self.contains_ast() {
if self.contains_ast()
|| self
.0
.values()
.flat_map(|file| file.values().flatten())
.any(|o| o.contains("ethdebug"))
{
return None;
}
let mut files = BTreeMap::new();
Expand Down Expand Up @@ -314,6 +327,15 @@ pub enum ContractOutputSelection {
TransientStorageLayout,
Evm(EvmOutputSelection),
Ewasm(EwasmOutputSelection),
/// ETHDebug resources of the compilation.
///
/// Since solc 0.8.35. Older solc versions emit the resources with any requested ETHDebug
/// program.
EthdebugResources,
/// ETHDebug compilation record, the `compilation` key of the resources.
///
/// Since solc 0.8.35.
EthdebugCompilation,
}

impl ContractOutputSelection {
Expand Down Expand Up @@ -373,6 +395,8 @@ impl fmt::Display for ContractOutputSelection {
Self::TransientStorageLayout => f.write_str("transientStorageLayout"),
Self::Evm(e) => e.fmt(f),
Self::Ewasm(e) => e.fmt(f),
Self::EthdebugResources => f.write_str("ethdebug.resources"),
Self::EthdebugCompilation => f.write_str("ethdebug.compilation"),
}
}
}
Expand All @@ -393,6 +417,8 @@ impl FromStr for ContractOutputSelection {
"transient-storage-layout" | "transientstoragelayout" | "transientStorageLayout" => {
Ok(Self::TransientStorageLayout)
}
"ethdebug.resources" => Ok(Self::EthdebugResources),
"ethdebug.compilation" => Ok(Self::EthdebugCompilation),
s => EvmOutputSelection::from_str(s)
.map(ContractOutputSelection::Evm)
.or_else(|_| EwasmOutputSelection::from_str(s).map(ContractOutputSelection::Ewasm))
Expand Down Expand Up @@ -502,6 +528,8 @@ pub enum BytecodeOutputSelection {
SourceMap,
LinkReferences,
GeneratedSources,
/// ETHDebug program. Solc requires `viaIR` for it.
Ethdebug,
}

impl Serialize for BytecodeOutputSelection {
Expand Down Expand Up @@ -532,6 +560,7 @@ impl fmt::Display for BytecodeOutputSelection {
Self::SourceMap => f.write_str("evm.bytecode.sourceMap"),
Self::LinkReferences => f.write_str("evm.bytecode.linkReferences"),
Self::GeneratedSources => f.write_str("evm.bytecode.generatedSources"),
Self::Ethdebug => f.write_str("evm.bytecode.ethdebug"),
}
}
}
Expand All @@ -548,6 +577,7 @@ impl FromStr for BytecodeOutputSelection {
"evm.bytecode.sourceMap" => Ok(Self::SourceMap),
"evm.bytecode.linkReferences" => Ok(Self::LinkReferences),
"evm.bytecode.generatedSources" => Ok(Self::GeneratedSources),
"evm.bytecode.ethdebug" => Ok(Self::Ethdebug),
s => Err(format!("Invalid bytecode selection: {s}")),
}
}
Expand All @@ -564,6 +594,8 @@ pub enum DeployedBytecodeOutputSelection {
LinkReferences,
GeneratedSources,
ImmutableReferences,
/// ETHDebug program. Solc requires `viaIR` for it.
Ethdebug,
}

impl Serialize for DeployedBytecodeOutputSelection {
Expand Down Expand Up @@ -595,6 +627,7 @@ impl fmt::Display for DeployedBytecodeOutputSelection {
Self::LinkReferences => f.write_str("evm.deployedBytecode.linkReferences"),
Self::GeneratedSources => f.write_str("evm.deployedBytecode.generatedSources"),
Self::ImmutableReferences => f.write_str("evm.deployedBytecode.immutableReferences"),
Self::Ethdebug => f.write_str("evm.deployedBytecode.ethdebug"),
}
}
}
Expand All @@ -616,6 +649,7 @@ impl FromStr for DeployedBytecodeOutputSelection {
"evm.deployedBytecode.linkReferences" => Ok(Self::LinkReferences),
"evm.deployedBytecode.generatedSources" => Ok(Self::GeneratedSources),
"evm.deployedBytecode.immutableReferences" => Ok(Self::ImmutableReferences),
"evm.deployedBytecode.ethdebug" => Ok(Self::Ethdebug),
s => Err(format!("Invalid deployedBytecode selection: {s}")),
}
}
Expand Down Expand Up @@ -698,6 +732,9 @@ mod tests {
assert!(selection.split(sources(), 1).is_none());
assert_eq!(selection.split(sources(), 8).unwrap().len(), 2);
assert!(OutputSelection::ast_output_selection().split(sources(), 8).is_none());
let mut ethdebug = selection;
ethdebug.0.extend([file_outputs("*", &["evm.bytecode.ethdebug"])]);
assert!(ethdebug.split(sources(), 8).is_none());
}

#[test]
Expand Down Expand Up @@ -888,4 +925,22 @@ mod tests {
)]));
assert!(!contract_only.contains_ast());
}

#[test]
fn ethdebug_output_selection_from_str() {
for (s, selection) in [
("evm.bytecode.ethdebug", BytecodeOutputSelection::Ethdebug.into()),
("evm.deployedBytecode.ethdebug", DeployedBytecodeOutputSelection::Ethdebug.into()),
("ethdebug.resources", ContractOutputSelection::EthdebugResources),
("ethdebug.compilation", ContractOutputSelection::EthdebugCompilation),
] {
assert_eq!(ContractOutputSelection::from_str(s).unwrap(), selection);
assert_eq!(selection.to_string(), s);
assert_eq!(serde_json::to_string(&selection).unwrap(), format!("\"{s}\""));
}
assert_eq!(
ContractOutputSelection::from_str("ethdebug").unwrap_err(),
"Invalid contract output selection: ethdebug"
);
}
}
1 change: 1 addition & 0 deletions crates/compilers/crates/artifacts/vyper/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ impl From<Bytecode> for solc_artifacts::Bytecode {
function_debug_data: Default::default(),
generated_sources: Default::default(),
link_references: Default::default(),
ethdebug: Default::default(),
}
}
}
Expand Down
Loading
Loading