Skip to main content

i8051_disassembler/store/
value.rs

1use std::collections::BTreeMap;
2
3/// The DSL abstract syntax tree. Every serializable value is lowered into this
4/// shape, then rendered to text (or parsed back from it). It is the single
5/// pivot between Rust types and the textual DSL — both the generic
6/// [`Serializer`](crate::store::ser) and [`Deserializer`](crate::store::de)
7/// speak only `Value`.
8#[derive(Debug, Clone, PartialEq)]
9pub enum Value {
10    Null,
11    Bool(bool),
12    Int(u64),
13    String(String),
14    List(Vec<Value>),
15    Set(Vec<Value>),
16    Map(BTreeMap<String, Value>),
17    Address {
18        space: String,
19        offset: u64,
20    },
21    AddressRange {
22        space: String,
23        start: u64,
24        end: u64,
25    },
26    /// A top-level command: `name(field=value, ...)`.
27    Call {
28        name: String,
29        kwargs: BTreeMap<String, Value>,
30    },
31    /// A named struct: `Name(field=value, ...)`.
32    Struct {
33        name: String,
34        fields: BTreeMap<String, Value>,
35    },
36    /// An enum variant: `Type::Variant`, `Type::Variant(a, b)`, or
37    /// `Type::Variant(field=value)`.
38    Enum {
39        type_name: String,
40        variant: String,
41        args: EnumArgs,
42    },
43}
44
45#[derive(Debug, Clone, PartialEq)]
46pub enum EnumArgs {
47    Unit,
48    Positional(Vec<Value>),
49    Named(BTreeMap<String, Value>),
50}
51
52impl Value {
53    pub fn as_bool(&self) -> Option<bool> {
54        match self {
55            Self::Bool(v) => Some(*v),
56            _ => None,
57        }
58    }
59
60    pub fn as_u64(&self) -> Option<u64> {
61        match self {
62            Self::Int(v) => Some(*v),
63            _ => None,
64        }
65    }
66
67    pub fn as_str(&self) -> Option<&str> {
68        match self {
69            Self::String(v) => Some(v),
70            _ => None,
71        }
72    }
73
74    pub fn field(&self, name: &str) -> Option<&Value> {
75        match self {
76            Self::Struct { fields, .. } | Self::Call { kwargs: fields, .. } => fields.get(name),
77            _ => None,
78        }
79    }
80
81    /// Render this value to DSL text.
82    pub fn render(&self) -> String {
83        match self {
84            Self::Null => "None".into(),
85            Self::Bool(true) => "True".into(),
86            Self::Bool(false) => "False".into(),
87            Self::Int(v) => format!("0x{v:X}"),
88            Self::String(s) => render_string(s),
89            Self::List(items) => format!("[{}]", render_seq(items)),
90            Self::Set(items) => format!("{{{}}}", render_seq(items)),
91            Self::Map(map) => format!("{{{}}}", render_map(map)),
92            Self::Address { space, offset } => format!("{space}:0x{offset:X}"),
93            Self::AddressRange { space, start, end } => format!("{space}:0x{start:X}..0x{end:X}"),
94            Self::Call { name, kwargs } => format!("{name}({})", render_kwargs(kwargs)),
95            Self::Struct { name, fields } => format!("{name}({})", render_kwargs(fields)),
96            Self::Enum {
97                type_name,
98                variant,
99                args,
100            } => match args {
101                EnumArgs::Unit => format!("{type_name}::{variant}"),
102                EnumArgs::Positional(values) => {
103                    format!("{type_name}::{variant}({})", render_seq(values))
104                }
105                EnumArgs::Named(fields) => {
106                    format!("{type_name}::{variant}({})", render_kwargs(fields))
107                }
108            },
109        }
110    }
111}
112
113fn render_seq(items: &[Value]) -> String {
114    items
115        .iter()
116        .map(Value::render)
117        .collect::<Vec<_>>()
118        .join(", ")
119}
120
121fn render_kwargs(fields: &BTreeMap<String, Value>) -> String {
122    fields
123        .iter()
124        .map(|(key, value)| format!("{key}={}", value.render()))
125        .collect::<Vec<_>>()
126        .join(", ")
127}
128
129fn render_map(map: &BTreeMap<String, Value>) -> String {
130    map.iter()
131        .map(|(key, value)| format!("{}: {}", render_string(key), value.render()))
132        .collect::<Vec<_>>()
133        .join(", ")
134}
135
136/// Render a string, choosing the most readable of `"..."`, `r"..."`, or
137/// `r#"..."#` so the result re-lexes to the same contents.
138fn render_string(value: &str) -> String {
139    if !value.contains(['\n', '\r', '"', '\\']) {
140        return format!("\"{value}\"");
141    }
142    if !value.contains('"') {
143        return format!("r\"{value}\"");
144    }
145    let mut delim = String::from("#");
146    while value.contains(&format!("\"{delim}")) {
147        delim.push('#');
148    }
149    format!("r{delim}\"{value}\"{delim}")
150}