Skip to main content

documented_toml/
source.rs

1//! Input documents, before the merge walks them.
2
3use toml_edit::{Document, DocumentMut, Table, TomlError};
4
5use crate::report::SpanIndex;
6
7/// One of the two documents a merge is given, after parsing.
8///
9/// Zero bytes and "parsed, but declares no keys" are different states, and only
10/// byte length decides which. A file holding `# notes to self` is not empty: it
11/// has text that has to survive the merge, and default keys are written in
12/// beneath it. Only a file of no length has nothing to preserve.
13#[derive(Debug, Clone)]
14pub enum SourceDocument {
15    /// Zero bytes. Nothing to parse, nothing to keep.
16    Empty,
17    /// Text that parsed. The root table may hold no keys, which is a document
18    /// with content all the same.
19    Content {
20        /// The root table. Every key, table and array of tables in the document
21        /// nests inside it.
22        root: Table,
23        /// Whitespace and comments after the last element, which belong to no
24        /// key. A comment-only document is all trailing and no keys.
25        trailing: String,
26    },
27}
28
29impl SourceDocument {
30    /// Parses a document, keeping nothing but the root table and the trailing
31    /// text. Spans are discarded; use [`SourceDocument::parse_with_spans`] for
32    /// the document diagnostics point into.
33    pub fn parse(src: &str) -> Result<Self, TomlError> {
34        Ok(Self::parse_with_spans(src)?.0)
35    }
36
37    /// Parses a document and harvests its key spans first.
38    ///
39    /// `Document::into_mut` resolves spans into owned strings and the
40    /// `span()` accessors then return `None`, so positions have to be taken
41    /// before the conversion. There is no way back.
42    pub fn parse_with_spans(src: &str) -> Result<(Self, SpanIndex), TomlError> {
43        if src.is_empty() {
44            return Ok((Self::Empty, SpanIndex::default()));
45        }
46        let parsed = Document::parse(src)?;
47        let spans = SpanIndex::build(parsed.as_table());
48        let document: DocumentMut = parsed.into_mut();
49        let trailing = document.trailing().as_str().unwrap_or_default().to_owned();
50        Ok((
51            Self::Content {
52                root: document.into_table(),
53                trailing,
54            },
55            spans,
56        ))
57    }
58
59    /// The root table, or `None` for a zero-byte document.
60    pub fn root(&self) -> Option<&Table> {
61        match self {
62            Self::Empty => None,
63            Self::Content { root, .. } => Some(root),
64        }
65    }
66
67    /// The root table, mutable, or `None` for a zero-byte document.
68    pub(crate) fn root_mut(&mut self) -> Option<&mut Table> {
69        match self {
70            Self::Empty => None,
71            Self::Content { root, .. } => Some(root),
72        }
73    }
74
75    /// The text after the last element, empty for a zero-byte document.
76    pub fn trailing(&self) -> &str {
77        match self {
78            Self::Empty => "",
79            Self::Content { trailing, .. } => trailing,
80        }
81    }
82
83    /// Whether the document parsed and declares no keys. A zero-byte document
84    /// is not one of these: it has no text at all.
85    pub fn has_text_but_no_keys(&self) -> bool {
86        match self {
87            Self::Empty => false,
88            Self::Content { root, .. } => root.is_empty(),
89        }
90    }
91}