Skip to main content

scripting/
debug_value.rs

1//! Decodes a script-mode program's result from its output buffer. The result
2//! is the run of `DebugValue` entities (other entities, such as a created tag,
3//! may be interleaved); a list is a pre-order `List` … `ListEnd` run. When
4//! several values were written, the last complete one is the result.
5
6use crate::runtime::guest_fraction;
7use nomiscript::{Closure, EntityKind, Fraction, Number, Value, entity_layout, vec_to_list};
8use scripting_format::{
9    DEBUG_VALUE_DATA_SIZE, DebugValueData, ENTITY_HEADER_SIZE, EntityHeader, EntityType,
10    OUTPUT_HEADER_SIZE, OutputHeader, ValueType,
11};
12use uuid::Uuid;
13
14/// The commodity id's inline bytes after an atomic money's fixed data.
15const COMMODITY_ID_BYTES: usize = 16;
16
17/// Why no result could be decoded from an output buffer.
18#[derive(Debug, thiserror::Error, PartialEq, Eq)]
19pub enum DecodeError {
20    /// The buffer is well formed but carries no result value.
21    #[error("{0}")]
22    Absent(&'static str),
23    #[error("{0}")]
24    Malformed(String),
25}
26
27type Result<T> = std::result::Result<T, DecodeError>;
28
29/// The script's output buffer within linear memory: exactly `size` bytes from
30/// `start`, so the decoder never reads what a script wrote past its capacity.
31pub fn output_region(memory: &[u8], start: usize, size: usize) -> Result<&[u8]> {
32    start
33        .checked_add(size)
34        .and_then(|end| memory.get(start..end))
35        .ok_or_else(|| runtime("output buffer lies outside memory"))
36}
37
38/// The script's result value from its output buffer `data`.
39pub fn decode_result(data: &[u8]) -> Result<Value> {
40    let header = OutputHeader::from_bytes(data).ok_or_else(|| runtime("invalid output header"))?;
41    if header.output_entity_count == 0 {
42        return Err(DecodeError::Absent("no output entities"));
43    }
44    let mut open: Vec<Open> = Vec::new();
45    let mut result = None;
46    let mut offset = OUTPUT_HEADER_SIZE;
47    for _ in 0..header.output_entity_count {
48        let entity = data
49            .get(offset..)
50            .and_then(EntityHeader::from_bytes)
51            .ok_or_else(|| runtime("invalid entity header"))?;
52        if entity.entity_type == EntityType::DebugValue as u8 {
53            match debug_value(data, entity.data_offset as usize)? {
54                Token::Open(kind) => open.push(Open {
55                    kind,
56                    items: Vec::new(),
57                }),
58                Token::Close => {
59                    let frame = open.pop().ok_or_else(|| runtime("unopened list end"))?;
60                    place(frame.finish()?, &mut open, &mut result);
61                }
62                Token::Atom(value) => place(value, &mut open, &mut result),
63            }
64        }
65        offset += ENTITY_HEADER_SIZE + entity.data_size as usize;
66    }
67    if !open.is_empty() {
68        return Err(runtime("unterminated list"));
69    }
70    result.ok_or(DecodeError::Absent("no debug value in output"))
71}
72
73#[derive(Clone, Copy)]
74enum Kind {
75    List,
76    Struct,
77}
78
79enum Token {
80    Open(Kind),
81    Close,
82    Atom(Value),
83}
84
85/// A list or struct whose `ListEnd` has not been read yet.
86struct Open {
87    kind: Kind,
88    items: Vec<Value>,
89}
90
91impl Open {
92    fn finish(self) -> Result<Value> {
93        match self.kind {
94            Kind::List => Ok(vec_to_list(self.items)),
95            Kind::Struct => struct_value(self.items),
96        }
97    }
98}
99
100/// `items` is the struct's name symbol then each field's keyword and value.
101fn struct_value(items: Vec<Value>) -> Result<Value> {
102    let mut items = items.into_iter();
103    let Some(Value::Symbol(name)) = items.next() else {
104        return Err(runtime("a struct without a name"));
105    };
106    let mut fields = Vec::new();
107    while let Some(key) = items.next() {
108        let Value::Symbol(key) = key else {
109            return Err(runtime("a struct field without a keyword"));
110        };
111        let value = items
112            .next()
113            .ok_or_else(|| runtime("a struct field without a value"))?;
114        fields.push((key.trim_start_matches(':').to_string(), value));
115    }
116    Ok(Value::Struct { name, fields })
117}
118
119fn place(value: Value, open: &mut [Open], result: &mut Option<Value>) {
120    match open.last_mut() {
121        Some(frame) => frame.items.push(value),
122        None => *result = Some(value),
123    }
124}
125
126/// The debug value whose data starts at `data_offset`. String bytes are inline
127/// right after the fixed `DebugValueData`, at `data1` (0 today) past it.
128fn debug_value(data: &[u8], data_offset: usize) -> Result<Token> {
129    let value = data
130        .get(data_offset..)
131        .and_then(DebugValueData::from_bytes)
132        .ok_or_else(|| runtime("invalid debug value data"))?;
133    let value_type =
134        ValueType::try_from(value.value_type).map_err(|()| runtime("unknown value type"))?;
135    Ok(match value_type {
136        ValueType::List => Token::Open(Kind::List),
137        ValueType::Struct => Token::Open(Kind::Struct),
138        ValueType::ListEnd => Token::Close,
139        ValueType::Nil => Token::Atom(Value::Nil),
140        ValueType::T => Token::Atom(Value::T),
141        ValueType::Number => Token::Atom(Value::Number(Number::Index(debug_index(&value)?))),
142        ValueType::Scalar => Token::Atom(Value::Number(Number::Scalar(debug_fraction(&value)?))),
143        ValueType::String | ValueType::Symbol => {
144            let text = inline_text(data, data_offset, &value)?;
145            Token::Atom(if value_type == ValueType::Symbol {
146                Value::Symbol(text)
147            } else {
148                Value::String(text)
149            })
150        }
151        ValueType::Commodity => Token::Atom(Value::Commodity {
152            amount: debug_fraction(&value)?,
153            commodity_id: inline_commodity_id(data, data_offset)?,
154        }),
155        ValueType::Closure => {
156            let closure = u32::try_from(value.data1).map_or_else(
157                |_| Closure::siteless(),
158                |site| Closure::new(site, Vec::new()),
159            );
160            Token::Atom(Value::Closure(closure))
161        }
162        ValueType::Entity => {
163            let kind = EntityKind::from_wire_code(value.data1)
164                .ok_or_else(|| runtime("unknown entity kind"))?;
165            Token::Atom(entity_tag(kind))
166        }
167    })
168}
169
170/// An entity reference on the wire is its kind alone: the struct named as
171/// the host's eval-path plist names it, with no fields; a condition is its
172/// own opaque value.
173fn entity_tag(kind: EntityKind) -> Value {
174    if kind == EntityKind::Condition {
175        return Value::Condition;
176    }
177    let name = entity_layout(kind).map_or(kind.type_name(), |layout| layout.label);
178    Value::Struct {
179        name: name.to_string(),
180        fields: Vec::new(),
181    }
182}
183
184/// The commodity id's two i64 halves (high, then low) inline right after the
185/// fixed `DebugValueData`, each in the host's byte order like the data
186/// fields themselves.
187fn inline_commodity_id(data: &[u8], data_offset: usize) -> Result<Uuid> {
188    let start = data_offset + DEBUG_VALUE_DATA_SIZE;
189    let bytes = data
190        .get(start..start + COMMODITY_ID_BYTES)
191        .ok_or_else(|| runtime("commodity id out of bounds"))?;
192    let half = |at: usize| {
193        bytes
194            .get(at..at + 8)
195            .and_then(|slice| <[u8; 8]>::try_from(slice).ok())
196            .map(u64::from_le_bytes)
197            .ok_or_else(|| runtime("commodity id out of bounds"))
198    };
199    let (hi, lo) = (half(0)?, half(8)?);
200    Ok(Uuid::from_u64_pair(hi, lo))
201}
202
203fn inline_text(data: &[u8], data_offset: usize, value: &DebugValueData) -> Result<String> {
204    let start = usize::try_from(value.data1)
205        .ok()
206        .and_then(|skip| (data_offset + DEBUG_VALUE_DATA_SIZE).checked_add(skip));
207    let len = usize::try_from(value.data2).ok();
208    let bytes = start
209        .zip(len)
210        .and_then(|(start, len)| data.get(start..start.checked_add(len)?))
211        .ok_or_else(|| runtime("string data out of bounds"))?;
212    std::str::from_utf8(bytes)
213        .map(str::to_string)
214        .map_err(|_| runtime("invalid UTF-8 in string"))
215}
216
217fn debug_fraction(value: &DebugValueData) -> Result<Fraction> {
218    guest_fraction(value.data1, value.data2).ok_or_else(|| runtime("non-positive denominator"))
219}
220
221fn debug_index(value: &DebugValueData) -> Result<i64> {
222    let index = debug_fraction(value)?;
223    index
224        .is_integer()
225        .then(|| index.to_integer())
226        .ok_or_else(|| runtime("index with a denominator"))
227}
228
229fn runtime(message: &str) -> DecodeError {
230    DecodeError::Malformed(message.to_string())
231}
232
233#[cfg(test)]
234#[path = "debug_value_tests.rs"]
235mod tests;