1use std::collections::HashMap;
8use std::fmt;
9
10use parsec_base::{Diagnostic, Span};
11
12pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
14pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
16
17pub(crate) const NONE: u32 = u32::MAX;
18pub(crate) const NS_XML: u32 = 1;
20pub(crate) const NS_XMLNS: u32 = 2;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
24pub struct NodeId(pub(crate) u32);
25
26impl NodeId {
27 pub fn index(self) -> usize {
29 self.0 as usize
30 }
31
32 pub fn from_index(index: usize) -> NodeId {
40 NodeId(u32::try_from(index).expect("a node index fits in a u32"))
41 }
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub(crate) struct Str {
47 pub start: u32,
48 pub len: u32,
49}
50
51impl Str {
52 pub fn end(self) -> u32 {
53 self.start + self.len
54 }
55}
56
57#[derive(Clone, Copy, Debug)]
58pub(crate) enum Data {
59 Document,
60 Doctype,
61 Element {
62 name: u32,
63 ns: u32,
64 attrs: u32,
65 attrs_len: u32,
66 },
67 Text(Str),
68 Cdata(Str),
69 Comment(Str),
70 Pi {
71 target: Str,
72 data: Str,
73 },
74 EntityRef(Str),
75}
76
77#[derive(Clone, Copy, Debug)]
78pub(crate) struct Node {
79 pub parent: u32,
80 pub first: u32,
81 pub last: u32,
82 pub prev: u32,
83 pub next: u32,
84 pub span: Span,
85 pub data: Data,
86}
87
88#[derive(Clone, Copy, Debug)]
89pub(crate) struct AttrData {
90 pub name: u32,
91 pub ns: u32,
92 pub value: Str,
93 pub span: Span,
94 pub specified: bool,
95}
96
97pub(crate) const PREFIX_XML: u32 = 1;
99pub(crate) const PREFIX_XMLNS: u32 = 2;
100
101#[derive(Debug)]
102pub(crate) struct QName {
103 pub qname: Box<str>,
104 pub colon: u32,
106 pub prefix: u32,
107}
108
109#[derive(Debug)]
112pub(crate) struct Names {
113 qnames: Vec<QName>,
114 qname_ids: HashMap<Box<str>, u32>,
115 prefix_ids: HashMap<Box<str>, u32>,
116 uris: Vec<Box<str>>,
117 uri_ids: HashMap<Box<str>, u32>,
118}
119
120const SCAN: usize = 16;
122
123const BUILTIN_URIS: [&str; 3] = ["", XML_NS, XMLNS_NS];
125const BUILTIN_PREFIXES: [&str; 3] = ["", "xml", "xmlns"];
126
127impl Names {
128 pub fn new() -> Names {
129 Names {
130 qnames: Vec::new(),
131 qname_ids: HashMap::new(),
132 prefix_ids: HashMap::new(),
133 uris: Vec::new(),
134 uri_ids: HashMap::new(),
135 }
136 }
137
138 pub fn get(&self, qname: &str) -> Option<u32> {
139 if self.qnames.len() <= SCAN {
142 return self
143 .qnames
144 .iter()
145 .position(|q| &*q.qname == qname)
146 .map(|i| i as u32);
147 }
148 self.qname_ids.get(qname).copied()
149 }
150
151 pub fn insert(&mut self, qname: &str, colon: u32) -> u32 {
153 let prefix = match colon {
154 NONE => 0,
155 c => self.prefix(&qname[..c as usize]),
156 };
157 let id = self.qnames.len() as u32;
158 self.qnames.push(QName {
159 qname: qname.into(),
160 colon,
161 prefix,
162 });
163 if self.qnames.len() == SCAN + 1 {
164 self.qname_ids = self
165 .qnames
166 .iter()
167 .enumerate()
168 .map(|(i, q)| (q.qname.clone(), i as u32))
169 .collect();
170 } else if self.qnames.len() > SCAN + 1 {
171 self.qname_ids.insert(qname.into(), id);
172 }
173 id
174 }
175
176 pub fn prefix(&mut self, prefix: &str) -> u32 {
177 if let Some(i) = BUILTIN_PREFIXES.iter().position(|&p| p == prefix) {
178 return i as u32;
179 }
180 if let Some(&id) = self.prefix_ids.get(prefix) {
181 return id;
182 }
183 let id = (BUILTIN_PREFIXES.len() + self.prefix_ids.len()) as u32;
184 self.prefix_ids.insert(prefix.into(), id);
185 id
186 }
187
188 pub fn uri(&mut self, uri: &str) -> u32 {
189 if let Some(i) = BUILTIN_URIS.iter().position(|&u| u == uri) {
190 return i as u32;
191 }
192 if let Some(&id) = self.uri_ids.get(uri) {
193 return id;
194 }
195 let id = (BUILTIN_URIS.len() + self.uris.len()) as u32;
196 self.uris.push(uri.into());
197 self.uri_ids.insert(uri.into(), id);
198 id
199 }
200
201 pub fn qname_info(&self, id: u32) -> &QName {
202 &self.qnames[id as usize]
203 }
204
205 pub fn qname_str(&self, id: u32) -> &str {
206 &self.qnames[id as usize].qname
207 }
208
209 pub fn local(&self, id: u32) -> &str {
211 let q = &self.qnames[id as usize];
212 match q.colon {
213 NONE => &q.qname,
214 c => &q.qname[c as usize + 1..],
215 }
216 }
217
218 pub fn uri_str(&self, id: u32) -> &str {
219 match BUILTIN_URIS.get(id as usize) {
220 Some(u) => u,
221 None => &self.uris[id as usize - BUILTIN_URIS.len()],
222 }
223 }
224
225 fn name(&self, qname: u32, ns: u32) -> Name<'_> {
226 let q = &self.qnames[qname as usize];
227 let (prefix, local) = match q.colon {
228 NONE => ("", &*q.qname),
229 c => (&q.qname[..c as usize], &q.qname[c as usize + 1..]),
230 };
231 Name {
232 qname: &q.qname,
233 prefix,
234 local,
235 namespace: self.uri_str(ns),
236 }
237 }
238}
239
240#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
242pub struct Name<'a> {
243 pub qname: &'a str,
245 pub prefix: &'a str,
247 pub local: &'a str,
249 pub namespace: &'a str,
251}
252
253impl fmt::Display for Name<'_> {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(self.qname)
256 }
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub struct Attribute<'a> {
262 pub name: Name<'a>,
263 pub value: &'a str,
267 pub span: Span,
270 pub specified: bool,
272}
273
274impl Attribute<'_> {
275 pub fn is_namespace_declaration(&self) -> bool {
277 self.name.namespace == XMLNS_NS
278 }
279}
280
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub enum NodeKind<'a> {
284 Document,
286 Doctype,
288 Element(Name<'a>),
289 Text(&'a str),
292 CData(&'a str),
294 Comment(&'a str),
295 ProcessingInstruction {
296 target: &'a str,
297 data: &'a str,
298 },
299 EntityRef(&'a str),
303}
304
305#[derive(Clone, Debug, PartialEq, Eq)]
307pub struct XmlDecl {
308 pub version: String,
309 pub encoding: Option<String>,
310 pub standalone: Option<bool>,
311 pub span: Span,
312}
313
314#[derive(Clone, Debug, PartialEq, Eq)]
316pub struct Doctype {
317 pub name: String,
319 pub public_id: Option<String>,
320 pub system_id: Option<String>,
322 pub internal_subset: Option<String>,
324 pub span: Span,
325}
326
327#[derive(Clone, Debug, PartialEq, Eq)]
329pub struct EntityDecl {
330 pub name: String,
331 pub parameter: bool,
333 pub value: Option<String>,
335 pub public_id: Option<String>,
336 pub system_id: Option<String>,
338 pub notation: Option<String>,
340 pub span: Span,
341}
342
343#[derive(Clone, Debug, PartialEq, Eq)]
345pub struct Notation {
346 pub name: String,
347 pub public_id: Option<String>,
348 pub system_id: Option<String>,
349 pub span: Span,
350}
351
352#[derive(Debug)]
358pub struct Document {
359 pub(crate) nodes: Vec<Node>,
360 pub(crate) attrs: Vec<AttrData>,
361 pub(crate) text: String,
362 pub(crate) names: Names,
363 pub(crate) decl: Option<XmlDecl>,
364 pub(crate) doctype: Option<Doctype>,
365 pub(crate) entities: Vec<EntityDecl>,
366 pub(crate) notations: Vec<Notation>,
367 pub(crate) id_attrs: HashMap<u32, u32>,
370 #[cfg(feature = "xpath")]
372 pub(crate) xpath_attrs: std::sync::OnceLock<crate::xpath_tree::Declared>,
373 pub(crate) warnings: Vec<Diagnostic>,
374 pub(crate) namespaces: bool,
375}
376
377impl Document {
378 pub(crate) fn new(namespaces: bool, len: usize) -> Document {
381 Document {
382 nodes: vec![Node {
383 parent: NONE,
384 first: NONE,
385 last: NONE,
386 prev: NONE,
387 next: NONE,
388 span: Span::default(),
389 data: Data::Document,
390 }],
391 attrs: Vec::new(),
392 text: String::with_capacity(len),
393 names: Names::new(),
394 decl: None,
395 doctype: None,
396 entities: Vec::new(),
397 notations: Vec::new(),
398 id_attrs: HashMap::new(),
399 #[cfg(feature = "xpath")]
400 xpath_attrs: std::sync::OnceLock::new(),
401 warnings: Vec::new(),
402 namespaces,
403 }
404 }
405
406 pub(crate) fn str(&self, s: Str) -> &str {
407 &self.text[s.start as usize..s.end() as usize]
408 }
409
410 pub(crate) fn append(&mut self, parent: u32, span: Span, data: Data) -> u32 {
412 let id = self.nodes.len() as u32;
413 let prev = self.nodes[parent as usize].last;
414 self.nodes.push(Node {
415 parent,
416 first: NONE,
417 last: NONE,
418 prev,
419 next: NONE,
420 span,
421 data,
422 });
423 if prev == NONE {
424 self.nodes[parent as usize].first = id;
425 } else {
426 self.nodes[prev as usize].next = id;
427 }
428 self.nodes[parent as usize].last = id;
429 id
430 }
431
432 pub fn root(&self) -> NodeId {
434 NodeId(0)
435 }
436
437 pub fn root_element(&self) -> NodeId {
439 self.children(self.root())
440 .find(|&n| matches!(self.nodes[n.index()].data, Data::Element { .. }))
441 .expect("a parsed document has a document element")
442 }
443
444 pub fn len(&self) -> usize {
446 self.nodes.len()
447 }
448
449 pub fn node(&self, index: usize) -> Option<NodeId> {
459 (index < self.nodes.len()).then_some(NodeId(index as u32))
460 }
461
462 pub fn is_empty(&self) -> bool {
464 false
465 }
466
467 pub fn kind(&self, node: NodeId) -> NodeKind<'_> {
468 match self.nodes[node.index()].data {
469 Data::Document => NodeKind::Document,
470 Data::Doctype => NodeKind::Doctype,
471 Data::Element { name, ns, .. } => NodeKind::Element(self.names.name(name, ns)),
472 Data::Text(s) => NodeKind::Text(self.str(s)),
473 Data::Cdata(s) => NodeKind::CData(self.str(s)),
474 Data::Comment(s) => NodeKind::Comment(self.str(s)),
475 Data::Pi { target, data } => NodeKind::ProcessingInstruction {
476 target: self.str(target),
477 data: self.str(data),
478 },
479 Data::EntityRef(s) => NodeKind::EntityRef(self.str(s)),
480 }
481 }
482
483 pub fn is_element(&self, node: NodeId) -> bool {
484 matches!(self.nodes[node.index()].data, Data::Element { .. })
485 }
486
487 pub fn name(&self, node: NodeId) -> Option<Name<'_>> {
489 match self.nodes[node.index()].data {
490 Data::Element { name, ns, .. } => Some(self.names.name(name, ns)),
491 _ => None,
492 }
493 }
494
495 pub fn span(&self, node: NodeId) -> Span {
498 self.nodes[node.index()].span
499 }
500
501 fn link(id: u32) -> Option<NodeId> {
502 (id != NONE).then_some(NodeId(id))
503 }
504
505 pub fn parent(&self, node: NodeId) -> Option<NodeId> {
506 Self::link(self.nodes[node.index()].parent)
507 }
508
509 pub fn first_child(&self, node: NodeId) -> Option<NodeId> {
510 Self::link(self.nodes[node.index()].first)
511 }
512
513 pub fn last_child(&self, node: NodeId) -> Option<NodeId> {
514 Self::link(self.nodes[node.index()].last)
515 }
516
517 pub fn next_sibling(&self, node: NodeId) -> Option<NodeId> {
518 Self::link(self.nodes[node.index()].next)
519 }
520
521 pub fn prev_sibling(&self, node: NodeId) -> Option<NodeId> {
522 Self::link(self.nodes[node.index()].prev)
523 }
524
525 pub fn children(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
526 std::iter::successors(self.first_child(node), |&n| self.next_sibling(n))
527 }
528
529 pub fn ancestors(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
531 std::iter::successors(self.parent(node), |&n| self.parent(n))
532 }
533
534 pub fn descendants(&self, node: NodeId) -> impl Iterator<Item = NodeId> + '_ {
536 let mut end = node;
539 let stop = loop {
540 if let Some(next) = self.next_sibling(end) {
541 break next.0;
542 }
543 match self.parent(end) {
544 Some(p) => end = p,
545 None => break self.nodes.len() as u32,
546 }
547 };
548 (node.0..stop).map(NodeId)
549 }
550
551 pub fn attributes(&self, node: NodeId) -> impl ExactSizeIterator<Item = Attribute<'_>> + '_ {
554 let range = match self.nodes[node.index()].data {
555 Data::Element {
556 attrs, attrs_len, ..
557 } => attrs as usize..(attrs + attrs_len) as usize,
558 _ => 0..0,
559 };
560 self.attrs[range].iter().map(|a| Attribute {
561 name: self.names.name(a.name, a.ns),
562 value: self.str(a.value),
563 span: a.span,
564 specified: a.specified,
565 })
566 }
567
568 pub fn attribute(&self, node: NodeId, namespace: &str, local: &str) -> Option<&str> {
571 self.attributes(node)
572 .find(|a| a.name.local == local && a.name.namespace == namespace)
573 .map(|a| a.value)
574 }
575
576 pub fn attribute_named(&self, node: NodeId, qname: &str) -> Option<&str> {
579 self.attributes(node)
580 .find(|a| a.name.qname == qname)
581 .map(|a| a.value)
582 }
583
584 pub fn text(&self, node: NodeId) -> String {
587 let mut out = String::new();
588 for n in self.descendants(node) {
589 if let Data::Text(s) | Data::Cdata(s) = self.nodes[n.index()].data {
590 out.push_str(self.str(s));
591 }
592 }
593 out
594 }
595
596 pub fn lookup_namespace(&self, node: NodeId, prefix: &str) -> Option<&str> {
599 if prefix == "xml" {
600 return Some(XML_NS);
601 }
602 for n in std::iter::once(node).chain(self.ancestors(node)) {
603 for a in self.attributes(n) {
604 if a.is_namespace_declaration()
605 && (a.name.local == prefix && a.name.prefix == "xmlns"
606 || prefix.is_empty() && a.name.qname == "xmlns")
607 {
608 return (!a.value.is_empty()).then_some(a.value);
609 }
610 }
611 }
612 None
613 }
614
615 fn inherited(&self, node: NodeId, local: &str) -> Option<&str> {
617 std::iter::once(node)
618 .chain(self.ancestors(node))
619 .find_map(|n| self.attribute(n, XML_NS, local))
620 }
621
622 pub fn xml_lang(&self, node: NodeId) -> Option<&str> {
624 self.inherited(node, "lang")
625 }
626
627 pub fn preserves_space(&self, node: NodeId) -> bool {
630 self.inherited(node, "space") == Some("preserve")
631 }
632
633 pub fn xml_decl(&self) -> Option<&XmlDecl> {
635 self.decl.as_ref()
636 }
637
638 pub fn doctype(&self) -> Option<&Doctype> {
639 self.doctype.as_ref()
640 }
641
642 pub fn entities(&self) -> &[EntityDecl] {
645 &self.entities
646 }
647
648 pub fn notations(&self) -> &[Notation] {
649 &self.notations
650 }
651
652 pub fn warnings(&self) -> &[Diagnostic] {
657 &self.warnings
658 }
659
660 pub fn namespaces(&self) -> bool {
662 self.namespaces
663 }
664}
665
666const _: () = {
668 const fn send_sync<T: Send + Sync>() {}
669 send_sync::<Document>();
670};
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675
676 #[test]
677 fn names_are_found_either_side_of_the_map() {
678 let mut names = Names::new();
679 let ids: Vec<u32> = (0..40)
680 .map(|i| names.insert(&format!("n{i}"), NONE))
681 .collect();
682 for (i, &id) in ids.iter().enumerate() {
683 assert_eq!(names.get(&format!("n{i}")), Some(id));
684 assert_eq!(names.qname_str(id), format!("n{i}"));
685 }
686 assert_eq!(names.get("n40"), None);
687 assert_eq!(
688 (names.uri(""), names.uri(XML_NS), names.uri(XMLNS_NS)),
689 (0, NS_XML, NS_XMLNS)
690 );
691 let u = names.uri("urn:x");
692 assert_eq!(
693 (names.uri("urn:x"), names.uri_str(u), names.uri_str(NS_XML)),
694 (u, "urn:x", XML_NS)
695 );
696 assert_eq!(
697 (
698 names.prefix("xml"),
699 names.prefix("xmlns"),
700 names.prefix("p")
701 ),
702 (PREFIX_XML, PREFIX_XMLNS, 3)
703 );
704 assert_eq!(names.prefix("p"), 3);
705 }
706}