mod cursor;
mod markup;
mod reader;
mod tags;
mod text;
#[cfg(test)]
mod tests;
use cursor::Cursor;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Location {
pub(crate) start_line: usize,
pub(crate) start_column: usize,
pub(crate) start_offset: usize,
pub(crate) end_line: usize,
pub(crate) end_column: usize,
pub(crate) end_offset: usize,
}
impl Location {
pub(crate) fn slice<'s>(&self, source: &'s str) -> Option<&'s str> {
source.get(self.start_offset..self.end_offset)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Attribute {
pub(crate) name: String,
pub(crate) value: String,
pub(crate) location: Location,
pub(crate) value_location: Location,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Element {
pub(crate) name: String,
pub(crate) namespace: Option<String>,
pub(crate) attributes: Vec<Attribute>,
pub(crate) children: Vec<Node>,
pub(crate) location: Location,
}
impl Drop for Element {
fn drop(&mut self) {
let mut pending = std::mem::take(&mut self.children);
while let Some(node) = pending.pop() {
if let Node::Element(mut element) = node {
pending.append(&mut element.children);
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Text {
pub(crate) value: String,
pub(crate) location: Location,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Node {
Element(Element),
Text(Text),
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
InvalidEncoding,
ByteOrderMark,
MissingRoot,
ContentBeforeRoot,
ContentAfterRoot,
UnexpectedEnd,
ExpectedName,
ExpectedEquals,
ExpectedQuote,
ExpectedWhitespace,
ExpectedTagEnd,
LtInAttributeValue,
MismatchedEndTag,
UnclosedElement,
UnterminatedComment,
DoubleHyphenInComment,
UnterminatedCdata,
UnterminatedProcessingInstruction,
MisplacedXmlDeclaration,
MalformedXmlDeclaration,
UnsupportedEncoding,
ReservedTarget,
UnterminatedDoctype,
AmbiguousDoctype,
MalformedReference,
InvalidCharacterReference,
InvalidCharacter,
CdataEndInText,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ParseError {
pub(crate) reason: Reason,
pub(crate) message: String,
pub(crate) location: Location,
}
pub(crate) fn parse(source: &[u8]) -> Result<Element, ParseError> {
let text = match std::str::from_utf8(source) {
Ok(text) => text,
Err(error) => {
let valid = source
.get(..error.valid_up_to())
.and_then(|bytes| std::str::from_utf8(bytes).ok())
.unwrap_or("");
let mut cursor = Cursor::new(valid);
cursor.move_to_end();
return Err(cursor.refuse(Reason::InvalidEncoding, "the document is not valid UTF-8"));
}
};
if text.starts_with('\u{FEFF}') {
return Err(
Cursor::new(text).refuse(Reason::ByteOrderMark, "a byte order mark is not read")
);
}
reader::Reader::new(text).document()
}