Skip to main content

hpr_io/ork/
document.rs

1//! The design document: the XML tree inside a `.ork`, kept whole.
2//!
3//! OpenRocket publishes no schema for `.ork` (there is no XSD), and every version has added tags.
4//! So the document is read into a plain tree of elements and text, with nothing thrown away and
5//! nothing interpreted: later milestones walk it into [`hpr_design`] types, and whatever they do
6//! not understand is still here to be written back out. Reading and writing are exact inverses:
7//! [`Document::to_xml`] followed by [`Document::parse`] returns the same document.
8
9use std::fmt;
10
11use serde::{Deserialize, Serialize};
12
13use super::error::OrkError;
14use super::left_out::NOTHING_DEPENDS;
15use super::warning::{Imported, Warning, WarningKind};
16
17/// The `.ork` schema versions this reader knows, as `1.0` up to and including `1.MAX_KNOWN_MINOR`.
18///
19/// 1.9 is OpenRocket 23.09 and 1.10 is 24.12; 1.11 is documented for 26.xx and adds embedded
20/// `.rse` thrust curves, CSV lookup tables, a gravity model and `preview.png`
21/// (`docs/VALIDATION.md`). A newer file is read anyway, with a warning.
22pub const MAX_KNOWN_MINOR: u32 = 11;
23
24/// How deeply elements may nest before the document is refused.
25///
26/// An ordinary `.ork` design nests 11 deep, and the deepest of the 76 in the reference corpus
27/// (OpenRocket's own parallel-booster example) reaches 17, so 64 leaves room to spare. The limit
28/// is here because both the XML parser underneath and this module's own reader descend the tree:
29/// a file written to nest far enough exhausts the stack, which is a crash where [Loft lesson L56:
30/// malformed input must give an error rather than crash][lessons] asks for an error. On a debug
31/// test build with a 2 MiB stack, `roxmltree` read 120 levels and died on 130, so the depth is
32/// counted before the text is handed to it.
33///
34/// [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
35pub const MAX_DEPTH: usize = 64;
36
37/// A `.ork` schema version, as written in the root element's `version` attribute.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
39pub struct SchemaVersion {
40    /// The major version. Every `.ork` ever written has 1 here.
41    pub major: u32,
42    /// The minor version: 0 to 11 so far.
43    pub minor: u32,
44}
45
46impl SchemaVersion {
47    /// Reads `major.minor`, the only form the attribute takes.
48    pub fn parse(text: &str) -> Result<Self, OrkError> {
49        let version = || OrkError::Version {
50            text: text.to_owned(),
51        };
52        let (major, minor) = text.split_once('.').ok_or_else(version)?;
53        let number = |field: &str| {
54            if field.is_empty() || !field.bytes().all(|byte| byte.is_ascii_digit()) {
55                return Err(version());
56            }
57            field.parse::<u32>().map_err(|_| version())
58        };
59        Ok(Self {
60            major: number(major)?,
61            minor: number(minor)?,
62        })
63    }
64
65    /// Whether this version is one the format documentation describes.
66    pub fn is_known(self) -> bool {
67        self.major == 1 && self.minor <= MAX_KNOWN_MINOR
68    }
69}
70
71impl fmt::Display for SchemaVersion {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        write!(f, "{}.{}", self.major, self.minor)
74    }
75}
76
77/// A design document: its schema version, the program that wrote it, and the whole XML tree.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct Document {
80    /// The root element's `version` attribute.
81    pub version: SchemaVersion,
82    /// The root element's `creator` attribute, for example `OpenRocket 24.12`. Absent in files
83    /// some other program wrote.
84    pub creator: Option<String>,
85    /// The `<openrocket>` element, with every attribute and child it was written with.
86    pub root: Element,
87}
88
89/// An XML element: its name, its attributes in the order they were written, and its children.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
91#[serde(deny_unknown_fields)]
92pub struct Element {
93    /// The element's name, such as `nosecone`.
94    pub name: String,
95    /// The attributes, in document order, as name and value.
96    pub attributes: Vec<(String, String)>,
97    /// The children, in document order.
98    pub children: Vec<Node>,
99}
100
101/// A child of an [`Element`]: another element, or text.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
103#[serde(rename_all = "snake_case", tag = "kind")]
104#[serde(deny_unknown_fields)]
105pub enum Node {
106    /// A child element.
107    Element(Element),
108    /// Text. Character and entity references are already resolved.
109    Text {
110        /// The text as it stands.
111        text: String,
112    },
113}
114
115impl Element {
116    /// The value of the attribute called `name`, if it has one.
117    pub fn attribute(&self, name: &str) -> Option<&str> {
118        super::reads::note_attribute(self, name);
119        self.attributes
120            .iter()
121            .find(|(key, _)| key == name)
122            .map(|(_, value)| value.as_str())
123    }
124
125    /// The child elements called `name`, in document order.
126    pub fn children_named<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a Element> {
127        let name = name.to_owned();
128        self.elements().filter(move |child| child.name == name)
129    }
130
131    /// The first child element called `name`.
132    pub fn child<'a>(&'a self, name: &str) -> Option<&'a Element> {
133        self.elements().find(|child| child.name == name)
134    }
135
136    /// Every child element, in document order.
137    pub fn elements(&self) -> impl Iterator<Item = &Element> {
138        self.children.iter().filter_map(|child| match child {
139            Node::Element(element) => Some(element),
140            Node::Text { .. } => None,
141        })
142    }
143
144    /// The element's text: its text children joined, or the empty string when it has none.
145    ///
146    /// `.ork` values sit in leaf elements (`<length>0.61</length>`), so this is how a value is
147    /// read. It is returned as written; the caller trims and parses it.
148    pub fn text(&self) -> String {
149        let mut text = String::new();
150        for child in &self.children {
151            if let Node::Text { text: part } = child {
152                text.push_str(part);
153            }
154        }
155        text
156    }
157
158    fn has_element_child(&self) -> bool {
159        self.elements().next().is_some()
160    }
161
162    fn has_text_child(&self) -> bool {
163        self.children
164            .iter()
165            .any(|child| matches!(child, Node::Text { .. }))
166    }
167}
168
169impl Document {
170    /// Reads a design document from XML text.
171    ///
172    /// Fails when the text is not well-formed XML, when its root is not `<openrocket>`, or when
173    /// the root carries no readable `version`. Everything else is a warning: a schema version
174    /// newer than [`MAX_KNOWN_MINOR`], a missing `creator`, or a comment (which is dropped).
175    ///
176    /// Blank text between child elements (the indentation OpenRocket writes) is not kept, so
177    /// that writing the document back out is free to lay it out again. Text an element holds
178    /// beside child elements *is* kept: OpenRocket writes a simulation `<warning>` that way.
179    pub fn parse(text: &str) -> Result<Imported<Self>, OrkError> {
180        let deepest = deepest_nesting(text);
181        if deepest > MAX_DEPTH {
182            return Err(OrkError::TooDeep {
183                limit: MAX_DEPTH,
184                depth: deepest,
185            });
186        }
187        let parsed = roxmltree::Document::parse(text).map_err(|error| OrkError::Xml {
188            reason: error.to_string(),
189        })?;
190        let root = parsed.root_element();
191        if root.tag_name().name() != "openrocket" {
192            return Err(OrkError::NotOpenRocket {
193                root: root.tag_name().name().to_owned(),
194            });
195        }
196        let version = SchemaVersion::parse(root.attribute("version").unwrap_or_default())?;
197        let creator = root.attribute("creator").map(str::to_owned);
198
199        let mut warnings = Vec::new();
200        if !version.is_known() {
201            warnings.push(Warning::new(
202                "openrocket",
203                WarningKind::Unusual,
204                if version.major == 1 {
205                    format!(
206                        "schema version {version} is newer than 1.{MAX_KNOWN_MINOR}, the newest \
207                         this reader knows; it was read as far as it is understood"
208                    )
209                } else {
210                    format!(
211                        "schema version {version} is not one this reader knows (1.0 to \
212                         1.{MAX_KNOWN_MINOR}); it was read as far as it is understood"
213                    )
214                },
215            ));
216        }
217        if creator.is_none() {
218            warnings.push(Warning::new(
219                "openrocket",
220                WarningKind::Unusual,
221                "the root element has no `creator` attribute, so the program that wrote this \
222                 design is unknown",
223            ));
224        }
225        if root.tag_name().namespace().is_some()
226            || parsed
227                .descendants()
228                .any(|node| node.namespaces().next().is_some())
229        {
230            warnings.push(Warning::new(
231                "openrocket",
232                WarningKind::Dropped,
233                "this document declares XML namespaces; their prefixes and declarations were left \
234                 out, and two attributes that differ only by prefix become one. No `.ork` \
235                 OpenRocket writes uses them",
236            ));
237        }
238        let root = read_element(root, "", &mut warnings);
239        Ok(Imported {
240            value: Self {
241                version,
242                creator,
243                root,
244            },
245            warnings,
246        })
247    }
248
249    /// Writes the document back out as XML.
250    ///
251    /// The result is written in one fixed style rather than byte-identical to the file it was
252    /// read from: two-space indentation, attributes in the order they were read, and `<tag/>` for
253    /// an empty element. Reading it again gives an equal [`Document`], which is what makes the
254    /// tree lossless.
255    ///
256    /// [`version`](Self::version) and [`creator`](Self::creator) are written onto the root, so
257    /// changing either changes the file. Everything else comes from [`root`](Self::root).
258    ///
259    /// This is defined for a document that came from [`parse`](Self::parse). `Element`'s fields
260    /// are public, and a tree built by hand can hold a name that is not an XML name, or nest
261    /// deeper than [`MAX_DEPTH`]. Writing either gives XML that will not read back.
262    pub fn to_xml(&self) -> String {
263        let mut root = self.root.clone();
264        set_attribute(&mut root, "version", Some(self.version.to_string()));
265        set_attribute(&mut root, "creator", self.creator.clone());
266        let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
267        write_element(&root, 0, &mut out);
268        out.push('\n');
269        out
270    }
271}
272
273/// Reads one element and its children, recording `at` as the path for any warning.
274fn read_element(
275    node: roxmltree::Node<'_, '_>,
276    parent: &str,
277    warnings: &mut Vec<Warning>,
278) -> Element {
279    let name = node.tag_name().name().to_owned();
280    let at = if parent.is_empty() {
281        name.clone()
282    } else {
283        format!("{parent}/{name}")
284    };
285    let attributes = node
286        .attributes()
287        .map(|attribute| (attribute.name().to_owned(), attribute.value().to_owned()))
288        .collect();
289
290    let keeps_blank_text = !node.children().any(|child| child.is_element());
291    let mut children = Vec::new();
292    for child in node.children() {
293        if child.is_element() {
294            children.push(Node::Element(read_element(child, &at, warnings)));
295        } else if child.is_text() {
296            let text = child.text().unwrap_or_default();
297            // A comment, a processing instruction or a CDATA section splits a run of text in two.
298            // Joining them here is what keeps writing and reading again exact: the writer has
299            // nowhere to put the split, since it drops the comment that made it.
300            if let Some(Node::Text { text: last }) = children.last_mut()
301                && (keeps_blank_text || !text.trim().is_empty())
302            {
303                last.push_str(text);
304                continue;
305            }
306            if keeps_blank_text {
307                children.push(Node::Text {
308                    text: text.to_owned(),
309                });
310            } else if !text.trim().is_empty() {
311                // An element with both child elements and text of its own. OpenRocket writes one:
312                // a simulation's `<warning>` prints its own message after its fields. Both are
313                // kept, and the blank text that only lays the file out is not.
314                children.push(Node::Text {
315                    text: text.to_owned(),
316                });
317            }
318        } else if child.is_comment() {
319            warnings.push(Warning::new(
320                at.clone(),
321                WarningKind::Dropped,
322                format!("an XML comment was left out, and {NOTHING_DEPENDS}"),
323            ));
324        } else if child.is_pi() {
325            warnings.push(Warning::new(
326                at.clone(),
327                WarningKind::Dropped,
328                format!("an XML processing instruction was left out, and {NOTHING_DEPENDS}"),
329            ));
330        }
331    }
332    Element {
333        name,
334        attributes,
335        children,
336    }
337}
338
339/// Counts how deeply elements nest in `text`, without building a tree.
340///
341/// This is a scan, not a parser: it walks the text, skips comments, CDATA sections and processing
342/// instructions, tracks quotes so that a `>` inside an attribute value does not end a tag, and
343/// counts start tags against end tags. It can only ever return more nesting than a parser will
344/// find (XML forbids a raw `<` inside an attribute value, so every element start it sees is one),
345/// which is what makes it safe to use as a guard.
346pub(crate) fn deepest_nesting(text: &str) -> usize {
347    let bytes = text.as_bytes();
348    let mut index = 0;
349    let mut depth = 0usize;
350    let mut deepest = 0usize;
351    while index < bytes.len() {
352        if bytes[index] != b'<' {
353            index += 1;
354            continue;
355        }
356        let rest = &bytes[index..];
357        if let Some(skip) = skipped(rest, b"<!--", b"-->")
358            .or_else(|| skipped(rest, b"<![CDATA[", b"]]>"))
359            .or_else(|| skipped(rest, b"<?", b"?>"))
360        {
361            index += skip;
362            continue;
363        }
364        let closing = rest.starts_with(b"</");
365        // `<!DOCTYPE …>` and the like: not an element, so it changes no depth.
366        let declaration = rest.starts_with(b"<!");
367
368        let mut cursor = index + 1;
369        let mut quote: Option<u8> = None;
370        let mut last = 0u8;
371        while cursor < bytes.len() {
372            let byte = bytes[cursor];
373            match quote {
374                Some(open) if byte == open => quote = None,
375                Some(_) => {}
376                None if byte == b'"' || byte == b'\'' => quote = Some(byte),
377                None if byte == b'>' => break,
378                None => {}
379            }
380            if !byte.is_ascii_whitespace() {
381                last = byte;
382            }
383            cursor += 1;
384        }
385        if !declaration {
386            if closing {
387                depth = depth.saturating_sub(1);
388            } else {
389                depth += 1;
390                deepest = deepest.max(depth);
391                if last == b'/' {
392                    depth -= 1;
393                }
394            }
395        }
396        index = cursor + 1;
397    }
398    deepest
399}
400
401/// When `rest` starts with `opening`, the length up to and including the next `closing`, or to the
402/// end of the text when there is none.
403fn skipped(rest: &[u8], opening: &[u8], closing: &[u8]) -> Option<usize> {
404    if !rest.starts_with(opening) {
405        return None;
406    }
407    let from = opening.len();
408    let found = rest[from..]
409        .windows(closing.len())
410        .position(|window| window == closing)
411        .map(|at| from + at + closing.len());
412    Some(found.unwrap_or(rest.len()))
413}
414
415/// Sets, replaces or removes one attribute of an element, keeping the order of the rest.
416fn set_attribute(element: &mut Element, name: &str, value: Option<String>) {
417    let at = element.attributes.iter().position(|(key, _)| key == name);
418    match (at, value) {
419        (Some(at), Some(value)) => element.attributes[at].1 = value,
420        (Some(at), None) => {
421            element.attributes.remove(at);
422        }
423        (None, Some(value)) => element.attributes.push((name.to_owned(), value)),
424        (None, None) => {}
425    }
426}
427
428/// Writes an element, indented by `depth`, laying out child elements one per line.
429fn write_element(element: &Element, depth: usize, out: &mut String) {
430    let mixed = element.has_element_child() && element.has_text_child();
431    if mixed {
432        // Adding whitespace around text would change the text when the document is read again,
433        // so an element that mixes the two is written with no layout at all.
434        write_compact(element, out);
435        return;
436    }
437    for _ in 0..depth {
438        out.push_str("  ");
439    }
440    write_open_tag(element, out);
441    if element.children.is_empty() {
442        out.truncate(out.len() - 1);
443        out.push_str("/>");
444        return;
445    }
446    if element.has_element_child() {
447        for child in &element.children {
448            if let Node::Element(child) = child {
449                out.push('\n');
450                write_element(child, depth + 1, out);
451            }
452        }
453        out.push('\n');
454        for _ in 0..depth {
455            out.push_str("  ");
456        }
457    } else {
458        out.push_str(&escape_text(&element.text()));
459    }
460    out.push_str("</");
461    out.push_str(&element.name);
462    out.push('>');
463}
464
465/// Writes an element with no added whitespace, used for mixed content.
466fn write_compact(element: &Element, out: &mut String) {
467    write_open_tag(element, out);
468    if element.children.is_empty() {
469        out.truncate(out.len() - 1);
470        out.push_str("/>");
471        return;
472    }
473    for child in &element.children {
474        match child {
475            Node::Element(child) => write_compact(child, out),
476            Node::Text { text } => out.push_str(&escape_text(text)),
477        }
478    }
479    out.push_str("</");
480    out.push_str(&element.name);
481    out.push('>');
482}
483
484fn write_open_tag(element: &Element, out: &mut String) {
485    out.push('<');
486    out.push_str(&element.name);
487    for (name, value) in &element.attributes {
488        out.push(' ');
489        out.push_str(name);
490        out.push_str("=\"");
491        out.push_str(&escape_attribute(value));
492        out.push('"');
493    }
494    out.push('>');
495}
496
497/// Escapes text. A carriage return becomes a character reference: XML parsers turn a literal one
498/// into a line feed, which would change the text when the document is read again.
499fn escape_text(text: &str) -> String {
500    let mut out = String::with_capacity(text.len());
501    for character in text.chars() {
502        match character {
503            '&' => out.push_str("&amp;"),
504            '<' => out.push_str("&lt;"),
505            '>' => out.push_str("&gt;"),
506            '\r' => out.push_str("&#13;"),
507            other => out.push(other),
508        }
509    }
510    out
511}
512
513/// Escapes an attribute value. Every whitespace character but the space becomes a character
514/// reference, because a parser turns literal ones into spaces.
515fn escape_attribute(value: &str) -> String {
516    let mut out = String::with_capacity(value.len());
517    for character in value.chars() {
518        match character {
519            '&' => out.push_str("&amp;"),
520            '<' => out.push_str("&lt;"),
521            '>' => out.push_str("&gt;"),
522            '"' => out.push_str("&quot;"),
523            '\t' => out.push_str("&#9;"),
524            '\n' => out.push_str("&#10;"),
525            '\r' => out.push_str("&#13;"),
526            other => out.push(other),
527        }
528    }
529    out
530}