use quick_xml::Reader;
use quick_xml::events::Event;
use crate::error::{ParseError, ParseErrorKind};
use crate::ids::Span;
const NONE: u32 = u32::MAX;
macro_rules! symbols {
($(#[$meta:meta])* $vis:vis enum $name:ident { $($variant:ident => $text:literal),* $(,)? }) => {
$(#[$meta])*
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
$vis enum $name {
$(
#[doc = concat!("The XML symbol `", $text, "`.")]
$variant,
)*
Other,
}
impl $name {
$vis const ALL: &'static [$name] = &[$($name::$variant,)*];
#[must_use]
$vis const fn text(self) -> &'static str {
match self {
$($name::$variant => $text,)*
$name::Other => "",
}
}
#[must_use]
$vis fn from_text(text: &str) -> Self {
match text {
$($text => $name::$variant,)*
_ => $name::Other,
}
}
}
};
}
symbols! {
pub enum Tag {
SpaceSystem => "SpaceSystem",
TelemetryMetaData => "TelemetryMetaData",
CommandMetaData => "CommandMetaData",
ArgumentTypeSet => "ArgumentTypeSet",
MetaCommandSet => "MetaCommandSet",
MetaCommand => "MetaCommand",
BaseMetaCommand => "BaseMetaCommand",
ArgumentAssignmentList => "ArgumentAssignmentList",
ArgumentAssignment => "ArgumentAssignment",
ArgumentList => "ArgumentList",
Argument => "Argument",
CommandContainer => "CommandContainer",
CommandContainerSet => "CommandContainerSet",
ArgumentRefEntry => "ArgumentRefEntry",
ArrayArgumentRefEntry => "ArrayArgumentRefEntry",
FixedValueEntry => "FixedValueEntry",
IntegerArgumentType => "IntegerArgumentType",
FloatArgumentType => "FloatArgumentType",
StringArgumentType => "StringArgumentType",
BinaryArgumentType => "BinaryArgumentType",
BooleanArgumentType => "BooleanArgumentType",
EnumeratedArgumentType => "EnumeratedArgumentType",
AbsoluteTimeArgumentType => "AbsoluteTimeArgumentType",
RelativeTimeArgumentType => "RelativeTimeArgumentType",
ArrayArgumentType => "ArrayArgumentType",
AggregateArgumentType => "AggregateArgumentType",
ParameterTypeSet => "ParameterTypeSet",
ParameterSet => "ParameterSet",
ContainerSet => "ContainerSet",
Parameter => "Parameter",
SequenceContainer => "SequenceContainer",
BaseContainer => "BaseContainer",
RestrictionCriteria => "RestrictionCriteria",
EntryList => "EntryList",
ParameterRefEntry => "ParameterRefEntry",
ContainerRefEntry => "ContainerRefEntry",
IndirectParameterRefEntry => "IndirectParameterRefEntry",
ArrayParameterRefEntry => "ArrayParameterRefEntry",
LocationInContainerInBits => "LocationInContainerInBits",
IntegerParameterType => "IntegerParameterType",
FloatParameterType => "FloatParameterType",
StringParameterType => "StringParameterType",
BinaryParameterType => "BinaryParameterType",
BooleanParameterType => "BooleanParameterType",
EnumeratedParameterType => "EnumeratedParameterType",
AbsoluteTimeParameterType => "AbsoluteTimeParameterType",
RelativeTimeParameterType => "RelativeTimeParameterType",
ArrayParameterType => "ArrayParameterType",
DimensionList => "DimensionList",
Dimension => "Dimension",
StartingIndex => "StartingIndex",
EndingIndex => "EndingIndex",
AggregateParameterType => "AggregateParameterType",
MemberList => "MemberList",
Member => "Member",
IntegerDataEncoding => "IntegerDataEncoding",
FloatDataEncoding => "FloatDataEncoding",
StringDataEncoding => "StringDataEncoding",
BinaryDataEncoding => "BinaryDataEncoding",
Encoding => "Encoding",
SizeInBits => "SizeInBits",
Fixed => "Fixed",
FixedValue => "FixedValue",
Variable => "Variable",
DynamicValue => "DynamicValue",
DiscreteLookupList => "DiscreteLookupList",
DiscreteLookup => "DiscreteLookup",
LeadingSize => "LeadingSize",
TerminationChar => "TerminationChar",
ParameterInstanceRef => "ParameterInstanceRef",
LinearAdjustment => "LinearAdjustment",
EnumerationList => "EnumerationList",
Enumeration => "Enumeration",
Comparison => "Comparison",
ComparisonList => "ComparisonList",
BooleanExpression => "BooleanExpression",
Condition => "Condition",
ANDedConditions => "ANDedConditions",
ORedConditions => "ORedConditions",
ComparisonOperator => "ComparisonOperator",
Value => "Value",
DefaultCalibrator => "DefaultCalibrator",
ContextCalibratorList => "ContextCalibratorList",
ContextCalibrator => "ContextCalibrator",
ContextMatch => "ContextMatch",
Calibrator => "Calibrator",
PolynomialCalibrator => "PolynomialCalibrator",
SplineCalibrator => "SplineCalibrator",
MathOperationCalibrator => "MathOperationCalibrator",
Term => "Term",
SplinePoint => "SplinePoint",
CustomAlgorithm => "CustomAlgorithm",
UnitSet => "UnitSet",
Unit => "Unit",
LongDescription => "LongDescription",
ReferenceTime => "ReferenceTime",
Epoch => "Epoch",
OffsetFrom => "OffsetFrom",
RepeatEntry => "RepeatEntry",
Count => "Count",
IncludeCondition => "IncludeCondition",
ServiceSet => "ServiceSet",
MessageSet => "MessageSet",
StreamSet => "StreamSet",
AlgorithmSet => "AlgorithmSet",
AliasSet => "AliasSet",
AncillaryDataSet => "AncillaryDataSet",
}
}
impl Tag {
#[must_use]
const fn is_skipped_section(self) -> bool {
matches!(
self,
Self::ServiceSet
| Self::MessageSet
| Self::StreamSet
| Self::AlgorithmSet
| Self::AliasSet
| Self::AncillaryDataSet
)
}
}
symbols! {
pub enum AttrKey {
Name => "name",
Abstract => "abstract",
ShortDescription => "shortDescription",
ParameterRef => "parameterRef",
ContainerRef => "containerRef",
ParameterTypeRef => "parameterTypeRef",
ArgumentTypeRef => "argumentTypeRef",
ArgumentRef => "argumentRef",
ArgumentName => "argumentName",
ArgumentValue => "argumentValue",
MetaCommandRef => "metaCommandRef",
BinaryValue => "binaryValue",
ArrayTypeRef => "arrayTypeRef",
TypeRef => "typeRef",
SizeInBits => "sizeInBits",
Encoding => "encoding",
ByteOrder => "byteOrder",
Value => "value",
Label => "label",
MaxValue => "maxValue",
ComparisonOperator => "comparisonOperator",
UseCalibratedValue => "useCalibratedValue",
Slope => "slope",
Intercept => "intercept",
Order => "order",
Extrapolate => "extrapolate",
Raw => "raw",
Calibrated => "calibrated",
Coefficient => "coefficient",
Exponent => "exponent",
Offset => "offset",
Scale => "scale",
Units => "units",
SizeInBitsOfSizeTag => "sizeInBitsOfSizeTag",
InitialValue => "initialValue",
ReferenceLocation => "referenceLocation",
ZeroStringValue => "zeroStringValue",
OneStringValue => "oneStringValue",
}
}
#[derive(Clone, Copy, Debug)]
pub struct Node {
tag: Tag,
name: Span,
parent: u32,
first_child: u32,
next_sibling: u32,
attr_start: u32,
attr_len: u32,
text: Span,
has_text: bool,
}
#[derive(Clone, Copy, Debug)]
struct Attr {
key: AttrKey,
name: Span,
value: Span,
}
pub struct Dom {
nodes: Vec<Node>,
attrs: Vec<Attr>,
last_child: Vec<u32>,
arena: String,
skipped_sections: Vec<String>,
xmlns: Option<String>,
}
#[derive(Clone, Copy)]
pub struct Element<'d> {
dom: &'d Dom,
index: u32,
}
impl Dom {
pub fn parse(input: &str) -> Result<Self, ParseError> {
let approx_elements = input.len() / 48;
let mut dom = Self {
nodes: Vec::with_capacity(approx_elements),
attrs: Vec::with_capacity(approx_elements * 2),
last_child: Vec::with_capacity(approx_elements),
arena: String::with_capacity(input.len() / 4),
skipped_sections: Vec::new(),
xmlns: None,
};
dom.run(input)?;
Ok(dom)
}
#[inline]
fn push_text(&mut self, text: &str) -> Span {
let start = self.arena.len();
self.arena.push_str(text);
Span::between(start, self.arena.len())
}
#[inline]
fn str_at(&self, span: Span) -> &str {
let start = span.start();
self.arena
.get(start..start + span.len())
.unwrap_or_default()
}
fn run(&mut self, input: &str) -> Result<(), ParseError> {
let mut reader = Reader::from_str(input);
let config = reader.config_mut();
config.trim_text(true);
config.expand_empty_elements = false;
config.check_end_names = true;
let mut open: Vec<u32> = Vec::with_capacity(32);
let mut skipping: Option<usize> = None;
let mut scratch = String::new();
loop {
let event = match reader.read_event() {
Ok(event) => event,
Err(source) => return Err(ParseError::at_offset(reader.buffer_position(), source)),
};
match event {
Event::Start(start) => {
if let Some(depth) = skipping.as_mut() {
*depth += 1;
continue;
}
match self.open_element(&start, open.last().copied())? {
Some(index) => open.push(index),
None => skipping = Some(1),
}
scratch.clear();
}
Event::Empty(start) => {
if skipping.is_some() {
continue;
}
self.open_element(&start, open.last().copied())?;
}
Event::End(_) => match skipping.as_mut() {
Some(1) => skipping = None,
Some(depth) => *depth -= 1,
None => {
if let Some(index) = open.pop() {
if !scratch.trim().is_empty() {
let span = self.push_text(&scratch);
if let Some(node) = self.nodes.get_mut(index as usize) {
node.text = span;
node.has_text = true;
}
}
}
scratch.clear();
}
},
Event::Text(text) => {
if skipping.is_some() || open.is_empty() {
continue;
}
let offset = reader.buffer_position();
let decoded = text
.xml_content()
.map_err(|source| ParseError::at_offset(offset, source))?;
scratch.push_str(&decoded);
}
Event::CData(cdata) => {
if skipping.is_some() || open.is_empty() {
continue;
}
let offset = reader.buffer_position();
let decoded = cdata
.decode()
.map_err(|source| ParseError::at_offset(offset, source))?;
scratch.push_str(&decoded);
}
Event::GeneralRef(entity) => {
if skipping.is_some() || open.is_empty() {
continue;
}
let offset = reader.buffer_position();
push_entity(&mut scratch, &entity)
.map_err(|source| ParseError::at_offset(offset, source))?;
}
Event::Eof => break,
Event::Decl(_) | Event::PI(_) | Event::Comment(_) | Event::DocType(_) => {}
}
}
if self.nodes.is_empty() {
return Err(ParseError::new(ParseErrorKind::EmptyDocument));
}
Ok(())
}
fn open_element(
&mut self,
start: &quick_xml::events::BytesStart<'_>,
parent: Option<u32>,
) -> Result<Option<u32>, ParseError> {
let local = start.local_name();
let local = std::str::from_utf8(local.as_ref()).unwrap_or_default();
let tag = Tag::from_text(local);
if tag.is_skipped_section() {
self.skipped_sections.push(local.to_owned());
return Ok(None);
}
let index = self.push_node(tag, local, parent);
self.push_attributes(index, start)?;
if index == 0 {
self.xmlns = element_namespace(start);
}
Ok(Some(index))
}
fn push_node(&mut self, tag: Tag, local: &str, parent: Option<u32>) -> u32 {
let name = if tag == Tag::Other {
self.push_text(local)
} else {
Span::EMPTY
};
let index = u32::try_from(self.nodes.len()).unwrap_or(NONE);
self.nodes.push(Node {
tag,
name,
parent: parent.unwrap_or(NONE),
first_child: NONE,
next_sibling: NONE,
attr_start: u32::try_from(self.attrs.len()).unwrap_or(0),
attr_len: 0,
text: Span::EMPTY,
has_text: false,
});
self.last_child.push(NONE);
if let Some(parent) = parent {
match self.last_child.get(parent as usize).copied() {
Some(NONE) | None => {
if let Some(node) = self.nodes.get_mut(parent as usize) {
node.first_child = index;
}
}
Some(previous) => {
if let Some(node) = self.nodes.get_mut(previous as usize) {
node.next_sibling = index;
}
}
}
if let Some(slot) = self.last_child.get_mut(parent as usize) {
*slot = index;
}
}
index
}
fn push_attributes(
&mut self,
index: u32,
start: &quick_xml::events::BytesStart<'_>,
) -> Result<(), ParseError> {
let start_len = self.attrs.len();
for attr in start.attributes() {
let attr = attr.map_err(|source| ParseError::new(source.into()))?;
let key_bytes = attr.key.as_ref();
if key_bytes == b"xmlns" || key_bytes.starts_with(b"xmlns:") {
continue;
}
let key_local = attr.key.local_name();
let key_local = std::str::from_utf8(key_local.as_ref()).unwrap_or_default();
let value = attr
.unescape_value()
.map_err(|source| ParseError::new(source.into()))?;
let key = AttrKey::from_text(key_local);
let name = if key == AttrKey::Other {
self.push_text(key_local)
} else {
Span::EMPTY
};
let value = self.push_text(&value);
self.attrs.push(Attr { key, name, value });
}
if let Some(node) = self.nodes.get_mut(index as usize) {
node.attr_start = u32::try_from(start_len).unwrap_or(0);
node.attr_len = u32::try_from(self.attrs.len() - start_len).unwrap_or(0);
}
Ok(())
}
#[must_use]
pub fn root(&self) -> Element<'_> {
Element {
dom: self,
index: 0,
}
}
#[must_use]
pub fn skipped_sections(&self) -> &[String] {
&self.skipped_sections
}
#[must_use]
pub fn xmlns(&self) -> Option<&str> {
self.xmlns.as_deref()
}
#[must_use]
pub fn len(&self) -> usize {
self.nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
}
impl<'d> Element<'d> {
fn node(self) -> &'d Node {
self.dom.nodes.get(self.index as usize).unwrap_or(&DETACHED)
}
#[must_use]
pub fn tag(self) -> Tag {
self.node().tag
}
#[must_use]
pub fn name(self) -> &'d str {
let node = self.node();
match node.tag {
Tag::Other => self.dom.str_at(node.name),
tag => tag.text(),
}
}
#[must_use]
pub fn parent(self) -> Option<Element<'d>> {
let parent = self.node().parent;
(parent != NONE).then_some(Element {
dom: self.dom,
index: parent,
})
}
#[must_use]
pub fn children(self) -> Children<'d> {
Children {
dom: self.dom,
next: self.node().first_child,
}
}
pub fn children_with(self, tag: Tag) -> impl Iterator<Item = Element<'d>> {
self.children().filter(move |child| child.tag() == tag)
}
#[must_use]
pub fn child(self, tag: Tag) -> Option<Element<'d>> {
self.children().find(|child| child.tag() == tag)
}
#[must_use]
pub fn descendant(self, tag: Tag) -> Option<Element<'d>> {
self.children().find_map(|child| {
if child.tag() == tag {
Some(child)
} else {
child.descendant(tag)
}
})
}
#[must_use]
pub fn descendant_any(self, tags: &[Tag]) -> Option<Element<'d>> {
for child in self.children() {
if tags.contains(&child.tag()) {
return Some(child);
}
}
self.children().find_map(|child| child.descendant_any(tags))
}
#[must_use]
pub fn attr(self, key: AttrKey) -> Option<&'d str> {
self.attrs_raw()
.iter()
.find(|attr| attr.key == key)
.map(|attr| self.dom.str_at(attr.value))
}
#[must_use]
pub fn attr_named(self, name: &str) -> Option<&'d str> {
self.attrs_raw()
.iter()
.find(|attr| self.attr_name(attr) == name)
.map(|attr| self.dom.str_at(attr.value))
}
pub fn attr_names(self) -> impl Iterator<Item = &'d str> {
self.attrs_raw()
.iter()
.map(move |attr| self.attr_name(attr))
}
fn attr_name(self, attr: &Attr) -> &'d str {
match attr.key {
AttrKey::Other => self.dom.str_at(attr.name),
key => key.text(),
}
}
fn attrs_raw(self) -> &'d [Attr] {
let node = self.node();
let start = node.attr_start as usize;
let end = start + node.attr_len as usize;
self.dom.attrs.get(start..end).unwrap_or_default()
}
#[must_use]
pub fn text(self) -> Option<&'d str> {
let node = self.node();
node.has_text.then(|| self.dom.str_at(node.text).trim())
}
#[must_use]
pub fn path(self) -> String {
let mut parts = Vec::new();
let mut cursor = Some(self);
while let Some(element) = cursor {
parts.push(element.name());
cursor = element.parent();
}
parts.reverse();
parts.join("/")
}
}
static DETACHED: Node = Node {
tag: Tag::Other,
name: Span::EMPTY,
parent: NONE,
first_child: NONE,
next_sibling: NONE,
attr_start: 0,
attr_len: 0,
text: Span::EMPTY,
has_text: false,
};
pub struct Children<'d> {
dom: &'d Dom,
next: u32,
}
impl<'d> Iterator for Children<'d> {
type Item = Element<'d>;
fn next(&mut self) -> Option<Self::Item> {
if self.next == NONE {
return None;
}
let index = self.next;
self.next = self
.dom
.nodes
.get(index as usize)
.map_or(NONE, |n| n.next_sibling);
Some(Element {
dom: self.dom,
index,
})
}
}
impl std::iter::FusedIterator for Children<'_> {}
fn push_entity(
out: &mut String,
entity: &quick_xml::events::BytesRef<'_>,
) -> Result<(), quick_xml::encoding::EncodingError> {
if entity.is_char_ref() {
if let Ok(Some(ch)) = entity.resolve_char_ref() {
out.push(ch);
return Ok(());
}
}
let name = entity.decode()?;
match name.as_ref() {
"amp" => out.push('&'),
"lt" => out.push('<'),
"gt" => out.push('>'),
"apos" => out.push('\''),
"quot" => out.push('"'),
other => {
out.push('&');
out.push_str(other);
out.push(';');
}
}
Ok(())
}
fn element_namespace(start: &quick_xml::events::BytesStart<'_>) -> Option<String> {
let qname = start.name();
let wanted: Vec<u8> = match qname.prefix() {
Some(prefix) => [b"xmlns:".as_slice(), prefix.as_ref()].concat(),
None => b"xmlns".to_vec(),
};
start
.attributes()
.flatten()
.find(|attr| attr.key.as_ref() == wanted.as_slice())
.and_then(|attr| String::from_utf8(attr.value.into_owned()).ok())
}