Skip to main content

zumen_xml/
lib.rs

1//! XML の L0(決定 0008・0209)。
2//!
3//! 形式の意味を知らずに、要素・属性・文字と名前空間を、元のバイト範囲のまま読む。
4//! UTF-8・Shift_JIS・UTF-16LE・UTF-16BE に対応する。UTF-16 の解析用の UTF-8 と原本の位置を
5//! 対応づけ、公開する範囲と [`Document::src`] は原本を保つ。文字にするのは [`Document::text`] と
6//! [`Document::value`] で行う。名前の比較には [`Document::parsed_local_name`] を使う。
7//!
8//! 文書型宣言(DTD)は処理しない。外部の DTD と実体を解決せず、DTD で宣言する実体の参照は戻さない。
9
10mod name;
11mod parse;
12mod text;
13mod utf16;
14mod write;
15
16use core::ops::Range;
17use std::borrow::Cow;
18
19pub use parse::read;
20pub use write::{Edit, NewElement, write};
21
22/// 文書の文字コード
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum Encoding {
26    /// UTF-8。XML 宣言がないか、宣言が `UTF-8` のもの
27    Utf8,
28    /// Shift_JIS(WHATWG の Shift_JIS。`Shift_JIS`・`windows-31j` などの名前)
29    ShiftJis,
30    /// UTF-16 のリトルエンディアン
31    Utf16Le,
32    /// UTF-16 のビッグエンディアン
33    Utf16Be,
34}
35
36/// 名前空間
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Namespace {
39    /// 文書が宣言した名前空間。範囲は、宣言の属性の値の内側
40    Declared(Range<usize>),
41    /// 接頭辞 `xml` の名前空間(`http://www.w3.org/XML/1998/namespace`)
42    Xml,
43    /// 名前空間の宣言の属性(`xmlns`・`xmlns:…`)の名前空間(`http://www.w3.org/2000/xmlns/`)
44    Xmlns,
45}
46
47/// 要素か属性の名前
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Name {
50    raw: Range<usize>,
51    local: usize,
52    prefix_end: Option<usize>,
53    namespace: Option<Namespace>,
54}
55
56impl Name {
57    /// 書いたままの名前の範囲(`p:name`)
58    pub fn raw(&self) -> Range<usize> {
59        self.raw.clone()
60    }
61
62    /// 接頭辞の範囲。なければ `None`
63    pub fn prefix(&self) -> Option<Range<usize>> {
64        self.prefix_end.map(|end| self.raw.start..end)
65    }
66
67    /// 接頭辞を除いた名前の範囲
68    pub fn local(&self) -> Range<usize> {
69        self.local..self.raw.end
70    }
71
72    /// 名前空間。名前空間のない名前と、宣言されていない接頭辞の名前は `None`
73    pub fn namespace(&self) -> Option<&Namespace> {
74        self.namespace.as_ref()
75    }
76}
77
78/// 属性
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct Attribute {
81    name: Name,
82    value: Range<usize>,
83}
84
85impl Attribute {
86    /// 名前
87    pub fn name(&self) -> &Name {
88        &self.name
89    }
90
91    /// 値の引用符の内側の範囲。参照は戻さない
92    pub fn raw(&self) -> Range<usize> {
93        self.value.clone()
94    }
95}
96
97/// 要素の中身
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub enum Node {
100    /// 子の要素。[`Document::element`] の番号
101    Element(usize),
102    /// 文字。参照は戻さない
103    Text(Range<usize>),
104    /// `<![CDATA[…]]>` の内側
105    CData(Range<usize>),
106}
107
108/// 要素
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct Element {
111    span: Range<usize>,
112    name: Name,
113    attributes: Vec<Attribute>,
114    children: Vec<Node>,
115    parent: Option<usize>,
116}
117
118impl Element {
119    /// 開始タグから終了タグまで(空要素はそのタグ)の範囲
120    pub fn span(&self) -> Range<usize> {
121        self.span.clone()
122    }
123
124    /// 名前
125    pub fn name(&self) -> &Name {
126        &self.name
127    }
128
129    /// 属性。書いた順
130    pub fn attributes(&self) -> &[Attribute] {
131        &self.attributes
132    }
133
134    /// 中身。書いた順。注記と処理命令は入れない
135    pub fn children(&self) -> &[Node] {
136        &self.children
137    }
138
139    /// 親の要素の番号。ルートにはない
140    pub fn parent(&self) -> Option<usize> {
141        self.parent
142    }
143}
144
145/// 読んだ XML の文書。元のバイト列と、要素
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct Document {
148    src: Vec<u8>,
149    encoding: Encoding,
150    elements: Vec<Element>,
151    doctype: Option<Range<usize>>,
152    decoded: Option<utf16::Decoded>,
153}
154
155impl Document {
156    /// 文字コード
157    pub fn encoding(&self) -> Encoding {
158        self.encoding
159    }
160
161    /// 元のバイト列
162    pub fn src(&self) -> &[u8] {
163        &self.src
164    }
165
166    /// 元のバイト列の範囲。外なら空
167    pub fn bytes(&self, range: Range<usize>) -> &[u8] {
168        self.src.get(range).unwrap_or_default()
169    }
170
171    /// ルートの要素の番号。いつも 0
172    pub fn root(&self) -> usize {
173        0
174    }
175
176    /// 番号の要素。番号は、開始タグを書いた順
177    pub fn element(&self, index: usize) -> Option<&Element> {
178        self.elements.get(index)
179    }
180
181    /// 要素。開始タグを書いた順
182    pub fn elements(&self) -> &[Element] {
183        &self.elements
184    }
185
186    /// 文書型宣言(`<!DOCTYPE …>`)の範囲。処理はしない
187    pub fn doctype(&self) -> Option<Range<usize>> {
188        self.doctype.clone()
189    }
190
191    /// 名前の、接頭辞を除いた部分のバイト列
192    pub fn local_name(&self, name: &Name) -> &[u8] {
193        self.bytes(name.local())
194    }
195
196    /// 字句解析に使う名前。UTF-16 は UTF-8、UTF-8 と Shift_JIS は元の文字コードのまま。
197    /// ASCII の要素名の比較に使う。原本の取得は [`Self::local_name`]、文字は [`Self::local_name_text`]。
198    pub fn parsed_local_name(&self, name: &Name) -> &[u8] {
199        match &self.decoded {
200            Some(decoded) => decoded
201                .bytes
202                .get(decoded.decoded_range(name.local()))
203                .unwrap_or_default(),
204            None => self.local_name(name),
205        }
206    }
207
208    /// 接頭辞を除いた名前を文字にする。原本の範囲を返す [`Self::local_name`] と区別する。
209    pub fn local_name_text(&self, name: &Name) -> Cow<'_, str> {
210        if let Some(decoded) = &self.decoded {
211            return String::from_utf8_lossy(
212                decoded
213                    .bytes
214                    .get(decoded.decoded_range(name.local()))
215                    .unwrap_or_default(),
216            );
217        }
218        match self.encoding {
219            Encoding::Utf8 => String::from_utf8_lossy(self.local_name(name)),
220            Encoding::ShiftJis => {
221                encoding_rs::SHIFT_JIS
222                    .decode_without_bom_handling(self.local_name(name))
223                    .0
224            }
225            Encoding::Utf16Le | Encoding::Utf16Be => Cow::Owned(self.text(name.local())),
226        }
227    }
228
229    /// 名前空間の名前(URI)。名前空間がなければ `None`
230    pub fn namespace(&self, name: &Name) -> Option<String> {
231        match name.namespace()? {
232            Namespace::Declared(range) => Some(self.value_of(range.clone())),
233            Namespace::Xml => Some(String::from("http://www.w3.org/XML/1998/namespace")),
234            Namespace::Xmlns => Some(String::from("http://www.w3.org/2000/xmlns/")),
235        }
236    }
237
238    /// 名前の名前空間が `namespace`(URI)で、接頭辞を除いた名前が `local` なら真。
239    /// `local` は [`Document::parsed_local_name`] とバイトで比べる。非 ASCII の文字列は [`Document::local_name_text`] で比べる
240    pub fn is(&self, name: &Name, namespace: Option<&str>, local: &[u8]) -> bool {
241        self.parsed_local_name(name) == local && self.namespace(name).as_deref() == namespace
242    }
243
244    /// 文字の範囲を文字にする。文字コードを戻し、改行を `\n` にそろえ、定義済みの実体と文字の参照を戻す。
245    /// DTD で宣言する実体の参照は、そのまま残す
246    pub fn text(&self, range: Range<usize>) -> String {
247        text::decode(self.encoding, self.bytes(range), text::Mode::Text)
248    }
249
250    /// `<![CDATA[…]]>` の内側を文字にする。文字コードを戻し、改行を `\n` にそろえる。参照は戻さない
251    pub fn cdata(&self, range: Range<usize>) -> String {
252        text::decode(self.encoding, self.bytes(range), text::Mode::CData)
253    }
254
255    /// 属性の値を文字にする。[`Document::text`] に加え、XML の属性の値の正規化で、空白の文字を空白にする
256    pub fn value(&self, attribute: &Attribute) -> String {
257        self.value_of(attribute.raw())
258    }
259
260    fn value_of(&self, range: Range<usize>) -> String {
261        text::decode(self.encoding, self.bytes(range), text::Mode::Attribute)
262    }
263
264    /// 要素の、名前空間と接頭辞を除いた名前が合う属性
265    pub fn attribute<'e>(
266        &self,
267        element: &'e Element,
268        namespace: Option<&str>,
269        local: &[u8],
270    ) -> Option<&'e Attribute> {
271        element
272            .attributes
273            .iter()
274            .find(|attribute| self.is(&attribute.name, namespace, local))
275    }
276}