f_office_xml/fragment.rs
1//! A fragment of XML, parsed as the content of an element of another document, with the
2//! namespace declarations in scope there.
3
4use crate::{Builder, Document, Error, Limits, NodeId};
5
6/// The name of the element that holds a fragment while it is parsed.
7const CONTAINER: &str = "fragment";
8
9/// XML parsed as the content of an element of another document ([`Document::parse_fragment`]):
10/// a document whose nodes stand for the fragment's, in order.
11#[derive(Clone, Debug)]
12pub struct Fragment {
13 document: Document,
14 nodes: Vec<NodeId>,
15}
16
17impl Fragment {
18 /// The document that holds the fragment's nodes. Its spans count from the fragment's
19 /// first byte.
20 #[must_use]
21 pub const fn document(&self) -> &Document {
22 &self.document
23 }
24
25 /// The fragment's nodes at its top, in order: its elements, text, comments and processing
26 /// instructions.
27 #[must_use]
28 pub fn nodes(&self) -> &[NodeId] {
29 &self.nodes
30 }
31}
32
33impl Document {
34 /// Parses `bytes` as the content of an element at which the namespace declarations
35 /// `in_scope` are in scope, such as the bytes of an element's span or the new XML of an
36 /// edit in its place: each prefix (`""` for the default namespace) with its URI, as
37 /// [`Document::namespaces_in_scope`] gives them. Each URI binds as given: the reader binds
38 /// a namespace to its declaration's value as written, with no reference resolved, so a
39 /// URI of a part binds the same in the fragment. A prefix that neither the fragment nor
40 /// `in_scope` declares is an error here, unlike in a part, because the fragment is to
41 /// stand in a part where it must read.
42 ///
43 /// # Errors
44 ///
45 /// Returns [`Error::UndeclaredPrefix`] for a prefix without a declaration, and every error
46 /// of [`Document::parse`]; a prefix of `in_scope` that is no name, a URI that holds both
47 /// quotation marks, and a fragment that closes the element that it stands in, are
48 /// [`Error::Syntax`].
49 pub fn parse_fragment(
50 bytes: &[u8],
51 in_scope: &[(String, String)],
52 limits: &Limits,
53 ) -> Result<Fragment, Error> {
54 let fragment = Self::parse_fragment_with_aliases_at(bytes, in_scope, &[], 0, limits)?;
55 if let Some(prefix) = fragment.document.undeclared_prefixes.first() {
56 return Err(Error::UndeclaredPrefix(prefix.clone()));
57 }
58 Ok(fragment)
59 }
60
61 /// Parses `bytes` as a slice of a larger XML part starting at `base_offset`, resolving
62 /// namespace declarations `in_scope` and namespace `aliases`, while recording undeclared
63 /// prefixes on [`Document::undeclared_prefixes`] instead of failing.
64 ///
65 /// Node byte spans returned by [`Document::span`] are shifted by `base_offset` so they match
66 /// exact byte offsets in the enclosing part.
67 ///
68 /// # Errors
69 ///
70 /// Returns the errors of [`Document::parse_with_aliases`], or [`Error::Syntax`] when
71 /// `in_scope` contains an invalid prefix/URI or `bytes` closes the synthetic container.
72 pub fn parse_fragment_with_aliases_at(
73 bytes: &[u8],
74 in_scope: &[(String, String)],
75 aliases: &[(&str, &str)],
76 base_offset: u64,
77 limits: &Limits,
78 ) -> Result<Fragment, Error> {
79 let mut container = format!("<{CONTAINER}");
80 for (prefix, uri) in in_scope {
81 if prefix != "xml" && prefix != "xmlns" {
82 container.push_str(&declaration(prefix, uri)?);
83 }
84 }
85 container.push('>');
86 let offset = container.len();
87 let mut wrapped = container.into_bytes();
88 wrapped.extend_from_slice(bytes);
89 wrapped.extend_from_slice(format!("</{CONTAINER}>").as_bytes());
90 let mut builder = Builder::new(*limits, aliases);
91 builder.offset = offset as u64;
92 builder.base_offset = base_offset;
93 let document = builder.run(&wrapped)?;
94 let [container] = document.top.as_slice() else {
95 return Err(Error::Syntax(
96 "the fragment closes the element that it stands in".to_owned(),
97 ));
98 };
99 let nodes = document.children(*container).to_vec();
100 Ok(Fragment { document, nodes })
101 }
102}
103
104/// The attribute that declares `prefix` (`""` for the default namespace) with `uri` as written,
105/// in a quotation mark that the URI does not hold.
106fn declaration(prefix: &str, uri: &str) -> Result<String, Error> {
107 if !prefix
108 .chars()
109 .all(|ch| ch.is_alphanumeric() || matches!(ch, '_' | '-' | '.'))
110 {
111 return Err(Error::Syntax(format!(
112 "{prefix:?} is not a namespace prefix"
113 )));
114 }
115 let quote = match (uri.contains('"'), uri.contains('\'')) {
116 (false, _) => '"',
117 (true, false) => '\'',
118 (true, true) => {
119 return Err(Error::Syntax(
120 "a namespace URI holds both quotation marks".to_owned(),
121 ));
122 }
123 };
124 let name = if prefix.is_empty() {
125 "xmlns".to_owned()
126 } else {
127 format!("xmlns:{prefix}")
128 };
129 Ok(format!(" {name}={quote}{uri}{quote}"))
130}