Skip to main content

i8051_disassembler/
address.rs

1use std::marker::PhantomData;
2use std::ops::{Bound, Deref, RangeBounds};
3
4use i8051::{ControlFlow, Instruction, Mnemonic};
5use serde::de::value::SeqAccessDeserializer;
6use serde::de::{Error as _, SeqAccess, Visitor};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9pub type AddressValue = u32;
10
11// Signals to the serializer/deserializer to use compact syntax.
12pub(crate) const ADDRESS_TOKEN: &str = "$dsl::address";
13pub(crate) const ADDRESS_RANGE_TOKEN: &str = "$dsl::address_range";
14
15/// A space-qualified address. Derefs to its [`AddressValue`] offset.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct SpaceAddressValue {
18    pub space: AddressSpace,
19    pub offset: AddressValue,
20}
21
22impl Deref for SpaceAddressValue {
23    type Target = AddressValue;
24    fn deref(&self) -> &Self::Target {
25        &self.offset
26    }
27}
28
29impl From<(AddressSpace, AddressValue)> for SpaceAddressValue {
30    fn from((space, offset): (AddressSpace, AddressValue)) -> Self {
31        Self { space, offset }
32    }
33}
34
35impl Serialize for SpaceAddressValue {
36    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
37        serializer
38            .serialize_newtype_struct(ADDRESS_TOKEN, &(self.space.dsl_name(), self.offset as u64))
39    }
40}
41
42impl<'de> Deserialize<'de> for SpaceAddressValue {
43    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
44        let (space, offset): (String, u64) = deserialize_token(deserializer, ADDRESS_TOKEN)?;
45        Ok(Self {
46            space: decode_space::<D>(&space)?,
47            offset: offset as AddressValue,
48        })
49    }
50}
51
52/// A space-qualified address range. Derefs to its [`AddressRange`].
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
54pub struct SpaceAddressRange {
55    pub space: AddressSpace,
56    pub range: AddressRange,
57}
58
59impl Deref for SpaceAddressRange {
60    type Target = AddressRange;
61    fn deref(&self) -> &Self::Target {
62        &self.range
63    }
64}
65
66impl From<(AddressSpace, AddressRange)> for SpaceAddressRange {
67    fn from((space, range): (AddressSpace, AddressRange)) -> Self {
68        Self { space, range }
69    }
70}
71
72impl Serialize for SpaceAddressRange {
73    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
74        serializer.serialize_newtype_struct(
75            ADDRESS_RANGE_TOKEN,
76            &(
77                self.space.dsl_name(),
78                self.range.start as u64,
79                self.range.end as u64,
80            ),
81        )
82    }
83}
84
85impl<'de> Deserialize<'de> for SpaceAddressRange {
86    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
87        let (space, start, end): (String, u64, u64) =
88            deserialize_token(deserializer, ADDRESS_RANGE_TOKEN)?;
89        Ok(Self {
90            space: decode_space::<D>(&space)?,
91            range: AddressRange::new(start as AddressValue, end as AddressValue),
92        })
93    }
94}
95
96fn decode_space<'de, D: Deserializer<'de>>(name: &str) -> Result<AddressSpace, D::Error> {
97    AddressSpace::from_dsl_name(name)
98        .ok_or_else(|| D::Error::custom(format!("unknown address space {name}")))
99}
100
101/// Deserialize the tuple carried inside an address newtype token, tolerating
102/// serializers that ignore the token and pass a plain sequence.
103fn deserialize_token<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
104    deserializer: D,
105    token: &'static str,
106) -> Result<T, D::Error> {
107    struct TokenVisitor<T>(PhantomData<T>);
108
109    impl<'de, T: Deserialize<'de>> Visitor<'de> for TokenVisitor<T> {
110        type Value = T;
111        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112            f.write_str("a DSL address")
113        }
114        fn visit_newtype_struct<D: Deserializer<'de>>(self, d: D) -> Result<T, D::Error> {
115            T::deserialize(d)
116        }
117        fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<T, A::Error> {
118            T::deserialize(SeqAccessDeserializer::new(seq))
119        }
120    }
121
122    deserializer.deserialize_newtype_struct(token, TokenVisitor(PhantomData))
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
126pub struct AddressRange {
127    pub start: AddressValue,
128    pub end: AddressValue,
129}
130
131impl AddressRange {
132    pub fn new(start_inclusive: AddressValue, end_exclusive: AddressValue) -> Self {
133        Self {
134            start: start_inclusive,
135            end: end_exclusive,
136        }
137    }
138}
139
140impl<T: RangeBounds<AddressValue>> From<T> for AddressRange {
141    fn from(range: T) -> Self {
142        let range_start_inclusive = match range.start_bound() {
143            Bound::Included(addr) => *addr,
144            Bound::Excluded(addr) => addr.saturating_add(1),
145            Bound::Unbounded => 0,
146        };
147        let range_end_inclusive = match range.end_bound() {
148            Bound::Included(addr) => *addr,
149            Bound::Excluded(addr) => addr.saturating_sub(1),
150            Bound::Unbounded => AddressValue::MAX,
151        };
152        Self {
153            start: range_start_inclusive,
154            end: range_end_inclusive,
155        }
156    }
157}
158
159/// Explicit emission order for sdas area headers.
160pub const AREA_ORDER: [AddressSpace; 5] = [
161    AddressSpace::Code,
162    AddressSpace::Idata,
163    AddressSpace::Sfr,
164    AddressSpace::Bit,
165    AddressSpace::Xdata,
166];
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
169pub enum AddressSpace {
170    Code,
171    Idata,
172    Sfr,
173    Bit,
174    Xdata,
175}
176
177impl AddressSpace {
178    /// The DSL spelling of this space (`CODE`, `IDATA`, ...).
179    pub fn dsl_name(self) -> &'static str {
180        match self {
181            Self::Code => "CODE",
182            Self::Idata => "IDATA",
183            Self::Sfr => "SFR",
184            Self::Bit => "BIT",
185            Self::Xdata => "XDATA",
186        }
187    }
188
189    /// Parse a DSL space spelling, the inverse of [`dsl_name`](Self::dsl_name).
190    pub fn from_dsl_name(name: &str) -> Option<Self> {
191        Some(match name {
192            "CODE" => Self::Code,
193            "IDATA" => Self::Idata,
194            "SFR" => Self::Sfr,
195            "BIT" => Self::Bit,
196            "XDATA" => Self::Xdata,
197            _ => return None,
198        })
199    }
200
201    pub fn area_header(self) -> &'static str {
202        match self {
203            Self::Code => ".area CODE (CODE,ABS)\n",
204            Self::Idata => ".area IDATA (IDATA,ABS)\n",
205            Self::Sfr => ".area SFR (SFR,ABS)\n",
206            Self::Bit => ".area BIT (BIT,ABS)\n",
207            Self::Xdata => ".area XDATA (XDATA,ABS)\n",
208        }
209    }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
213pub struct PhysicalAddr {
214    pub space: AddressSpace,
215    pub offset: AddressValue,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
219pub struct Xref {
220    pub from: PhysicalAddr,
221    pub to: PhysicalAddr,
222    pub xref_type: XrefType,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
226pub enum XrefType {
227    Call,
228    Jump,
229    Data,
230}
231
232pub fn branch_target_operand_index(insn: &Instruction) -> Option<usize> {
233    branch_target(insn)?;
234    match insn.mnemonic() {
235        Mnemonic::LJMP | Mnemonic::LCALL | Mnemonic::AJMP | Mnemonic::ACALL | Mnemonic::SJMP => {
236            Some(0)
237        }
238        _ => {
239            let decoded = insn.as_string();
240            let operand_count = decoded.split_once(' ').map_or(0, |(_, rest)| {
241                if rest.is_empty() {
242                    0
243                } else {
244                    rest.split(',').count()
245                }
246            });
247            if operand_count == 0 {
248                None
249            } else {
250                Some(operand_count - 1)
251            }
252        }
253    }
254}
255
256pub fn branch_target(insn: &Instruction) -> Option<u32> {
257    match insn.control_flow() {
258        ControlFlow::Jump { target } => Some(target),
259        ControlFlow::Call { target, .. } => Some(target),
260        ControlFlow::Choice { branch_target, .. } => Some(branch_target),
261        _ => None,
262    }
263}
264
265pub fn xrefs_from_instruction(instruction: &Instruction, source: PhysicalAddr) -> Vec<Xref> {
266    let mut xrefs = Vec::new();
267    let mut push = |to_offset: u32, xref_type: XrefType| {
268        xrefs.push(Xref {
269            from: source,
270            to: PhysicalAddr {
271                space: source.space,
272                offset: to_offset,
273            },
274            xref_type,
275        });
276    };
277
278    match instruction.control_flow() {
279        ControlFlow::Jump { target } => {
280            push(target, xref_type_for(instruction.mnemonic()));
281        }
282        ControlFlow::Call { target, .. } => push(target, XrefType::Call),
283        ControlFlow::Choice { branch_target, .. } => push(branch_target, XrefType::Jump),
284        _ => {}
285    }
286
287    xrefs
288}
289
290pub fn xrefs_to_target(
291    instruction: &Instruction,
292    source: PhysicalAddr,
293    target: &PhysicalAddr,
294) -> Vec<Xref> {
295    xrefs_from_instruction(instruction, source)
296        .into_iter()
297        .filter(|xref| xref.to == *target)
298        .collect()
299}
300
301fn xref_type_for(opcode: Mnemonic) -> XrefType {
302    match opcode {
303        Mnemonic::LCALL | Mnemonic::ACALL => XrefType::Call,
304        _ => XrefType::Jump,
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    // The `$dsl::address` token is advisory: a non-DSL serializer ignores the
313    // newtype name and (de)serializes the inner `(space, offset)` tuple. So the
314    // address types still round-trip through stock serde formats like JSON.
315    #[test]
316    fn space_address_value_json_round_trip() {
317        let addr = SpaceAddressValue {
318            space: AddressSpace::Xdata,
319            offset: 0x1234,
320        };
321        let json = serde_json::to_string(&addr).unwrap();
322        assert_eq!(json, r#"["XDATA",4660]"#);
323        assert_eq!(serde_json::from_str::<SpaceAddressValue>(&json).unwrap(), addr);
324    }
325
326    #[test]
327    fn space_address_range_json_round_trip() {
328        let range = SpaceAddressRange {
329            space: AddressSpace::Code,
330            range: AddressRange::new(0x10, 0x20),
331        };
332        let json = serde_json::to_string(&range).unwrap();
333        assert_eq!(json, r#"["CODE",16,32]"#);
334        assert_eq!(
335            serde_json::from_str::<SpaceAddressRange>(&json).unwrap(),
336            range
337        );
338    }
339
340    #[test]
341    fn unknown_space_is_rejected() {
342        let err = serde_json::from_str::<SpaceAddressValue>(r#"["NOPE",0]"#).unwrap_err();
343        assert!(err.to_string().contains("unknown address space"));
344    }
345}