Skip to main content

i8051_script/
lib.rs

1//! The DSL value model, shared by the disassembler and the `dsl!` macro.
2
3use std::collections::BTreeMap;
4
5/// The DSL abstract syntax tree: the one pivot between Rust types and
6/// DSL text.
7#[derive(Debug, Clone, PartialEq)]
8pub enum Value {
9    Null,
10    Bool(bool),
11    Int(u64),
12    String(String),
13    List(Vec<Value>),
14    Set(Vec<Value>),
15    Map(BTreeMap<String, Value>),
16    Address {
17        space: String,
18        offset: u64,
19    },
20    AddressRange {
21        space: String,
22        start: u64,
23        end: u64,
24    },
25    /// A set of addresses within one space: `CODE:{0x10..0x13, 0x20}`. Ranges
26    /// are half-open `(start, end)`; a singleton has `end == start + 1`.
27    AddressSet {
28        space: String,
29        ranges: Vec<(u64, u64)>,
30    },
31    /// A top-level command: `name(field=value, ...)`.
32    Call {
33        name: String,
34        kwargs: Fields,
35    },
36    /// A named struct: `Name(field=value, ...)`.
37    Struct {
38        name: String,
39        fields: Fields,
40    },
41    /// An enum variant: `Type::Variant`, `Type::Variant(a, b)`, or
42    /// `Type::Variant(field=value)`.
43    Enum {
44        type_name: String,
45        variant: String,
46        args: EnumArgs,
47    },
48    /// Pre-rendered DSL text, spliced as-is. Never produced by parsing.
49    Verbatim(String),
50}
51
52/// Fields in the order they were declared or written.
53pub type Fields = Vec<(String, Value)>;
54
55#[derive(Debug, Clone, PartialEq)]
56pub enum EnumArgs {
57    Unit,
58    Positional(Vec<Value>),
59    Named(Fields),
60}
61
62impl Value {
63    pub fn as_bool(&self) -> Option<bool> {
64        match self {
65            Self::Bool(v) => Some(*v),
66            _ => None,
67        }
68    }
69
70    pub fn as_u64(&self) -> Option<u64> {
71        match self {
72            Self::Int(v) => Some(*v),
73            _ => None,
74        }
75    }
76
77    pub fn as_str(&self) -> Option<&str> {
78        match self {
79            Self::String(v) => Some(v),
80            _ => None,
81        }
82    }
83
84    pub fn field(&self, name: &str) -> Option<&Value> {
85        match self {
86            Self::Struct { fields, .. } | Self::Call { kwargs: fields, .. } => fields
87                .iter()
88                .find(|(key, _)| key == name)
89                .map(|(_, value)| value),
90            _ => None,
91        }
92    }
93
94    /// Render this value to DSL text.
95    pub fn render(&self) -> String {
96        match self {
97            Self::Null => "None".into(),
98            Self::Bool(true) => "True".into(),
99            Self::Bool(false) => "False".into(),
100            Self::Int(v) => format!("0x{v:X}"),
101            Self::String(s) => render_string(s),
102            Self::List(items) => format!("[{}]", render_seq(items)),
103            Self::Set(items) => format!("{{{}}}", render_seq(items)),
104            Self::Map(map) => format!("{{{}}}", render_map(map)),
105            Self::Address { space, offset } => format!("{space}:0x{offset:X}"),
106            Self::AddressRange { space, start, end } => format!("{space}:0x{start:X}..0x{end:X}"),
107            Self::AddressSet { space, ranges } => {
108                let body = ranges
109                    .iter()
110                    .map(|&(start, end)| {
111                        if end == start + 1 {
112                            format!("0x{start:X}")
113                        } else {
114                            format!("0x{start:X}..0x{end:X}")
115                        }
116                    })
117                    .collect::<Vec<_>>()
118                    .join(", ");
119                format!("{space}:{{{body}}}")
120            }
121            Self::Call { name, kwargs } => format!("{name}({})", render_kwargs(kwargs)),
122            Self::Struct { name, fields } => format!("{name}({})", render_kwargs(fields)),
123            Self::Enum {
124                type_name,
125                variant,
126                args,
127            } => match args {
128                EnumArgs::Unit => format!("{type_name}::{variant}"),
129                EnumArgs::Positional(values) => {
130                    format!("{type_name}::{variant}({})", render_seq(values))
131                }
132                EnumArgs::Named(fields) => {
133                    format!("{type_name}::{variant}({})", render_kwargs(fields))
134                }
135            },
136            Self::Verbatim(text) => text.clone(),
137        }
138    }
139}
140
141/// Render `name(key=value, ...)` in the given key order, so arguments
142/// stay in the command's declared order. Appends an optional
143/// `# comment`. The `dsl!` macro expands to this.
144pub fn render_call(name: &str, kwargs: &[(&str, Value)], comment: Option<&str>) -> String {
145    let call = Value::Call {
146        name: name.to_string(),
147        kwargs: kwargs
148            .iter()
149            .map(|(key, value)| (key.to_string(), value.clone()))
150            .collect(),
151    }
152    .render();
153    match comment {
154        Some(comment) => format!("{call}  # {comment}"),
155        None => call,
156    }
157}
158
159fn render_seq(items: &[Value]) -> String {
160    items
161        .iter()
162        .map(Value::render)
163        .collect::<Vec<_>>()
164        .join(", ")
165}
166
167fn render_kwargs(fields: &Fields) -> String {
168    fields
169        .iter()
170        .map(|(key, value)| format!("{key}={}", value.render()))
171        .collect::<Vec<_>>()
172        .join(", ")
173}
174
175fn render_map(map: &BTreeMap<String, Value>) -> String {
176    map.iter()
177        .map(|(key, value)| format!("{}: {}", render_string(key), value.render()))
178        .collect::<Vec<_>>()
179        .join(", ")
180}
181
182/// Render a string, choosing the most readable of `"..."`, `r"..."`, or
183/// `r#"..."#` so the result re-lexes to the same contents.
184fn render_string(value: &str) -> String {
185    if !value.contains(['\n', '\r', '"', '\\']) {
186        return format!("\"{value}\"");
187    }
188    if !value.contains(['"', '\n', '\r']) {
189        return format!("r\"{value}\"");
190    }
191    let mut delim = String::from("#");
192    while value.contains(&format!("\"{delim}")) {
193        delim.push('#');
194    }
195    format!("r{delim}\"{value}\"{delim}")
196}