Skip to main content

zumen_xml/
lib.rs

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