Skip to main content

labstream_net/
desc.rs

1//! The description tree, and the whole document that carries it.
2//!
3//! A discovery answer holds a short description with an empty `<desc />`
4//! (`src/stream_info_impl.cpp:160`). The whole document travels on the data
5//! port, in answer to `LSL:fullinfo` (`src/tcp_server.cpp:508`). That document
6//! carries the tree that an application builds, which is where channel labels,
7//! units, and device names live.
8//!
9//! # Why the model keeps text as a node
10//!
11//! liblsl holds the tree in pugixml, where the text of an element is a child
12//! node. The C ABI shows that model directly: `lsl_is_text` returns
13//! `type() != node_element`, and `lsl_value` returns the value of the node
14//! itself, which is empty for an element (`src/lsl_xml_element_c.cpp:36-38`).
15//! A model that stores text in a field of the element cannot answer those two
16//! calls correctly.
17//!
18//! # Where the layout rules come from
19//!
20//! Every rule below is measured. `oracle/descxml.cpp` builds trees through
21//! real liblsl and writes the document. `oracle/descread.cpp` feeds documents
22//! back in and writes what comes out. The results are in `captures/desc/`.
23//!
24//! | Case | What the oracle writes |
25//! |---|---|
26//! | An element with no children | `<x />` |
27//! | An element with one empty text child | `<x></x>` |
28//! | Text beside an element | `<v>a<b />c</v>`, all on one line |
29//! | Text that holds only spaces | dropped, and the element becomes `<x />` |
30//! | A comment | dropped |
31//! | An attribute | kept, always in double quotes |
32//! | A section of character data | kept as a section of character data |
33
34/// What a node holds.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Kind {
37    /// A tag with a name.
38    #[default]
39    Element,
40    /// A run of text.
41    Text,
42    /// A section of character data, which needs no escape.
43    Cdata,
44}
45
46/// One node of a description tree.
47#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub struct Node {
49    /// What this node holds.
50    pub kind: Kind,
51    /// The tag name. A text node has no name.
52    pub name: String,
53    /// The text. An element has no text of its own.
54    pub value: String,
55    /// The attributes of an element, in the order they were written.
56    ///
57    /// No call of the C ABI creates one (`include/lsl/xml.h`). An attribute
58    /// reaches the tree only through a document that an inlet reads, and the
59    /// oracle keeps it, so this keeps it too.
60    pub attrs: Vec<(String, String)>,
61    /// The nodes below this one.
62    pub children: Vec<Node>,
63}
64
65/// Write a newline before the node.
66const NEWLINE: u8 = 1;
67/// Write the indent before the node.
68const INDENT: u8 = 2;
69
70impl Node {
71    /// A tag with no content.
72    pub fn element(name: &str) -> Node {
73        Node {
74            kind: Kind::Element,
75            name: name.to_string(),
76            ..Default::default()
77        }
78    }
79
80    /// A run of text.
81    pub fn text(value: &str) -> Node {
82        Node {
83            kind: Kind::Text,
84            value: value.to_string(),
85            ..Default::default()
86        }
87    }
88
89    /// A section of character data.
90    pub fn cdata(value: &str) -> Node {
91        Node {
92            kind: Kind::Cdata,
93            value: value.to_string(),
94            ..Default::default()
95        }
96    }
97
98    /// Add a tag below this node and return it.
99    pub fn append_child(&mut self, name: &str) -> &mut Node {
100        self.children.push(Node::element(name));
101        self.children.last_mut().unwrap()
102    }
103
104    /// Add a tag that holds text.
105    ///
106    /// This matches `lsl_append_child_value`, which appends the tag and then
107    /// appends one text node below it (`src/lsl_xml_element_c.cpp:74`).
108    pub fn append_child_value(&mut self, name: &str, value: &str) -> &mut Node {
109        let mut e = Node::element(name);
110        e.children.push(Node::text(value));
111        self.children.push(e);
112        self.children.last_mut().unwrap()
113    }
114
115    /// The first child with this name.
116    pub fn child(&self, name: &str) -> Option<&Node> {
117        self.children.iter().find(|c| c.name == name)
118    }
119
120    /// The first child with this name, for a change.
121    pub fn child_mut(&mut self, name: &str) -> Option<&mut Node> {
122        self.children.iter_mut().find(|c| c.name == name)
123    }
124
125    /// The text of the first child that holds text.
126    pub fn child_value(&self) -> &str {
127        for c in &self.children {
128            if c.kind != Kind::Element {
129                return &c.value;
130            }
131        }
132        ""
133    }
134
135    /// The text of the first child with this name.
136    pub fn child_value_of(&self, name: &str) -> &str {
137        match self.child(name) {
138            Some(c) => c.child_value(),
139            None => "",
140        }
141    }
142
143    /// True when this node holds nothing at all.
144    pub fn is_empty(&self) -> bool {
145        self.name.is_empty()
146            && self.value.is_empty()
147            && self.children.is_empty()
148            && self.attrs.is_empty()
149    }
150
151    /// Write this node and everything below it, and end with a newline.
152    ///
153    /// `depth` counts the tabs before the opening tag.
154    pub fn write(&self, out: &mut String, depth: usize) {
155        self.emit(out, depth, INDENT);
156        out.push('\n');
157    }
158
159    /// Write one node and return the flags for the node that follows.
160    ///
161    /// pugixml carries two flags while it walks the tree. Text clears both, so
162    /// everything after text on the same level stays on the same line, up to
163    /// and including the closing tag. That rule produces `<v>a<b />c</v>` and
164    /// `<blank></blank>`, both of which the oracle writes.
165    fn emit(&self, out: &mut String, depth: usize, flags: u8) -> u8 {
166        if self.kind == Kind::Text {
167            escape_text_into(&self.value, out);
168            return 0;
169        }
170        if self.kind == Kind::Cdata {
171            out.push_str("<![CDATA[");
172            out.push_str(&self.value);
173            out.push_str("]]>");
174            return 0;
175        }
176        if flags & NEWLINE != 0 {
177            out.push('\n');
178        }
179        if flags & INDENT != 0 {
180            for _ in 0..depth {
181                out.push('\t');
182            }
183        }
184        out.push('<');
185        out.push_str(&self.name);
186        for (k, v) in &self.attrs {
187            out.push(' ');
188            out.push_str(k);
189            out.push_str("=\"");
190            escape_attr_into(v, out);
191            out.push('"');
192        }
193        if self.children.is_empty() {
194            out.push_str(" />");
195            return NEWLINE | INDENT;
196        }
197        out.push('>');
198        let mut f = NEWLINE | INDENT;
199        for c in &self.children {
200            f = c.emit(out, depth + 1, f);
201        }
202        if f & NEWLINE != 0 {
203            out.push('\n');
204        }
205        if f & INDENT != 0 {
206            for _ in 0..depth {
207                out.push('\t');
208            }
209        }
210        out.push_str("</");
211        out.push_str(&self.name);
212        out.push('>');
213        NEWLINE | INDENT
214    }
215}
216
217/// Escape the three characters that the oracle escapes in text.
218///
219/// `captures/desc/desc_escapes.xml` holds the measurement. A double quote, a
220/// single quote, a tab, a line feed, and a carriage return all pass through
221/// unchanged. Only `&`, `<`, and `>` change.
222fn escape_text_into(s: &str, out: &mut String) {
223    for c in s.chars() {
224        match c {
225            '&' => out.push_str("&amp;"),
226            '<' => out.push_str("&lt;"),
227            '>' => out.push_str("&gt;"),
228            other => out.push(other),
229        }
230    }
231}
232
233/// Escape an attribute value.
234///
235/// `captures/desc/desc_reader.txt`, case `attribute_escapes`, holds the
236/// measurement for `&`, `"`, `<`, `>`, a line feed, and a tab. A greater-than
237/// sign and a single quote stay as they are, and a tab writes as `&#09;` with
238/// two digits. A carriage return is not measured. It is escaped here for the
239/// same reason a line feed is. An XML reader turns an unescaped one into a
240/// space.
241fn escape_attr_into(s: &str, out: &mut String) {
242    for c in s.chars() {
243        match c {
244            '&' => out.push_str("&amp;"),
245            '<' => out.push_str("&lt;"),
246            '"' => out.push_str("&quot;"),
247            '\n' => out.push_str("&#10;"),
248            '\r' => out.push_str("&#13;"),
249            '\t' => out.push_str("&#09;"),
250            other => out.push(other),
251        }
252    }
253}
254
255// ===========================================================================
256// the reader
257// ===========================================================================
258
259/// Read a document and return its root element.
260///
261/// This follows the oracle, which loads the document with the default parse
262/// flags and never changes them (`src/stream_info_impl.cpp:183`):
263///
264/// * Text that holds only whitespace is dropped.
265///   `captures/desc/desc_reader.txt`, case `whitespace_only_text`.
266/// * A comment is dropped. Same file, case `comment`.
267/// * A line end is normalized. `\r\n` and a lone `\r` both become `\n`.
268///   `captures/desc/desc_reparse.hex` shows a carriage return that does not
269///   survive the round trip.
270/// * An entity reference is decoded, and a reference with no semicolon stays
271///   as it is. Same file, case `unterminated_reference`.
272pub fn parse(xml: &str) -> Option<Node> {
273    let b = xml.as_bytes();
274    let mut i = 0usize;
275    let mut stack: Vec<Node> = Vec::new();
276    let mut root: Option<Node> = None;
277
278    while i < b.len() {
279        if b[i] != b'<' {
280            let start = i;
281            while i < b.len() && b[i] != b'<' {
282                i += 1;
283            }
284            let raw = &xml[start..i];
285            if !raw.trim().is_empty() {
286                if let Some(top) = stack.last_mut() {
287                    top.children.push(Node::text(&decode(raw)));
288                }
289            }
290            continue;
291        }
292        if xml[i..].starts_with("<?") {
293            i = find(b, i, b"?>")? + 2;
294            continue;
295        }
296        if xml[i..].starts_with("<!--") {
297            i = find(b, i, b"-->")? + 3;
298            continue;
299        }
300        if xml[i..].starts_with("<![CDATA[") {
301            let end = find(b, i, b"]]>")?;
302            // A section of character data holds no entity reference. The line
303            // ends still change.
304            let raw = normalize_eol(&xml[i + 9..end]);
305            if let Some(top) = stack.last_mut() {
306                top.children.push(Node::cdata(&raw));
307            }
308            i = end + 3;
309            continue;
310        }
311        if xml[i..].starts_with("<!") {
312            i = find(b, i, b">")? + 1;
313            continue;
314        }
315        if xml[i..].starts_with("</") {
316            let end = find(b, i, b">")?;
317            let done = stack.pop()?;
318            if stack.is_empty() {
319                root = Some(done);
320            } else {
321                stack.last_mut()?.children.push(done);
322            }
323            i = end + 1;
324            continue;
325        }
326
327        // an opening tag
328        let end = tag_end(b, i)?;
329        let inner = &xml[i + 1..end];
330        let selfclose = inner.trim_end().ends_with('/');
331        let inner = match inner.trim_end().strip_suffix('/') {
332            Some(x) => x,
333            None => inner,
334        };
335        let (name, rest) = split_name(inner);
336        if name.is_empty() {
337            return None;
338        }
339        let mut node = Node::element(name);
340        node.attrs = read_attrs(rest);
341        if selfclose {
342            if let Some(top) = stack.last_mut() {
343                top.children.push(node);
344            } else {
345                root = Some(node);
346            }
347        } else {
348            stack.push(node);
349        }
350        i = end + 1;
351    }
352
353    if !stack.is_empty() {
354        return None;
355    }
356    root
357}
358
359/// Find the `>` that closes a tag, skipping one inside a quoted value.
360fn tag_end(b: &[u8], from: usize) -> Option<usize> {
361    let mut quote = 0u8;
362    for (k, &c) in b.iter().enumerate().skip(from) {
363        if quote != 0 {
364            if c == quote {
365                quote = 0;
366            }
367        } else if c == b'"' || c == b'\'' {
368            quote = c;
369        } else if c == b'>' {
370            return Some(k);
371        }
372    }
373    None
374}
375
376fn split_name(inner: &str) -> (&str, &str) {
377    match inner.find(|c: char| c.is_ascii_whitespace()) {
378        Some(k) => (&inner[..k], &inner[k..]),
379        None => (inner, ""),
380    }
381}
382
383/// Read `name="value"` pairs. A name with no value is dropped.
384fn read_attrs(rest: &str) -> Vec<(String, String)> {
385    let mut out = Vec::new();
386    let chars: Vec<char> = rest.chars().collect();
387    let mut i = 0;
388    while i < chars.len() {
389        if chars[i].is_ascii_whitespace() {
390            i += 1;
391            continue;
392        }
393        let start = i;
394        while i < chars.len() && chars[i] != '=' && !chars[i].is_ascii_whitespace() {
395            i += 1;
396        }
397        let name: String = chars[start..i].iter().collect();
398        while i < chars.len() && chars[i].is_ascii_whitespace() {
399            i += 1;
400        }
401        if i >= chars.len() || chars[i] != '=' {
402            continue;
403        }
404        i += 1;
405        while i < chars.len() && chars[i].is_ascii_whitespace() {
406            i += 1;
407        }
408        if i >= chars.len() {
409            break;
410        }
411        let quote = chars[i];
412        if quote != '"' && quote != '\'' {
413            break;
414        }
415        i += 1;
416        let vstart = i;
417        while i < chars.len() && chars[i] != quote {
418            i += 1;
419        }
420        let value: String = chars[vstart..i].iter().collect();
421        i += 1;
422        if !name.is_empty() {
423            out.push((name, decode(&value)));
424        }
425    }
426    out
427}
428
429fn find(b: &[u8], from: usize, pat: &[u8]) -> Option<usize> {
430    (from..=b.len().checked_sub(pat.len())?).find(|&k| &b[k..k + pat.len()] == pat)
431}
432
433/// Turn `\r\n` and a lone `\r` into `\n`.
434fn normalize_eol(s: &str) -> String {
435    let mut out = String::with_capacity(s.len());
436    let mut it = s.chars().peekable();
437    while let Some(c) = it.next() {
438        if c == '\r' {
439            if it.peek() == Some(&'\n') {
440                it.next();
441            }
442            out.push('\n');
443        } else {
444            out.push(c);
445        }
446    }
447    out
448}
449
450/// Decode entity references, then normalize the line ends.
451fn decode(s: &str) -> String {
452    let mut out = String::with_capacity(s.len());
453    let b = s.as_bytes();
454    let mut i = 0;
455    while i < b.len() {
456        if b[i] != b'&' {
457            let start = i;
458            while i < b.len() && b[i] != b'&' {
459                i += 1;
460            }
461            out.push_str(&s[start..i]);
462            continue;
463        }
464        let end = match find(b, i, b";") {
465            Some(e) if e - i <= 10 => e,
466            // An ampersand with no terminator stays as it is.
467            _ => {
468                out.push('&');
469                i += 1;
470                continue;
471            }
472        };
473        let name = &s[i + 1..end];
474        let decoded = match name {
475            "amp" => Some('&'),
476            "lt" => Some('<'),
477            "gt" => Some('>'),
478            "quot" => Some('"'),
479            "apos" => Some('\''),
480            _ => numeric_entity(name),
481        };
482        match decoded {
483            Some(c) => {
484                out.push(c);
485                i = end + 1;
486            }
487            None => {
488                out.push('&');
489                i += 1;
490            }
491        }
492    }
493    normalize_eol(&out)
494}
495
496fn numeric_entity(name: &str) -> Option<char> {
497    let digits = name.strip_prefix('#')?;
498    let code = match digits
499        .strip_prefix('x')
500        .or_else(|| digits.strip_prefix('X'))
501    {
502        Some(hex) => u32::from_str_radix(hex, 16).ok()?,
503        None => digits.parse::<u32>().ok()?,
504    };
505    char::from_u32(code)
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    fn render(n: &Node) -> String {
513        let mut s = String::new();
514        n.write(&mut s, 0);
515        s
516    }
517
518    /// Read a document, write it back, and return the `<desc>` part.
519    ///
520    /// This is the shape that `captures/desc/desc_reader.txt` records.
521    fn round(desc: &str) -> String {
522        let n = parse(desc).expect("a tree");
523        let mut s = String::new();
524        n.emit(&mut s, 1, INDENT);
525        s
526    }
527
528    #[test]
529    fn an_element_with_no_children_prints_as_an_empty_tag() {
530        assert_eq!(render(&Node::element("desc")), "<desc />\n");
531    }
532
533    #[test]
534    fn an_empty_text_child_prints_as_a_pair_of_tags() {
535        // `captures/desc/desc_blank.xml` shows `<blank></blank>` beside
536        // `<hollow />`. The two states have to stay apart.
537        let mut d = Node::element("desc");
538        d.append_child_value("blank", "");
539        d.append_child("hollow");
540        assert_eq!(
541            render(&d),
542            "<desc>\n\t<blank></blank>\n\t<hollow />\n</desc>\n"
543        );
544    }
545
546    #[test]
547    fn text_beside_an_element_keeps_the_whole_element_on_one_line() {
548        // `captures/desc/desc_reader.txt`, case `mixed_content`.
549        assert_eq!(
550            round("<desc><v>a<b />c</v></desc>"),
551            "\t<desc>\n\t\t<v>a<b />c</v>\n\t</desc>"
552        );
553    }
554
555    #[test]
556    fn only_three_characters_are_escaped_in_text() {
557        let mut d = Node::element("d");
558        d.append_child_value("v", "a & b <x> \" ' \t");
559        assert_eq!(
560            render(&d),
561            "<d>\n\t<v>a &amp; b &lt;x&gt; \" ' \t</v>\n</d>\n"
562        );
563    }
564
565    #[test]
566    fn an_attribute_survives_a_round_trip() {
567        // `captures/desc/desc_reader.txt`, case `attribute`. A single quote in
568        // the source becomes a double quote in the output.
569        assert_eq!(
570            round("<desc><v id=\"1\" unit='mV'>x</v></desc>"),
571            "\t<desc>\n\t\t<v id=\"1\" unit=\"mV\">x</v>\n\t</desc>"
572        );
573    }
574
575    #[test]
576    fn an_attribute_escapes_the_characters_that_the_oracle_escapes() {
577        // `captures/desc/desc_reader.txt`, case `attribute_escapes`.
578        assert_eq!(
579            round("<desc><v a=\"x&amp;y&quot;z&#10;w&#9;t&lt;u&gt;\" b='s&apos;q'>1</v></desc>"),
580            "\t<desc>\n\t\t<v a=\"x&amp;y&quot;z&#10;w&#09;t&lt;u>\" b=\"s'q\">1</v>\n\t</desc>"
581        );
582    }
583
584    #[test]
585    fn a_section_of_character_data_stays_one() {
586        // `captures/desc/desc_reader.txt`, cases `cdata` and `cdata_and_text`.
587        assert_eq!(
588            round("<desc><v><![CDATA[a & <b>]]></v></desc>"),
589            "\t<desc>\n\t\t<v><![CDATA[a & <b>]]></v>\n\t</desc>"
590        );
591        assert_eq!(
592            round("<desc><v>a<![CDATA[<b>]]>c</v></desc>"),
593            "\t<desc>\n\t\t<v>a<![CDATA[<b>]]>c</v>\n\t</desc>"
594        );
595    }
596
597    #[test]
598    fn a_comment_is_dropped() {
599        // `captures/desc/desc_reader.txt`, case `comment`.
600        assert_eq!(
601            round("<desc><!-- gone --><v>x</v></desc>"),
602            "\t<desc>\n\t\t<v>x</v>\n\t</desc>"
603        );
604    }
605
606    #[test]
607    fn text_that_holds_only_spaces_is_dropped() {
608        // `captures/desc/desc_reader.txt`, case `whitespace_only_text`.
609        assert_eq!(
610            round("<desc><v>   </v></desc>"),
611            "\t<desc>\n\t\t<v />\n\t</desc>"
612        );
613    }
614
615    #[test]
616    fn a_reference_with_no_semicolon_stays_as_it_is() {
617        // `captures/desc/desc_reader.txt`, case `unterminated_reference`. The
618        // value keeps the ampersand, so writing it out escapes that ampersand.
619        let n = parse("<desc><v>100% &amp fine</v></desc>").expect("a tree");
620        assert_eq!(n.child_value_of("v"), "100% &amp fine");
621        assert_eq!(
622            round("<desc><v>100% &amp fine</v></desc>"),
623            "\t<desc>\n\t\t<v>100% &amp;amp fine</v>\n\t</desc>"
624        );
625    }
626
627    #[test]
628    fn a_numeric_reference_is_decoded() {
629        // `captures/desc/desc_reader.txt`, case `numeric_reference`.
630        let n = parse("<desc><v>&#65;&#x42;&#10;</v></desc>").expect("a tree");
631        assert_eq!(n.child_value_of("v"), "AB\n");
632    }
633
634    #[test]
635    fn a_carriage_return_does_not_survive_the_reader() {
636        // Measured. `captures/desc/desc_reparse.hex` holds
637        // `lines 6f6e650a74776f0a746872656509666f7572`.
638        let n = parse("<a><lines>one\ntwo\rthree\tfour</lines></a>").expect("a tree");
639        assert_eq!(n.child_value_of("lines"), "one\ntwo\nthree\tfour");
640    }
641
642    #[test]
643    fn a_tag_that_never_closes_is_rejected() {
644        assert!(parse("<a><b></a>").is_none());
645        assert!(parse("<a>").is_none());
646    }
647
648    #[test]
649    fn text_reads_back_as_a_child_node() {
650        // The C ABI needs this. `lsl_is_text` asks the node itself.
651        let n = parse("<a><b>v</b></a>").expect("a tree");
652        let b = n.child("b").expect("b");
653        assert_eq!(b.kind, Kind::Element);
654        assert_eq!(b.value, "");
655        assert_eq!(b.children.len(), 1);
656        assert_eq!(b.children[0].kind, Kind::Text);
657        assert_eq!(b.children[0].value, "v");
658    }
659
660    #[test]
661    fn a_greater_than_sign_inside_an_attribute_does_not_end_the_tag() {
662        let n = parse("<a><b x=\"1>2\">v</b></a>").expect("a tree");
663        assert_eq!(
664            n.child("b").expect("b").attrs,
665            vec![("x".into(), "1>2".into())]
666        );
667    }
668}