use alloy_primitives::{Bytes, U256};
use smallvec::SmallVec;
use solar_data_structures::{fmt::FmtIteratorExt, index::IndexVec, map::FxHashMap, newtype_index};
use solar_interface::{Symbol, sym};
use std::{fmt, ops::Range};
newtype_index! {
pub struct LibraryId;
pub struct DataId;
pub struct ImmutableId;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Data {
pub bytes: DataBytes,
pub name: Option<Symbol>,
pub emit_in_runtime: bool,
pub library_relocations: Vec<LibraryRelocation>,
pub trailers: Vec<Trailer>,
}
impl Data {
pub fn new(bytes: Bytes, name: Option<Symbol>) -> Self {
Self {
bytes: DataBytes::Known(bytes),
name,
emit_in_runtime: false,
library_relocations: Vec::new(),
trailers: Vec::new(),
}
}
pub fn contract_code(code: ContractCode, name: Option<Symbol>) -> Self {
Self { bytes: DataBytes::Deferred(code), ..Self::new(Bytes::new(), name) }
}
pub fn display_contents<'a>(&'a self, libraries: &'a LibraryTable) -> impl fmt::Display + 'a {
solar_data_structures::fmt::from_fn(move |f| {
let bytes = match &self.bytes {
DataBytes::Known(bytes) => bytes,
DataBytes::Deferred(code) => return write!(f, "{code}"),
};
write!(f, "hex\"{}\"", alloy_primitives::hex::display(bytes))?;
if !self.library_relocations.is_empty() {
let relocations =
self.library_relocations.iter().map(|reloc| reloc.display(libraries));
write!(f, " library_relocations [{}]", relocations.format(", "))?;
}
Ok(())
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DataBytes {
Known(Bytes),
Deferred(ContractCode),
}
impl DataBytes {
pub fn known(&self) -> Option<&Bytes> {
match self {
Self::Known(bytes) => Some(bytes),
Self::Deferred(_) => None,
}
}
pub fn linked(&self) -> &Bytes {
self.known().expect("deferred data must be linked")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DataRef {
pub id: DataId,
pub offset: u32,
}
impl DataRef {
pub const fn new(id: DataId, offset: u32) -> Self {
Self { id, offset }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DataSize {
pub data: DataId,
pub addend: u64,
pub aligned: bool,
}
impl DataSize {
pub fn value(self, len: usize) -> U256 {
let size = U256::from(len) + U256::from(self.addend);
if self.aligned { size & !U256::from(31) } else { size }
}
pub fn bound(self) -> U256 {
U256::from(u32::MAX) + U256::from(self.addend)
}
pub fn is_length_of(self, data: DataRef) -> bool {
self.data == data.id && data.offset == 0 && self.addend == 0 && !self.aligned
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct QualifiedName(Symbol);
impl QualifiedName {
pub fn parse(text: &str) -> Option<Self> {
text.contains(':').then(|| Self(Symbol::intern(text)))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn split(&self) -> (&str, &str) {
self.as_str().rsplit_once(':').expect("qualified names contain `:`")
}
}
impl fmt::Display for QualifiedName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}\"", self.as_str().as_bytes().escape_ascii())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct LibraryTable {
entries: IndexVec<LibraryId, QualifiedName>,
}
impl LibraryTable {
pub fn clear(&mut self) {
self.entries.clear();
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn intern(&mut self, library: QualifiedName) -> LibraryId {
if let Some((id, _)) = self.entries.iter_enumerated().find(|(_, entry)| **entry == library)
{
id
} else {
self.entries.push(library)
}
}
pub fn get(&self, id: LibraryId) -> Option<&QualifiedName> {
self.entries.get(id)
}
pub fn display_ref(&self, id: LibraryId) -> impl fmt::Display + '_ {
fmt::from_fn(move |f| {
let (_, name) = self.get(id).expect("valid library ID").split();
write!(f, "{name}_{}", id.index())
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LibraryRelocation {
pub offset: usize,
pub library: LibraryId,
}
impl LibraryRelocation {
pub fn display<'a>(&'a self, libraries: &'a LibraryTable) -> impl fmt::Display + 'a {
fmt::from_fn(move |f| write!(f, "{}: {}", self.offset, libraries.display_ref(self.library)))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Trailer {
pub contracts: SmallVec<[QualifiedName; 1]>,
pub range: Range<usize>,
}
impl Trailer {
pub fn shifted(&self, base: usize) -> Self {
let range = base + self.range.start..base + self.range.end;
Self { contracts: self.contracts.clone(), range }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct RelocatableBytecode {
pub libraries: LibraryTable,
pub bytes: Bytes,
pub relocations: Vec<LibraryRelocation>,
pub trailers: Vec<Trailer>,
}
impl RelocatableBytecode {
pub fn relocations_in(&self, libraries: &mut LibraryTable) -> Vec<LibraryRelocation> {
self.relocations
.iter()
.map(|reloc| LibraryRelocation {
offset: reloc.offset,
library: libraries
.intern(*self.libraries.get(reloc.library).expect("valid bytecode library ID")),
})
.collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CodeKind {
Creation,
Runtime,
}
impl CodeKind {
pub fn keyword(self) -> Symbol {
match self {
Self::Creation => sym::creation_code,
Self::Runtime => sym::runtime_code,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ContractCode {
pub contract: QualifiedName,
pub kind: CodeKind,
}
impl ContractCode {
pub fn bytecode(self, bytecodes: &EmbeddedBytecodes) -> &RelocatableBytecode {
let bytecodes =
bytecodes.get(&self.contract).expect("embedded contract bytecode must be supplied");
match self.kind {
CodeKind::Creation => &bytecodes.deployment,
CodeKind::Runtime => &bytecodes.runtime,
}
}
}
impl fmt::Display for ContractCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.kind.keyword(), self.contract)
}
}
#[derive(Clone, Debug, Default)]
pub struct ContractBytecodes {
pub deployment: RelocatableBytecode,
pub runtime: RelocatableBytecode,
}
pub type EmbeddedBytecodes = FxHashMap<QualifiedName, ContractBytecodes>;
pub fn display_declarations<'a>(
libraries: &'a LibraryTable,
data: &'a IndexVec<DataId, Data>,
) -> impl fmt::Display + 'a {
fmt::from_fn(move |f| {
if !libraries.is_empty() {
writeln!(f, "@libraries")?;
for (id, library) in libraries.entries.iter_enumerated() {
writeln!(f, " {}: {library}", libraries.display_ref(id))?;
}
writeln!(f)?;
}
if !data.is_empty() {
writeln!(f, "@data")?;
for (id, entry) in data.iter_enumerated() {
let name = display_data_ref(entry.name, id.index(), 0);
writeln!(f, " {name}: {}", entry.display_contents(libraries))?;
}
writeln!(f)?;
}
Ok(())
})
}
pub fn display_data_name(name: Symbol, index: usize) -> impl fmt::Display {
fmt::from_fn(move |f| write!(f, "{name}_{index}"))
}
pub fn display_data_ref(name: Option<Symbol>, index: usize, offset: u32) -> impl fmt::Display {
fmt::from_fn(move |f| {
if let Some(name) = name {
write!(f, "{}", display_data_name(name, index))?;
} else {
write!(f, "{index}")?;
}
if offset != 0 {
write!(f, "+{offset}")?;
}
Ok(())
})
}
pub fn display_data_size(name: Option<Symbol>, size: DataSize) -> impl fmt::Display {
fmt::from_fn(move |f| {
write!(f, "{}", display_data_ref(name, size.data.index(), 0))?;
if size.addend != 0 || size.aligned {
write!(f, ", {}", size.addend)?;
}
if size.aligned {
f.write_str(", aligned")?;
}
Ok(())
})
}
pub fn display_u256(value: U256) -> impl fmt::Display {
fmt::from_fn(move |f| {
if let Ok(value) = u64::try_from(value)
&& value < 1000
{
write!(f, "{value}")
} else {
write!(f, "{value:#x}")
}
})
}