use toml_edit::{Document, DocumentMut, Table, TomlError};
use crate::report::SpanIndex;
#[derive(Debug, Clone)]
pub enum SourceDocument {
Empty,
Content {
root: Table,
trailing: String,
},
}
impl SourceDocument {
pub fn parse(src: &str) -> Result<Self, TomlError> {
Ok(Self::parse_with_spans(src)?.0)
}
pub fn parse_with_spans(src: &str) -> Result<(Self, SpanIndex), TomlError> {
if src.is_empty() {
return Ok((Self::Empty, SpanIndex::default()));
}
let parsed = Document::parse(src)?;
let spans = SpanIndex::build(parsed.as_table());
let document: DocumentMut = parsed.into_mut();
let trailing = document.trailing().as_str().unwrap_or_default().to_owned();
Ok((
Self::Content {
root: document.into_table(),
trailing,
},
spans,
))
}
pub fn root(&self) -> Option<&Table> {
match self {
Self::Empty => None,
Self::Content { root, .. } => Some(root),
}
}
pub(crate) fn root_mut(&mut self) -> Option<&mut Table> {
match self {
Self::Empty => None,
Self::Content { root, .. } => Some(root),
}
}
pub fn trailing(&self) -> &str {
match self {
Self::Empty => "",
Self::Content { trailing, .. } => trailing,
}
}
pub fn has_text_but_no_keys(&self) -> bool {
match self {
Self::Empty => false,
Self::Content { root, .. } => root.is_empty(),
}
}
}