Skip to main content

i8051_disassembler/commands/
mod.rs

1/// Assert a command round-trips.
2///
3/// ```ignore
4/// serialize_test!(
5///     auto_disassemble,
6///     "auto_disassemble(address=CODE:0x1234)",
7///     AutoDisassemble { address: (crate::platform::i8051::CODE, 0x1234).into() }
8/// );
9/// ```
10macro_rules! serialize_test {
11    ($name:ident, $dsl:expr, $variant:ident $body:tt $(,)?) => {
12        #[cfg(test)]
13        #[test]
14        fn $name() {
15            let command: ::std::boxed::Box<dyn $crate::commands::Command> =
16                ::std::boxed::Box::new($crate::commands::$variant $body);
17            assert_eq!($crate::store::to_dsl(&*command), $dsl, "Rust -> DSL");
18            let parsed = $crate::store::from_dsl($dsl).expect("DSL -> Rust");
19            assert!(
20                *parsed == *command,
21                "DSL -> Rust: {parsed:?} != {command:?}",
22            );
23        }
24    };
25}
26
27/// Register a command from its constructor's argument list.
28///
29/// Each `name: Type` becomes an `impl Into<Type>` parameter of a generated `pub
30/// fn new(..) -> Self`. Also implements [`Command`] and adds a [`CommandEntry`]
31/// (doc, argument signature, DSL parser) to the link-time [`COMMANDS`]
32/// registry, keyed by the type name (in `snake_case`).
33///
34/// ```ignore
35/// register!(SetLabel(
36///     /// Name the code `address` with `label`.
37///     address: SpaceAddressValue,
38///     label: String,
39/// ));
40/// ```
41macro_rules! register {
42    (
43        $type:ident (
44            $(#[doc = $doc:literal])*
45            $($arg:ident : $argty:ty),* $(,)?
46        )
47    ) => {
48        impl $type {
49            const COMMAND_NAME: &'static str = {
50                const SRC: &str = stringify!($type);
51                const LEN: usize = $crate::commands::snake_len(SRC);
52                const BYTES: [u8; LEN] = $crate::commands::snake_bytes::<LEN>(SRC);
53                match ::core::str::from_utf8(&BYTES) {
54                    ::core::result::Result::Ok(name) => name,
55                    ::core::result::Result::Err(_) => ::core::panic!("non-ASCII command name"),
56                }
57            };
58
59            $(#[doc = $doc])*
60            pub fn new($($arg: impl ::core::convert::Into<$argty>),*) -> Self {
61                Self { $($arg: $arg.into()),* }
62            }
63        }
64
65        impl $crate::commands::Command for $type {
66            fn apply(
67                self: ::std::boxed::Box<Self>,
68                db: &mut $crate::db::Db,
69                env: ::core::option::Option<&dyn $crate::commands::Environment>,
70            ) -> ::core::result::Result<
71                ::std::vec::Vec<::std::boxed::Box<dyn $crate::commands::Command>>,
72                $crate::db::Error,
73            > {
74                $crate::commands::Apply::apply(*self, db, env)
75            }
76
77            fn name(&self) -> &'static str {
78                <$type>::COMMAND_NAME
79            }
80
81            fn to_value(&self) -> $crate::store::value::Value {
82                $crate::store::ser::to_value(self).expect("command serialization is infallible")
83            }
84
85            fn as_any(&self) -> &dyn ::core::any::Any {
86                self
87            }
88        }
89
90        #[::scattered_collect::scatter($crate::commands::COMMANDS)]
91        const _: (&'static str, $crate::commands::CommandEntry) = (
92            <$type>::COMMAND_NAME,
93            $crate::commands::CommandEntry {
94                doc: ::core::concat!($($doc, "\n",)*),
95                args: &[$(
96                    $crate::commands::CommandArg {
97                        name: ::core::stringify!($arg),
98                        ty: ::core::stringify!($argty),
99                        kind: <$argty as $crate::commands::DslArg>::KIND,
100                        slug: <$argty as $crate::commands::DslArg>::SLUG,
101                        hint: <$argty as $crate::commands::DslArg>::HINT,
102                        example: <$argty as $crate::commands::DslArg>::EXAMPLE,
103                        check: |value: &$crate::store::value::Value| {
104                            $crate::store::de::from_value::<$argty>(
105                                ::core::clone::Clone::clone(value),
106                            )
107                            .map(|_| ())
108                        },
109                    }
110                ),*],
111                parse: $crate::commands::parse::<$type>,
112            },
113        );
114    };
115}
116
117mod auto_disassemble;
118mod bytes;
119mod comment;
120mod cpu;
121mod decoding;
122mod equivalent;
123mod extent;
124mod function;
125mod label;
126mod note;
127mod operand;
128mod platform_addr;
129mod pointer;
130
131use std::any::Any;
132use std::io;
133
134pub use auto_disassemble::{AutoDisassemble, ClearAutoDisassembleRoot};
135pub use bytes::{MapBytes, SetConstantBytes, UnmapBytes};
136pub use comment::{ClearComment, SetComment};
137pub use cpu::{ClearCpu, SetCpu};
138pub use decoding::{ClearAddressBits, SetAddressBits};
139pub use equivalent::ClearEquivalents;
140pub use extent::{DisassembleRange, MarkData, MarkUnknown};
141pub use function::{ClearFunction, SetFunction};
142pub use label::{ClearLabel, SetLabel, normalize_label};
143pub use note::{ClearNote, SetNote};
144pub use operand::OverrideOperand;
145pub use platform_addr::{DisablePlatformAddress, RestorePlatformAddress};
146pub use pointer::{ClearOperandType, SetOperandPointer, SetOperandValue};
147
148use scattered_collect::{ScatteredMap, gather};
149use serde::de::DeserializeOwned;
150
151use crate::address::{AddressValue, SpaceAddressRange, SpaceAddressSet, SpaceAddressValue};
152use crate::db::{DataType, Db, Error, Function, Note, NoteId, OperandOverride};
153use crate::store::error::DslError;
154use crate::store::value::{Fields, Value};
155
156pub trait Environment {
157    fn load_file_bytes(
158        &self,
159        file: &str,
160        offset: usize,
161        size: AddressValue,
162    ) -> Result<Vec<u8>, io::Error>;
163}
164
165/// A disassembly mutation.
166pub trait Command: std::fmt::Debug {
167    fn apply(
168        self: Box<Self>,
169        db: &mut Db,
170        env: Option<&dyn Environment>,
171    ) -> Result<Vec<Box<dyn Command>>, Error>;
172
173    /// The snake_case DSL name.
174    fn name(&self) -> &'static str;
175
176    /// The payload as a DSL [`Value`] (always a [`Value::Struct`]).
177    fn to_value(&self) -> Value;
178
179    fn as_any(&self) -> &dyn Any;
180}
181
182impl PartialEq for dyn Command {
183    fn eq(&self, other: &Self) -> bool {
184        self.name() == other.name() && self.to_value() == other.to_value()
185    }
186}
187
188/// The per-command logic behind [`Command::apply`], hand-written per payload.
189pub trait Apply {
190    fn apply(
191        self,
192        db: &mut Db,
193        env: Option<&dyn Environment>,
194    ) -> Result<Vec<Box<dyn Command>>, Error>;
195}
196
197/// Box a command payload as a trait object.
198pub fn boxed(command: impl Command + 'static) -> Box<dyn Command> {
199    Box::new(command)
200}
201
202/// Parses a command's kwargs into a boxed payload of type `T`. The registry
203/// stores one monomorphization of this per command.
204pub type CommandParser = fn(Fields) -> Result<Box<dyn Command>, DslError>;
205
206/// Type-checks one DSL value.
207pub type ArgCheck = fn(&Value) -> Result<(), DslError>;
208
209/// The shape axis coercion and JSON typing switch on.
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum ArgKind {
212    /// A single address, e.g. `CODE:0x10`.
213    Address,
214    /// An address range, e.g. `CODE:0x10..0x20`.
215    AddressRange,
216    /// A set of addresses, e.g. `CODE:{0x10, 0x20..0x30}`.
217    AddressSet,
218    /// Free text.
219    Text,
220    /// A byte offset or length.
221    Offset,
222    /// A single byte value.
223    Byte,
224    /// A domain type (`Note`, `Function`, `DataType`, ...).
225    Struct,
226    /// A boolean flag: `True` / `False`.
227    Flag,
228}
229
230impl ArgKind {
231    pub fn numeric(self) -> bool {
232        matches!(self, ArgKind::Offset | ArgKind::Byte)
233    }
234}
235
236/// The candidate closest to `target` by edit distance, if any is close enough
237/// to plausibly be a typo.
238pub fn closest<'a>(target: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
239    candidates
240        .into_iter()
241        .map(|c| (crate::strings::levenshtein(target, c), c))
242        .filter(|(d, c)| *d <= 2.max(c.len() / 3))
243        .min_by_key(|(d, _)| *d)
244        .map(|(_, c)| c)
245}
246
247pub trait DslArg {
248    /// How the generic machinery handles this argument's shape.
249    const KIND: ArgKind;
250    /// The stable wire slug a schema/UI switches on, finer than the JSON type.
251    const SLUG: &'static str;
252    /// A one-line syntax hint — the single string errors, schema hints, and
253    /// help all share.
254    const HINT: &'static str;
255    /// A canonical example, or `None` for free text (whose example
256    /// depends on the argument's *name*, not its type).
257    const EXAMPLE: Option<&'static str>;
258}
259
260macro_rules! dsl_arg {
261    ($($ty:ty),+ => $kind:ident, $slug:literal, $hint:literal, $example:expr $(,)?) => {
262        $(impl DslArg for $ty {
263            const KIND: ArgKind = ArgKind::$kind;
264            const SLUG: &'static str = $slug;
265            const HINT: &'static str = $hint;
266            const EXAMPLE: Option<&'static str> = $example;
267        })+
268    };
269}
270
271dsl_arg!(SpaceAddressValue => Address, "address", "a DSL address, e.g. CODE:0x100", Some("CODE:0x100"));
272dsl_arg!(SpaceAddressRange => AddressRange, "address_range",
273    "an address range (end exclusive), e.g. CODE:0x10..0x20, or a bare address for one byte",
274    Some("CODE:0x10..0x20"));
275dsl_arg!(SpaceAddressSet => AddressSet, "address_set",
276    "an address set, e.g. CODE:{0x10..0x20, 0x30}, or a bare address/range", Some("CODE:{0x10..0x20}"));
277dsl_arg!(String => Text, "text", "quoted text, e.g. \"...\"", None);
278dsl_arg!(usize, AddressValue => Offset, "offset", "a byte offset or length", Some("0x0"));
279dsl_arg!(u8 => Byte, "byte", "a byte value, 0-255", Some("0xFF"));
280dsl_arg!(DataType => Struct, "data_type", "a data type, e.g. DataType::Byte", Some("DataType::Byte"));
281dsl_arg!(Option<OperandOverride> => Struct, "operand",
282    "an operand override, or None to clear", Some("None"));
283dsl_arg!(Function => Struct, "function",
284    "a function definition, e.g. Function(addr=..., name=\"...\", length=...)",
285    Some("Function(addr=CODE:0x100, name=\"main\", signature=None, length=0x40, noreturn=False)"));
286dsl_arg!(Note => Struct, "note",
287    "a note, e.g. Note(content=\"...\", tags=[\"todo\"]), or bare \"text\"",
288    Some("Note(content=\"...\", tags=[\"todo\"])"));
289dsl_arg!(NoteId => Struct, "note_id", "a note id", Some("\"0000000000000YN222X7N2CE7T\""));
290dsl_arg!(bool => Flag, "flag", "True or False", Some("False"));
291
292#[derive(Debug, Clone, Copy)]
293pub struct CommandArg {
294    pub name: &'static str,
295    /// The raw constructor target type, e.g. `"SpaceAddressValue"`.
296    pub ty: &'static str,
297    pub kind: ArgKind,
298    pub slug: &'static str,
299    pub hint: &'static str,
300    pub example: Option<&'static str>,
301    pub check: ArgCheck,
302}
303
304/// A command's registry entry, built by [`register!`].
305#[derive(Debug, Clone, Copy)]
306pub struct CommandEntry {
307    pub doc: &'static str,
308    pub args: &'static [CommandArg],
309    pub parse: CommandParser,
310}
311
312#[gather]
313pub static COMMANDS: ScatteredMap<&'static str, CommandEntry>;
314
315pub fn parse<T: Command + DeserializeOwned + 'static>(
316    kwargs: Fields,
317) -> Result<Box<dyn Command>, DslError> {
318    let value = Value::Struct {
319        name: String::new(),
320        fields: kwargs,
321    };
322    Ok(Box::new(crate::store::de::from_value::<T>(value)?))
323}
324
325/// Length of the snake_case form of an ASCII PascalCase identifier.
326pub const fn snake_len(s: &str) -> usize {
327    let bytes = s.as_bytes();
328    let mut len = 0;
329    let mut i = 0;
330    while i < bytes.len() {
331        if i > 0 && bytes[i].is_ascii_uppercase() {
332            len += 1; // for the inserted '_'
333        }
334        len += 1;
335        i += 1;
336    }
337    len
338}
339
340/// snake_case an ASCII PascalCase identifier into an `N`-byte buffer, where `N`
341/// is [`snake_len`] of the same string.
342pub const fn snake_bytes<const N: usize>(s: &str) -> [u8; N] {
343    let bytes = s.as_bytes();
344    let mut out = [0u8; N];
345    let mut out_i = 0;
346    let mut i = 0;
347    while i < bytes.len() {
348        let byte = bytes[i];
349        if byte.is_ascii_uppercase() {
350            if i > 0 {
351                out[out_i] = b'_';
352                out_i += 1;
353            }
354            out[out_i] = byte.to_ascii_lowercase();
355        } else {
356            out[out_i] = byte;
357        }
358        out_i += 1;
359        i += 1;
360    }
361    out
362}
363
364#[cfg(test)]
365mod tests {
366    use super::COMMANDS;
367
368    /// The registry exposes each command's constructor doc + typed signature,
369    /// which an MCP server can enumerate without a hand-written schema.
370    #[test]
371    fn registry_captures_constructor_signature() {
372        let entry = COMMANDS.get("set_label").expect("set_label is registered");
373        assert!(entry.doc.contains("Name the code"), "doc: {:?}", entry.doc);
374        let args: Vec<(&str, &str, super::ArgKind)> =
375            entry.args.iter().map(|a| (a.name, a.ty, a.kind)).collect();
376        assert_eq!(
377            args,
378            [
379                ("address", "SpaceAddressValue", super::ArgKind::Address),
380                ("label", "String", super::ArgKind::Text),
381                ("provisional", "bool", super::ArgKind::Flag),
382                ("local", "bool", super::ArgKind::Flag),
383            ]
384        );
385    }
386
387    #[test]
388    fn arg_kinds_from_types() {
389        use super::ArgKind::*;
390        let kinds = |name: &str| -> Vec<super::ArgKind> {
391            COMMANDS
392                .get(name)
393                .unwrap()
394                .args
395                .iter()
396                .map(|a| a.kind)
397                .collect()
398        };
399        assert_eq!(kinds("map_bytes"), [Address, Text, Offset, Offset]);
400        assert_eq!(kinds("set_constant_bytes"), [AddressRange, Byte]);
401        assert_eq!(kinds("unmap_bytes"), [AddressSet]);
402        assert_eq!(kinds("disassemble_range"), [AddressRange, Flag]);
403        assert_eq!(kinds("mark_data"), [AddressRange, Struct]);
404        assert_eq!(kinds("override_operand"), [Address, Byte, Struct]);
405        assert_eq!(kinds("set_note"), [AddressRange, Struct]);
406        assert_eq!(kinds("clear_note"), [Struct]);
407    }
408
409    #[test]
410    fn struct_args_keep_slug() {
411        // ...but stay distinguishable on the wire via the type's slug
412        let arg = |cmd: &str, arg: &str| {
413            let entry = COMMANDS.get(cmd).unwrap();
414            *entry.args.iter().find(|a| a.name == arg).unwrap()
415        };
416        let note = arg("set_note", "note");
417        assert_eq!(note.kind, super::ArgKind::Struct);
418        assert_eq!(note.slug, "note");
419        assert_eq!(arg("mark_data", "data_type").slug, "data_type");
420    }
421}