Skip to main content

i8051_disassembler/commands/
mod.rs

1/// Assert a command round-trips through the DSL in both directions: that it
2/// renders to exactly `$dsl`, and that `$dsl` parses back to it. Emits a
3/// `#[test]` named `$name`.
4///
5/// ```ignore
6/// serialize_test!(
7///     auto_disassemble,
8///     "auto_disassemble(address=CODE:0x1234)",
9///     AutoDisassemble { address: (AddressSpace::Code, 0x1234).into() }
10/// );
11/// ```
12macro_rules! serialize_test {
13    ($name:ident, $dsl:expr, $variant:ident $body:tt $(,)?) => {
14        #[cfg(test)]
15        #[test]
16        fn $name() {
17            let command: ::std::boxed::Box<dyn $crate::commands::Command> =
18                ::std::boxed::Box::new($crate::commands::$variant $body);
19            assert_eq!($crate::store::to_dsl(&*command), $dsl, "Rust -> DSL");
20            let parsed = $crate::store::from_dsl($dsl).expect("DSL -> Rust");
21            assert!(
22                *parsed == *command,
23                "DSL -> Rust: {parsed:?} != {command:?}",
24            );
25        }
26    };
27}
28
29/// Register one or more command payload types: implement [`Command`] for each
30/// (forwarding to its [`Apply`] impl) and add it to the [`COMMANDS`] registry
31/// under its snake_case name, computed from the type name at compile time.
32macro_rules! register_commands {
33    ($($type:ident),* $(,)?) => {
34        $(
35            impl $type {
36                const COMMAND_NAME: &'static str = {
37                    const SRC: &str = stringify!($type);
38                    const LEN: usize = $crate::commands::snake_len(SRC);
39                    const BYTES: [u8; LEN] = $crate::commands::snake_bytes::<LEN>(SRC);
40                    match ::core::str::from_utf8(&BYTES) {
41                        ::core::result::Result::Ok(name) => name,
42                        ::core::result::Result::Err(_) => ::core::panic!("non-ASCII command name"),
43                    }
44                };
45            }
46
47            impl $crate::commands::Command for $type {
48                fn apply(
49                    self: ::std::boxed::Box<Self>,
50                    db: &mut $crate::db::Db,
51                    env: ::core::option::Option<&dyn $crate::commands::Environment>,
52                ) -> ::core::result::Result<
53                    ::std::vec::Vec<::std::boxed::Box<dyn $crate::commands::Command>>,
54                    $crate::db::Error,
55                > {
56                    $crate::commands::Apply::apply(*self, db, env)
57                }
58
59                fn name(&self) -> &'static str {
60                    <$type>::COMMAND_NAME
61                }
62
63                fn to_value(&self) -> $crate::store::value::Value {
64                    $crate::store::ser::to_value(self).expect("command serialization is infallible")
65                }
66
67                fn as_any(&self) -> &dyn ::core::any::Any {
68                    self
69                }
70            }
71
72            #[::scattered_collect::scatter($crate::commands::COMMANDS)]
73            #[allow(non_upper_case_globals)]
74            static $type: (&'static str, $crate::commands::CommandParser) =
75                (<$type>::COMMAND_NAME, $crate::commands::parse::<$type>);
76        )*
77    };
78}
79
80mod auto_disassemble;
81mod bytes;
82mod comment;
83mod equivalent;
84mod function;
85mod label;
86mod note;
87
88use std::any::Any;
89use std::collections::BTreeMap;
90use std::io;
91
92pub use auto_disassemble::AutoDisassemble;
93pub use bytes::{ClearBytes, MapBytes, SetConstantBytes};
94pub use comment::{ClearComment, SetComment};
95pub use equivalent::{ClearEquivalents, SetEquivalent};
96pub use function::{ClearFunction, SetFunction};
97pub use label::{ClearLabel, SetLabel};
98pub use note::{ClearNote, SetNote};
99
100use scattered_collect::{ScatteredMap, gather};
101use serde::de::DeserializeOwned;
102
103use crate::address::AddressValue;
104use crate::db::{Db, Error};
105use crate::store::error::DslError;
106use crate::store::value::Value;
107
108pub trait Environment {
109    fn load_file_bytes(
110        &self,
111        file: &str,
112        offset: usize,
113        size: AddressValue,
114    ) -> Result<Vec<u8>, io::Error>;
115}
116
117/// A disassembly mutation. Implemented by each payload type via
118/// [`register_commands!`]; the per-command logic lives in its [`Apply`] impl.
119pub trait Command: std::fmt::Debug {
120    /// Apply the command, returning the inverse commands that undo it.
121    fn apply(
122        self: Box<Self>,
123        db: &mut Db,
124        env: Option<&dyn Environment>,
125    ) -> Result<Vec<Box<dyn Command>>, Error>;
126
127    /// The snake_case name this command is spelled with in the DSL.
128    fn name(&self) -> &'static str;
129
130    /// The payload as a DSL [`Value`] (always a [`Value::Struct`]).
131    fn to_value(&self) -> Value;
132
133    fn as_any(&self) -> &dyn Any;
134}
135
136impl PartialEq for dyn Command {
137    fn eq(&self, other: &Self) -> bool {
138        self.name() == other.name() && self.to_value() == other.to_value()
139    }
140}
141
142/// The per-command logic behind [`Command::apply`], hand-written per payload.
143pub trait Apply {
144    fn apply(
145        self,
146        db: &mut Db,
147        env: Option<&dyn Environment>,
148    ) -> Result<Vec<Box<dyn Command>>, Error>;
149}
150
151/// Box a command payload as a trait object (handy for building undo vectors).
152pub fn boxed(command: impl Command + 'static) -> Box<dyn Command> {
153    Box::new(command)
154}
155
156/// Parses a command's kwargs into a boxed payload of type `T`. The registry
157/// stores one monomorphization of this per command.
158pub type CommandParser = fn(BTreeMap<String, Value>) -> Result<Box<dyn Command>, DslError>;
159
160#[gather]
161pub static COMMANDS: ScatteredMap<&'static str, CommandParser>;
162
163pub fn parse<T: Command + DeserializeOwned + 'static>(
164    kwargs: BTreeMap<String, Value>,
165) -> Result<Box<dyn Command>, DslError> {
166    let value = Value::Struct {
167        name: String::new(),
168        fields: kwargs,
169    };
170    Ok(Box::new(crate::store::de::from_value::<T>(value)?))
171}
172
173/// Length of the snake_case form of an ASCII PascalCase identifier.
174pub const fn snake_len(s: &str) -> usize {
175    let bytes = s.as_bytes();
176    let mut len = 0;
177    let mut i = 0;
178    while i < bytes.len() {
179        if i > 0 && bytes[i].is_ascii_uppercase() {
180            len += 1; // for the inserted '_'
181        }
182        len += 1;
183        i += 1;
184    }
185    len
186}
187
188/// snake_case an ASCII PascalCase identifier into an `N`-byte buffer, where `N`
189/// is [`snake_len`] of the same string.
190pub const fn snake_bytes<const N: usize>(s: &str) -> [u8; N] {
191    let bytes = s.as_bytes();
192    let mut out = [0u8; N];
193    let mut out_i = 0;
194    let mut i = 0;
195    while i < bytes.len() {
196        let byte = bytes[i];
197        if byte.is_ascii_uppercase() {
198            if i > 0 {
199                out[out_i] = b'_';
200                out_i += 1;
201            }
202            out[out_i] = byte.to_ascii_lowercase();
203        } else {
204            out[out_i] = byte;
205        }
206        out_i += 1;
207        i += 1;
208    }
209    out
210}