1use quick_xml::Reader;
31use quick_xml::events::Event;
32
33use crate::error::{ParseError, ParseErrorKind};
34use crate::ids::Span;
35
36const NONE: u32 = u32::MAX;
38
39macro_rules! symbols {
40 ($(#[$meta:meta])* $vis:vis enum $name:ident { $($variant:ident => $text:literal),* $(,)? }) => {
41 $(#[$meta])*
42 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
43 $vis enum $name {
44 $(
45 #[doc = concat!("The XML symbol `", $text, "`.")]
46 $variant,
47 )*
48 Other,
50 }
51
52 impl $name {
53 $vis const ALL: &'static [$name] = &[$($name::$variant,)*];
55
56 #[must_use]
58 $vis const fn text(self) -> &'static str {
59 match self {
60 $($name::$variant => $text,)*
61 $name::Other => "",
62 }
63 }
64
65 #[must_use]
68 $vis fn from_text(text: &str) -> Self {
69 match text {
70 $($text => $name::$variant,)*
71 _ => $name::Other,
72 }
73 }
74 }
75 };
76}
77
78symbols! {
79 pub enum Tag {
86 SpaceSystem => "SpaceSystem",
87 TelemetryMetaData => "TelemetryMetaData",
88 CommandMetaData => "CommandMetaData",
89 ArgumentTypeSet => "ArgumentTypeSet",
90 MetaCommandSet => "MetaCommandSet",
91 MetaCommand => "MetaCommand",
92 BaseMetaCommand => "BaseMetaCommand",
93 ArgumentAssignmentList => "ArgumentAssignmentList",
94 ArgumentAssignment => "ArgumentAssignment",
95 ArgumentList => "ArgumentList",
96 Argument => "Argument",
97 CommandContainer => "CommandContainer",
98 CommandContainerSet => "CommandContainerSet",
99 ArgumentRefEntry => "ArgumentRefEntry",
100 ArrayArgumentRefEntry => "ArrayArgumentRefEntry",
101 FixedValueEntry => "FixedValueEntry",
102 IntegerArgumentType => "IntegerArgumentType",
103 FloatArgumentType => "FloatArgumentType",
104 StringArgumentType => "StringArgumentType",
105 BinaryArgumentType => "BinaryArgumentType",
106 BooleanArgumentType => "BooleanArgumentType",
107 EnumeratedArgumentType => "EnumeratedArgumentType",
108 AbsoluteTimeArgumentType => "AbsoluteTimeArgumentType",
109 RelativeTimeArgumentType => "RelativeTimeArgumentType",
110 ArrayArgumentType => "ArrayArgumentType",
111 AggregateArgumentType => "AggregateArgumentType",
112 ParameterTypeSet => "ParameterTypeSet",
113 ParameterSet => "ParameterSet",
114 ContainerSet => "ContainerSet",
115 Parameter => "Parameter",
116 SequenceContainer => "SequenceContainer",
117 BaseContainer => "BaseContainer",
118 RestrictionCriteria => "RestrictionCriteria",
119 EntryList => "EntryList",
120 ParameterRefEntry => "ParameterRefEntry",
121 ContainerRefEntry => "ContainerRefEntry",
122 IndirectParameterRefEntry => "IndirectParameterRefEntry",
123 ArrayParameterRefEntry => "ArrayParameterRefEntry",
124 LocationInContainerInBits => "LocationInContainerInBits",
125 IntegerParameterType => "IntegerParameterType",
126 FloatParameterType => "FloatParameterType",
127 StringParameterType => "StringParameterType",
128 BinaryParameterType => "BinaryParameterType",
129 BooleanParameterType => "BooleanParameterType",
130 EnumeratedParameterType => "EnumeratedParameterType",
131 AbsoluteTimeParameterType => "AbsoluteTimeParameterType",
132 RelativeTimeParameterType => "RelativeTimeParameterType",
133 ArrayParameterType => "ArrayParameterType",
134 DimensionList => "DimensionList",
135 Dimension => "Dimension",
136 StartingIndex => "StartingIndex",
137 EndingIndex => "EndingIndex",
138 AggregateParameterType => "AggregateParameterType",
139 MemberList => "MemberList",
140 Member => "Member",
141 IntegerDataEncoding => "IntegerDataEncoding",
142 FloatDataEncoding => "FloatDataEncoding",
143 StringDataEncoding => "StringDataEncoding",
144 BinaryDataEncoding => "BinaryDataEncoding",
145 Encoding => "Encoding",
146 SizeInBits => "SizeInBits",
147 Fixed => "Fixed",
148 FixedValue => "FixedValue",
149 Variable => "Variable",
150 DynamicValue => "DynamicValue",
151 DiscreteLookupList => "DiscreteLookupList",
152 DiscreteLookup => "DiscreteLookup",
153 LeadingSize => "LeadingSize",
154 TerminationChar => "TerminationChar",
155 ParameterInstanceRef => "ParameterInstanceRef",
156 LinearAdjustment => "LinearAdjustment",
157 EnumerationList => "EnumerationList",
158 Enumeration => "Enumeration",
159 Comparison => "Comparison",
160 ComparisonList => "ComparisonList",
161 BooleanExpression => "BooleanExpression",
162 Condition => "Condition",
163 ANDedConditions => "ANDedConditions",
164 ORedConditions => "ORedConditions",
165 ComparisonOperator => "ComparisonOperator",
166 Value => "Value",
167 DefaultCalibrator => "DefaultCalibrator",
168 ContextCalibratorList => "ContextCalibratorList",
169 ContextCalibrator => "ContextCalibrator",
170 ContextMatch => "ContextMatch",
171 Calibrator => "Calibrator",
172 PolynomialCalibrator => "PolynomialCalibrator",
173 SplineCalibrator => "SplineCalibrator",
174 MathOperationCalibrator => "MathOperationCalibrator",
175 Term => "Term",
176 SplinePoint => "SplinePoint",
177 CustomAlgorithm => "CustomAlgorithm",
178 UnitSet => "UnitSet",
179 Unit => "Unit",
180 LongDescription => "LongDescription",
181 ReferenceTime => "ReferenceTime",
182 Epoch => "Epoch",
183 OffsetFrom => "OffsetFrom",
184 RepeatEntry => "RepeatEntry",
185 Count => "Count",
186 IncludeCondition => "IncludeCondition",
187 ServiceSet => "ServiceSet",
188 MessageSet => "MessageSet",
189 StreamSet => "StreamSet",
190 AlgorithmSet => "AlgorithmSet",
191 AliasSet => "AliasSet",
192 AncillaryDataSet => "AncillaryDataSet",
193 }
194}
195
196impl Tag {
197 #[must_use]
202 const fn is_skipped_section(self) -> bool {
203 matches!(
204 self,
205 Self::ServiceSet
206 | Self::MessageSet
207 | Self::StreamSet
208 | Self::AlgorithmSet
209 | Self::AliasSet
210 | Self::AncillaryDataSet
211 )
212 }
213}
214
215symbols! {
216 pub enum AttrKey {
218 Name => "name",
219 Abstract => "abstract",
220 ShortDescription => "shortDescription",
221 ParameterRef => "parameterRef",
222 ContainerRef => "containerRef",
223 ParameterTypeRef => "parameterTypeRef",
224 ArgumentTypeRef => "argumentTypeRef",
225 ArgumentRef => "argumentRef",
226 ArgumentName => "argumentName",
227 ArgumentValue => "argumentValue",
228 MetaCommandRef => "metaCommandRef",
229 BinaryValue => "binaryValue",
230 ArrayTypeRef => "arrayTypeRef",
231 TypeRef => "typeRef",
232 SizeInBits => "sizeInBits",
233 Encoding => "encoding",
234 ByteOrder => "byteOrder",
235 Value => "value",
236 Label => "label",
237 MaxValue => "maxValue",
238 ComparisonOperator => "comparisonOperator",
239 UseCalibratedValue => "useCalibratedValue",
240 Slope => "slope",
241 Intercept => "intercept",
242 Order => "order",
243 Extrapolate => "extrapolate",
244 Raw => "raw",
245 Calibrated => "calibrated",
246 Coefficient => "coefficient",
247 Exponent => "exponent",
248 Offset => "offset",
249 Scale => "scale",
250 Units => "units",
251 SizeInBitsOfSizeTag => "sizeInBitsOfSizeTag",
252 InitialValue => "initialValue",
253 ReferenceLocation => "referenceLocation",
254 ZeroStringValue => "zeroStringValue",
255 OneStringValue => "oneStringValue",
256 }
257}
258
259#[derive(Clone, Copy, Debug)]
270pub struct Node {
271 tag: Tag,
272 name: Span,
273 parent: u32,
274 first_child: u32,
275 next_sibling: u32,
276 attr_start: u32,
277 attr_len: u32,
278 text: Span,
280 has_text: bool,
281}
282
283#[derive(Clone, Copy, Debug)]
284struct Attr {
285 key: AttrKey,
286 name: Span,
287 value: Span,
288}
289
290pub struct Dom {
292 nodes: Vec<Node>,
293 attrs: Vec<Attr>,
294 last_child: Vec<u32>,
299 arena: String,
301 skipped_sections: Vec<String>,
302 xmlns: Option<String>,
303}
304
305#[derive(Clone, Copy)]
310pub struct Element<'d> {
311 dom: &'d Dom,
312 index: u32,
313}
314
315impl Dom {
316 pub fn parse(input: &str) -> Result<Self, ParseError> {
323 let approx_elements = input.len() / 48;
327 let mut dom = Self {
328 nodes: Vec::with_capacity(approx_elements),
329 attrs: Vec::with_capacity(approx_elements * 2),
330 last_child: Vec::with_capacity(approx_elements),
331 arena: String::with_capacity(input.len() / 4),
335 skipped_sections: Vec::new(),
336 xmlns: None,
337 };
338 dom.run(input)?;
339 Ok(dom)
340 }
341
342 #[inline]
344 fn push_text(&mut self, text: &str) -> Span {
345 let start = self.arena.len();
346 self.arena.push_str(text);
347 Span::between(start, self.arena.len())
348 }
349
350 #[inline]
351 fn str_at(&self, span: Span) -> &str {
352 let start = span.start();
353 self.arena
354 .get(start..start + span.len())
355 .unwrap_or_default()
356 }
357
358 fn run(&mut self, input: &str) -> Result<(), ParseError> {
359 let mut reader = Reader::from_str(input);
360 let config = reader.config_mut();
361 config.trim_text(true);
362 config.expand_empty_elements = false;
363 config.check_end_names = true;
364
365 let mut open: Vec<u32> = Vec::with_capacity(32);
367 let mut skipping: Option<usize> = None;
369 let mut scratch = String::new();
373
374 loop {
375 let event = match reader.read_event() {
376 Ok(event) => event,
377 Err(source) => return Err(ParseError::at_offset(reader.buffer_position(), source)),
378 };
379
380 match event {
381 Event::Start(start) => {
382 if let Some(depth) = skipping.as_mut() {
383 *depth += 1;
384 continue;
385 }
386 match self.open_element(&start, open.last().copied())? {
387 Some(index) => open.push(index),
388 None => skipping = Some(1),
389 }
390 scratch.clear();
391 }
392 Event::Empty(start) => {
393 if skipping.is_some() {
394 continue;
395 }
396 self.open_element(&start, open.last().copied())?;
397 }
398 Event::End(_) => match skipping.as_mut() {
399 Some(1) => skipping = None,
400 Some(depth) => *depth -= 1,
401 None => {
402 if let Some(index) = open.pop() {
403 if !scratch.trim().is_empty() {
404 let span = self.push_text(&scratch);
405 if let Some(node) = self.nodes.get_mut(index as usize) {
406 node.text = span;
407 node.has_text = true;
408 }
409 }
410 }
411 scratch.clear();
412 }
413 },
414 Event::Text(text) => {
415 if skipping.is_some() || open.is_empty() {
416 continue;
417 }
418 let offset = reader.buffer_position();
419 let decoded = text
420 .xml_content()
421 .map_err(|source| ParseError::at_offset(offset, source))?;
422 scratch.push_str(&decoded);
423 }
424 Event::CData(cdata) => {
425 if skipping.is_some() || open.is_empty() {
426 continue;
427 }
428 let offset = reader.buffer_position();
429 let decoded = cdata
430 .decode()
431 .map_err(|source| ParseError::at_offset(offset, source))?;
432 scratch.push_str(&decoded);
433 }
434 Event::GeneralRef(entity) => {
435 if skipping.is_some() || open.is_empty() {
436 continue;
437 }
438 let offset = reader.buffer_position();
439 push_entity(&mut scratch, &entity)
440 .map_err(|source| ParseError::at_offset(offset, source))?;
441 }
442 Event::Eof => break,
443 Event::Decl(_) | Event::PI(_) | Event::Comment(_) | Event::DocType(_) => {}
444 }
445 }
446
447 if self.nodes.is_empty() {
448 return Err(ParseError::new(ParseErrorKind::EmptyDocument));
449 }
450 Ok(())
451 }
452
453 fn open_element(
458 &mut self,
459 start: &quick_xml::events::BytesStart<'_>,
460 parent: Option<u32>,
461 ) -> Result<Option<u32>, ParseError> {
462 let local = start.local_name();
463 let local = std::str::from_utf8(local.as_ref()).unwrap_or_default();
464 let tag = Tag::from_text(local);
465 if tag.is_skipped_section() {
466 self.skipped_sections.push(local.to_owned());
467 return Ok(None);
468 }
469 let index = self.push_node(tag, local, parent);
470 self.push_attributes(index, start)?;
471 if index == 0 {
472 self.xmlns = element_namespace(start);
473 }
474 Ok(Some(index))
475 }
476
477 fn push_node(&mut self, tag: Tag, local: &str, parent: Option<u32>) -> u32 {
478 let name = if tag == Tag::Other {
481 self.push_text(local)
482 } else {
483 Span::EMPTY
484 };
485 let index = u32::try_from(self.nodes.len()).unwrap_or(NONE);
486 self.nodes.push(Node {
487 tag,
488 name,
489 parent: parent.unwrap_or(NONE),
490 first_child: NONE,
491 next_sibling: NONE,
492 attr_start: u32::try_from(self.attrs.len()).unwrap_or(0),
493 attr_len: 0,
494 text: Span::EMPTY,
495 has_text: false,
496 });
497 self.last_child.push(NONE);
498
499 if let Some(parent) = parent {
500 match self.last_child.get(parent as usize).copied() {
501 Some(NONE) | None => {
502 if let Some(node) = self.nodes.get_mut(parent as usize) {
503 node.first_child = index;
504 }
505 }
506 Some(previous) => {
507 if let Some(node) = self.nodes.get_mut(previous as usize) {
508 node.next_sibling = index;
509 }
510 }
511 }
512 if let Some(slot) = self.last_child.get_mut(parent as usize) {
513 *slot = index;
514 }
515 }
516 index
517 }
518
519 fn push_attributes(
520 &mut self,
521 index: u32,
522 start: &quick_xml::events::BytesStart<'_>,
523 ) -> Result<(), ParseError> {
524 let start_len = self.attrs.len();
525 for attr in start.attributes() {
526 let attr = attr.map_err(|source| ParseError::new(source.into()))?;
527 let key_bytes = attr.key.as_ref();
528 if key_bytes == b"xmlns" || key_bytes.starts_with(b"xmlns:") {
529 continue;
530 }
531 let key_local = attr.key.local_name();
532 let key_local = std::str::from_utf8(key_local.as_ref()).unwrap_or_default();
533 let value = attr
534 .unescape_value()
535 .map_err(|source| ParseError::new(source.into()))?;
536 let key = AttrKey::from_text(key_local);
537 let name = if key == AttrKey::Other {
538 self.push_text(key_local)
539 } else {
540 Span::EMPTY
541 };
542 let value = self.push_text(&value);
543 self.attrs.push(Attr { key, name, value });
544 }
545 if let Some(node) = self.nodes.get_mut(index as usize) {
546 node.attr_start = u32::try_from(start_len).unwrap_or(0);
547 node.attr_len = u32::try_from(self.attrs.len() - start_len).unwrap_or(0);
548 }
549 Ok(())
550 }
551
552 #[must_use]
554 pub fn root(&self) -> Element<'_> {
555 Element {
556 dom: self,
557 index: 0,
558 }
559 }
560
561 #[must_use]
563 pub fn skipped_sections(&self) -> &[String] {
564 &self.skipped_sections
565 }
566
567 #[must_use]
569 pub fn xmlns(&self) -> Option<&str> {
570 self.xmlns.as_deref()
571 }
572
573 #[must_use]
575 pub fn len(&self) -> usize {
576 self.nodes.len()
577 }
578
579 #[must_use]
581 pub fn is_empty(&self) -> bool {
582 self.nodes.is_empty()
583 }
584}
585
586impl<'d> Element<'d> {
587 fn node(self) -> &'d Node {
588 self.dom.nodes.get(self.index as usize).unwrap_or(&DETACHED)
591 }
592
593 #[must_use]
595 pub fn tag(self) -> Tag {
596 self.node().tag
597 }
598
599 #[must_use]
601 pub fn name(self) -> &'d str {
602 let node = self.node();
603 match node.tag {
604 Tag::Other => self.dom.str_at(node.name),
605 tag => tag.text(),
606 }
607 }
608
609 #[must_use]
611 pub fn parent(self) -> Option<Element<'d>> {
612 let parent = self.node().parent;
613 (parent != NONE).then_some(Element {
614 dom: self.dom,
615 index: parent,
616 })
617 }
618
619 #[must_use]
621 pub fn children(self) -> Children<'d> {
622 Children {
623 dom: self.dom,
624 next: self.node().first_child,
625 }
626 }
627
628 pub fn children_with(self, tag: Tag) -> impl Iterator<Item = Element<'d>> {
630 self.children().filter(move |child| child.tag() == tag)
631 }
632
633 #[must_use]
635 pub fn child(self, tag: Tag) -> Option<Element<'d>> {
636 self.children().find(|child| child.tag() == tag)
637 }
638
639 #[must_use]
644 pub fn descendant(self, tag: Tag) -> Option<Element<'d>> {
645 self.children().find_map(|child| {
646 if child.tag() == tag {
647 Some(child)
648 } else {
649 child.descendant(tag)
650 }
651 })
652 }
653
654 #[must_use]
657 pub fn descendant_any(self, tags: &[Tag]) -> Option<Element<'d>> {
658 for child in self.children() {
659 if tags.contains(&child.tag()) {
660 return Some(child);
661 }
662 }
663 self.children().find_map(|child| child.descendant_any(tags))
664 }
665
666 #[must_use]
668 pub fn attr(self, key: AttrKey) -> Option<&'d str> {
669 self.attrs_raw()
670 .iter()
671 .find(|attr| attr.key == key)
672 .map(|attr| self.dom.str_at(attr.value))
673 }
674
675 #[must_use]
677 pub fn attr_named(self, name: &str) -> Option<&'d str> {
678 self.attrs_raw()
679 .iter()
680 .find(|attr| self.attr_name(attr) == name)
681 .map(|attr| self.dom.str_at(attr.value))
682 }
683
684 pub fn attr_names(self) -> impl Iterator<Item = &'d str> {
686 self.attrs_raw()
687 .iter()
688 .map(move |attr| self.attr_name(attr))
689 }
690
691 fn attr_name(self, attr: &Attr) -> &'d str {
692 match attr.key {
693 AttrKey::Other => self.dom.str_at(attr.name),
694 key => key.text(),
695 }
696 }
697
698 fn attrs_raw(self) -> &'d [Attr] {
699 let node = self.node();
700 let start = node.attr_start as usize;
701 let end = start + node.attr_len as usize;
702 self.dom.attrs.get(start..end).unwrap_or_default()
703 }
704
705 #[must_use]
707 pub fn text(self) -> Option<&'d str> {
708 let node = self.node();
709 node.has_text.then(|| self.dom.str_at(node.text).trim())
710 }
711
712 #[must_use]
714 pub fn path(self) -> String {
715 let mut parts = Vec::new();
716 let mut cursor = Some(self);
717 while let Some(element) = cursor {
718 parts.push(element.name());
719 cursor = element.parent();
720 }
721 parts.reverse();
722 parts.join("/")
723 }
724}
725
726static DETACHED: Node = Node {
727 tag: Tag::Other,
728 name: Span::EMPTY,
729 parent: NONE,
730 first_child: NONE,
731 next_sibling: NONE,
732 attr_start: 0,
733 attr_len: 0,
734 text: Span::EMPTY,
735 has_text: false,
736};
737
738pub struct Children<'d> {
740 dom: &'d Dom,
741 next: u32,
742}
743
744impl<'d> Iterator for Children<'d> {
745 type Item = Element<'d>;
746
747 fn next(&mut self) -> Option<Self::Item> {
748 if self.next == NONE {
749 return None;
750 }
751 let index = self.next;
752 self.next = self
753 .dom
754 .nodes
755 .get(index as usize)
756 .map_or(NONE, |n| n.next_sibling);
757 Some(Element {
758 dom: self.dom,
759 index,
760 })
761 }
762}
763
764impl std::iter::FusedIterator for Children<'_> {}
765
766fn push_entity(
772 out: &mut String,
773 entity: &quick_xml::events::BytesRef<'_>,
774) -> Result<(), quick_xml::encoding::EncodingError> {
775 if entity.is_char_ref() {
776 if let Ok(Some(ch)) = entity.resolve_char_ref() {
777 out.push(ch);
778 return Ok(());
779 }
780 }
781 let name = entity.decode()?;
782 match name.as_ref() {
783 "amp" => out.push('&'),
784 "lt" => out.push('<'),
785 "gt" => out.push('>'),
786 "apos" => out.push('\''),
787 "quot" => out.push('"'),
788 other => {
789 out.push('&');
790 out.push_str(other);
791 out.push(';');
792 }
793 }
794 Ok(())
795}
796
797fn element_namespace(start: &quick_xml::events::BytesStart<'_>) -> Option<String> {
805 let qname = start.name();
806 let wanted: Vec<u8> = match qname.prefix() {
807 Some(prefix) => [b"xmlns:".as_slice(), prefix.as_ref()].concat(),
808 None => b"xmlns".to_vec(),
809 };
810 start
811 .attributes()
812 .flatten()
813 .find(|attr| attr.key.as_ref() == wanted.as_slice())
814 .and_then(|attr| String::from_utf8(attr.value.into_owned()).ok())
815}