lobzique 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/Cargo.lock +520 -0
  4. data/Cargo.toml +11 -0
  5. data/LICENSE-NOKOGIRI.md +15 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +144 -0
  8. data/crates/lobzique-core/Cargo.toml +14 -0
  9. data/crates/lobzique-core/src/css/mod.rs +127 -0
  10. data/crates/lobzique-core/src/css/parser.rs +805 -0
  11. data/crates/lobzique-core/src/css/tables.rs +282 -0
  12. data/crates/lobzique-core/src/css/tests.rs +476 -0
  13. data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
  14. data/crates/lobzique-core/src/css/translate.rs +806 -0
  15. data/crates/lobzique-core/src/css/write.rs +370 -0
  16. data/crates/lobzique-core/src/dom/attribute.rs +144 -0
  17. data/crates/lobzique-core/src/dom/check.rs +160 -0
  18. data/crates/lobzique-core/src/dom/copy.rs +229 -0
  19. data/crates/lobzique-core/src/dom/mod.rs +298 -0
  20. data/crates/lobzique-core/src/dom/namespace.rs +134 -0
  21. data/crates/lobzique-core/src/dom/node.rs +129 -0
  22. data/crates/lobzique-core/src/dom/path.rs +116 -0
  23. data/crates/lobzique-core/src/dom/reparent.rs +308 -0
  24. data/crates/lobzique-core/src/dom/tests.rs +1057 -0
  25. data/crates/lobzique-core/src/dom/text.rs +159 -0
  26. data/crates/lobzique-core/src/dom/tree.rs +446 -0
  27. data/crates/lobzique-core/src/html5/mod.rs +28 -0
  28. data/crates/lobzique-core/src/html5/parse.rs +838 -0
  29. data/crates/lobzique-core/src/html5/serialize.rs +181 -0
  30. data/crates/lobzique-core/src/html5/tests.rs +548 -0
  31. data/crates/lobzique-core/src/lib.rs +12 -0
  32. data/crates/lobzique-core/src/work.rs +26 -0
  33. data/crates/lobzique-core/src/xml/mod.rs +8 -0
  34. data/crates/lobzique-core/src/xml/serialize.rs +681 -0
  35. data/crates/lobzique-core/src/xml/tests.rs +174 -0
  36. data/crates/lobzique-core/src/xpath/ast.rs +415 -0
  37. data/crates/lobzique-core/src/xpath/chars.rs +139 -0
  38. data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
  39. data/crates/lobzique-core/src/xpath/mod.rs +118 -0
  40. data/crates/lobzique-core/src/xpath/parse.rs +729 -0
  41. data/crates/lobzique-core/src/xpath/tests.rs +921 -0
  42. data/ext/lobzique/Cargo.toml +22 -0
  43. data/ext/lobzique/build.rs +5 -0
  44. data/ext/lobzique/clippy.toml +15 -0
  45. data/ext/lobzique/extconf.rb +6 -0
  46. data/ext/lobzique/src/css/mod.rs +9 -0
  47. data/ext/lobzique/src/css/parser.rs +44 -0
  48. data/ext/lobzique/src/css/selector.rs +101 -0
  49. data/ext/lobzique/src/html4/document.rs +31 -0
  50. data/ext/lobzique/src/html4/mod.rs +7 -0
  51. data/ext/lobzique/src/html5/mod.rs +16 -0
  52. data/ext/lobzique/src/html5ever.rs +278 -0
  53. data/ext/lobzique/src/lib.rs +45 -0
  54. data/ext/lobzique/src/support.rs +156 -0
  55. data/ext/lobzique/src/xml/attr.rs +27 -0
  56. data/ext/lobzique/src/xml/cdata.rs +33 -0
  57. data/ext/lobzique/src/xml/comment.rs +34 -0
  58. data/ext/lobzique/src/xml/document.rs +199 -0
  59. data/ext/lobzique/src/xml/document_fragment.rs +27 -0
  60. data/ext/lobzique/src/xml/dtd.rs +37 -0
  61. data/ext/lobzique/src/xml/mod.rs +44 -0
  62. data/ext/lobzique/src/xml/namespace.rs +56 -0
  63. data/ext/lobzique/src/xml/node.rs +944 -0
  64. data/ext/lobzique/src/xml/node_set.rs +20 -0
  65. data/ext/lobzique/src/xml/syntax_error.rs +33 -0
  66. data/ext/lobzique/src/xml/text.rs +44 -0
  67. data/ext/lobzique/src/xml/xpath_context.rs +305 -0
  68. data/lib/lobzique/action_text.rb +29 -0
  69. data/lib/lobzique/class_resolver.rb +33 -0
  70. data/lib/lobzique/css/selector_cache.rb +36 -0
  71. data/lib/lobzique/css/syntax_error.rb +12 -0
  72. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  73. data/lib/lobzique/css.rb +57 -0
  74. data/lib/lobzique/extension.rb +31 -0
  75. data/lib/lobzique/html.rb +14 -0
  76. data/lib/lobzique/html4/document.rb +235 -0
  77. data/lib/lobzique/html4/document_fragment.rb +75 -0
  78. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  79. data/lib/lobzique/html4.rb +35 -0
  80. data/lib/lobzique/html5/document.rb +106 -0
  81. data/lib/lobzique/html5/document_fragment.rb +113 -0
  82. data/lib/lobzique/html5/node.rb +66 -0
  83. data/lib/lobzique/html5.rb +92 -0
  84. data/lib/lobzique/html5ever.rb +14 -0
  85. data/lib/lobzique/rails_dom_testing.rb +95 -0
  86. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  87. data/lib/lobzique/sanitizer/document.rb +14 -0
  88. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  89. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  90. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  91. data/lib/lobzique/sanitizer.rb +96 -0
  92. data/lib/lobzique/syntax_error.rb +8 -0
  93. data/lib/lobzique/version.rb +6 -0
  94. data/lib/lobzique/xml/attr.rb +23 -0
  95. data/lib/lobzique/xml/cdata.rb +13 -0
  96. data/lib/lobzique/xml/character_data.rb +11 -0
  97. data/lib/lobzique/xml/document.rb +149 -0
  98. data/lib/lobzique/xml/document_fragment.rb +109 -0
  99. data/lib/lobzique/xml/dtd.rb +28 -0
  100. data/lib/lobzique/xml/namespace.rb +19 -0
  101. data/lib/lobzique/xml/node/save_options.rb +52 -0
  102. data/lib/lobzique/xml/node.rb +629 -0
  103. data/lib/lobzique/xml/node_set.rb +329 -0
  104. data/lib/lobzique/xml/parse_options.rb +89 -0
  105. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  106. data/lib/lobzique/xml/pp/node.rb +73 -0
  107. data/lib/lobzique/xml/pp.rb +6 -0
  108. data/lib/lobzique/xml/searchable.rb +123 -0
  109. data/lib/lobzique/xml/syntax_error.rb +77 -0
  110. data/lib/lobzique/xml/text.rb +14 -0
  111. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  112. data/lib/lobzique/xml/xpath.rb +16 -0
  113. data/lib/lobzique/xml/xpath_context.rb +27 -0
  114. data/lib/lobzique/xml.rb +22 -0
  115. data/lib/lobzique.rb +15 -0
  116. metadata +177 -0
@@ -0,0 +1,174 @@
1
+ use super::save_options::*;
2
+ use super::*;
3
+ use crate::dom::{Doctype, Document, DocumentKind, NodeId, NodeKind};
4
+ use crate::html5::{parse_document, Options};
5
+
6
+ fn parse(input: &str) -> Document {
7
+ parse_document(input.as_bytes(), &Options::default())
8
+ .unwrap()
9
+ .0
10
+ }
11
+
12
+ fn string(document: &Document, id: NodeId, encoding: Option<&str>, options: u32) -> String {
13
+ let output = write(document, id, encoding.map(str::as_bytes), b" ", options).unwrap();
14
+ String::from_utf8(output.bytes).unwrap()
15
+ }
16
+
17
+ fn find(document: &Document, local: &str) -> NodeId {
18
+ document
19
+ .descendants(NodeId::DOCUMENT)
20
+ .find(
21
+ |&id| matches!(document.node_kind(id), NodeKind::Element(e) if &*e.name.local == local),
22
+ )
23
+ .unwrap()
24
+ }
25
+
26
+ #[test]
27
+ fn html_output_is_libxml2s_html_serializer() {
28
+ let html = parse("<p>");
29
+ let p = find(&html, "p");
30
+ assert_eq!(write(&html, p, None, b"", FORMAT), Err(HtmlUnsupported));
31
+ assert_eq!(
32
+ write(&html, p, None, b"", AS_XML | AS_HTML),
33
+ Err(HtmlUnsupported)
34
+ );
35
+ assert!(write(&html, p, None, b"", AS_XHTML | AS_HTML).is_ok());
36
+ assert_eq!(
37
+ write(&html, NodeId::DOCUMENT, None, b"", AS_XHTML | AS_HTML),
38
+ Err(HtmlUnsupported)
39
+ );
40
+ let xml = Document::new(DocumentKind::Xml);
41
+ assert!(write(&xml, NodeId::DOCUMENT, None, b"", 0).is_ok());
42
+ }
43
+
44
+ #[test]
45
+ fn text_without_an_encoding_is_ascii() {
46
+ let mut document = parse("<p title='\u{e9}\u{e9}'>\u{e9}\u{1f600}\u{1}\r\x7f</p>");
47
+ let p = find(&document, "p");
48
+ assert_eq!(
49
+ string(&document, p, None, AS_XML),
50
+ "<p title=\"&#xE9;&#xE9;\">&#xE9;&#x1F600;&#xFFFD;\n\x7f</p>"
51
+ );
52
+ document.set_encoding(Some(b"UTF-8".to_vec()));
53
+ // the parse turned CR into LF; attributes stay UTF-8 when the document has an encoding
54
+ assert_eq!(
55
+ string(&document, p, None, AS_XML),
56
+ "<p title=\"\u{e9}\u{e9}\">&#xE9;&#x1F600;&#xFFFD;\n\x7f</p>"
57
+ );
58
+ assert_eq!(
59
+ string(&document, p, Some("UTF-8"), AS_XML),
60
+ "<p title=\"\u{e9}\u{e9}\">\u{e9}\u{1f600}\u{1}\n\x7f</p>"
61
+ );
62
+ }
63
+
64
+ #[test]
65
+ fn malformed_utf8_is_a_replacement_character() {
66
+ let mut document = Document::new(DocumentKind::Xml);
67
+ let text = document.create_text(b"\xC3(\xED\xA0\x80\xEF\xBF\xBE\xF8\x90\x80\x80\xC3".to_vec());
68
+ assert_eq!(
69
+ string(&document, text, None, AS_XML),
70
+ "&#xFFFD;(&#xFFFD;&#xFFFD;&#xFFFD;&#xFFFD;&#x10000;&#xFFFD;"
71
+ );
72
+ let element = document.create_element_named("p");
73
+ document.set_attribute(element, "a", b"\xC3\xA9\xC3(\xC3".to_vec());
74
+ // a last byte is written as it is
75
+ let output = write(&document, element, None, b"", AS_XML).unwrap();
76
+ assert_eq!(output.bytes, b"<p a=\"&#xE9;&#xFFFD;(\xC3\"/>");
77
+ }
78
+
79
+ #[test]
80
+ fn a_documents_encoding_is_switched_to_only_with_a_declaration() {
81
+ let mut document = parse("<p>\u{e9}</p>");
82
+ document.set_encoding(Some(b"ISO-8859-1".to_vec()));
83
+ let output = write(&document, NodeId::DOCUMENT, None, b"", AS_XML).unwrap();
84
+ assert_eq!(output.encoding.as_deref(), Some(&b"ISO-8859-1"[..]));
85
+ assert!(output
86
+ .bytes
87
+ .ends_with("<p>\u{e9}</p></body></html>\n".as_bytes()));
88
+ let output = write(
89
+ &document,
90
+ NodeId::DOCUMENT,
91
+ None,
92
+ b"",
93
+ AS_XML | NO_DECLARATION,
94
+ )
95
+ .unwrap();
96
+ assert_eq!(output.encoding, None);
97
+ assert!(output.bytes.ends_with(b"<p>&#xE9;</p></body></html>\n"));
98
+ document.set_encoding(Some(b"utf8".to_vec()));
99
+ let output = write(&document, NodeId::DOCUMENT, None, b"", AS_XML).unwrap();
100
+ assert_eq!(output.encoding, None);
101
+ }
102
+
103
+ #[test]
104
+ fn indentation_stops_at_sixty_bytes() {
105
+ let document = parse(&"<div>".repeat(40));
106
+ let output = string(
107
+ &document,
108
+ NodeId::DOCUMENT,
109
+ None,
110
+ AS_XML | FORMAT | NO_DECLARATION,
111
+ );
112
+ let deepest = output
113
+ .lines()
114
+ .find(|line| line.ends_with("<div/>"))
115
+ .unwrap();
116
+ assert_eq!(deepest, format!("{}<div/>", " ".repeat(60)));
117
+ let long = "x".repeat(61);
118
+ let options = AS_XML | FORMAT | NO_DECLARATION;
119
+ let output = write(&document, NodeId::DOCUMENT, None, long.as_bytes(), options).unwrap();
120
+ assert!(!String::from_utf8(output.bytes).unwrap().contains('x'));
121
+ }
122
+
123
+ #[test]
124
+ fn doctypes_quote_as_libxml2_does() {
125
+ let mut document = Document::new(DocumentKind::Xml);
126
+ let doctype = document.create_doctype(Doctype {
127
+ name: b"html".to_vec(),
128
+ public_id: Some(b"a\"b".to_vec()),
129
+ system_id: None,
130
+ });
131
+ assert_eq!(
132
+ string(&document, doctype, None, AS_XML),
133
+ "<!DOCTYPE html PUBLIC 'a\"b' \"\">"
134
+ );
135
+ let doctype = document.create_doctype(Doctype {
136
+ name: b"html".to_vec(),
137
+ public_id: None,
138
+ system_id: Some(b"'\"".to_vec()),
139
+ });
140
+ assert_eq!(
141
+ string(&document, doctype, None, AS_XML),
142
+ "<!DOCTYPE html SYSTEM \"'&quot;\">"
143
+ );
144
+ }
145
+
146
+ #[test]
147
+ fn an_xhtml_doctype_gives_xhtml_rules_to_xml_output() {
148
+ let document =
149
+ parse("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"\"><p>x<br>");
150
+ let output = string(&document, NodeId::DOCUMENT, None, AS_XML | NO_DECLARATION);
151
+ assert!(output.contains("<p>x<br /></p>"), "{output}");
152
+ let output = string(
153
+ &document,
154
+ NodeId::DOCUMENT,
155
+ None,
156
+ AS_XML | NO_DECLARATION | NO_XHTML,
157
+ );
158
+ assert!(output.contains("<p>x<br/></p>"), "{output}");
159
+ }
160
+
161
+ #[test]
162
+ fn deep_trees_cost_no_stack() {
163
+ let depth = if cfg!(miri) { 100 } else { 5_000 };
164
+ let serialize = move || {
165
+ let input = "<div>".repeat(depth);
166
+ let (document, _) = parse_document(input.as_bytes(), &Options::default()).unwrap();
167
+ let xml = write(&document, NodeId::DOCUMENT, None, b"", AS_XML).unwrap();
168
+ let xhtml = write(&document, NodeId::DOCUMENT, None, b"", AS_XHTML).unwrap();
169
+ (xml.bytes.len(), xhtml.bytes.len())
170
+ };
171
+ let small_stack = std::thread::Builder::new().stack_size(256 * 1024);
172
+ let lengths = small_stack.spawn(serialize).unwrap().join().unwrap();
173
+ assert!(lengths.0 > 11 * depth && lengths.1 > 11 * depth);
174
+ }
@@ -0,0 +1,415 @@
1
+ //! XPath expressions as trees. Operators of one precedence take lists,
2
+ //! so a long chain of them uses no extra stack. Only brackets nest,
3
+ //! and the parser limits their depth.
4
+
5
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6
+ pub enum Axis {
7
+ Ancestor,
8
+ AncestorOrSelf,
9
+ Attribute,
10
+ Child,
11
+ Descendant,
12
+ DescendantOrSelf,
13
+ Following,
14
+ FollowingSibling,
15
+ Parent,
16
+ Preceding,
17
+ PrecedingSibling,
18
+ Self_,
19
+ }
20
+
21
+ impl Axis {
22
+ /// Reverse axes number positions from the context node backwards.
23
+ pub fn is_reverse(self) -> bool {
24
+ matches!(
25
+ self,
26
+ Axis::Ancestor | Axis::AncestorOrSelf | Axis::Preceding | Axis::PrecedingSibling
27
+ )
28
+ }
29
+ }
30
+
31
+ #[derive(Clone, Debug, PartialEq, Eq)]
32
+ pub struct QName {
33
+ pub prefix: Option<String>,
34
+ pub local: String,
35
+ }
36
+
37
+ #[derive(Clone, Debug, PartialEq, Eq)]
38
+ pub enum NodeTest {
39
+ Node,
40
+ /// `text()`. CDATA sections pass it too.
41
+ Text,
42
+ Comment,
43
+ /// `*`: any node of the principal type of the axis.
44
+ Any,
45
+ /// `name` or `prefix:name`. No prefix means no namespace.
46
+ Name(QName),
47
+ /// `*:name`, the wildcard namespace of libxml2 as Nokogiri patches
48
+ /// it: an element with the local name in any namespace or in none.
49
+ LocalName(String),
50
+ /// `prefix:*`: any node of the principal type of the axis in the namespace.
51
+ AnyIn(String),
52
+ /// `processing-instruction()`. With a literal, only those with that target.
53
+ ProcessingInstruction(Option<Vec<u8>>),
54
+ }
55
+
56
+ #[derive(Clone, Debug)]
57
+ pub struct Step {
58
+ pub axis: Axis,
59
+ pub test: NodeTest,
60
+ pub predicates: Vec<Expr>,
61
+ }
62
+
63
+ impl Step {
64
+ pub fn new(axis: Axis, test: NodeTest) -> Step {
65
+ Step {
66
+ axis,
67
+ test,
68
+ predicates: Vec::new(),
69
+ }
70
+ }
71
+ }
72
+
73
+ #[derive(Clone, Debug)]
74
+ pub struct Path {
75
+ /// Starts at the document node, not the context node.
76
+ pub absolute: bool,
77
+ pub steps: Vec<Step>,
78
+ }
79
+
80
+ impl Path {
81
+ pub fn relative(steps: Vec<Step>) -> Path {
82
+ Path {
83
+ absolute: false,
84
+ steps,
85
+ }
86
+ }
87
+
88
+ pub fn context_node() -> Path {
89
+ Path::relative(vec![Step::new(Axis::Self_, NodeTest::Node)])
90
+ }
91
+ }
92
+
93
+ /// The steps after `descendant-or-self::node()` that merge
94
+ /// into it. From any context node except a document fragment, both rules find
95
+ /// the same nodes. A fragment differs because `node()` does not pass it.
96
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
97
+ pub(super) enum Merge {
98
+ /// A child step whose predicates do not read the position. CSS never
99
+ /// searches from a fragment: Nokogiri searches its children instead.
100
+ UnlessPositional,
101
+ /// libxml2's `xmlXPathOptimizeExpression`, for XPath strings: a step
102
+ /// without predicates on the child, descendant, self or
103
+ /// descendant-or-self axis.
104
+ WithoutPredicates,
105
+ }
106
+
107
+ impl Merge {
108
+ fn axis(self, next: &Step) -> Option<Axis> {
109
+ match self {
110
+ Merge::UnlessPositional => (next.axis == Axis::Child
111
+ && !next.predicates.iter().any(Expr::is_positional))
112
+ .then_some(Axis::Descendant),
113
+ Merge::WithoutPredicates if !next.predicates.is_empty() => None,
114
+ Merge::WithoutPredicates => match next.axis {
115
+ Axis::Child | Axis::Descendant => Some(Axis::Descendant),
116
+ Axis::Self_ | Axis::DescendantOrSelf => Some(Axis::DescendantOrSelf),
117
+ _ => None,
118
+ },
119
+ }
120
+ }
121
+ }
122
+
123
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
124
+ pub enum Comparison {
125
+ Equal,
126
+ NotEqual,
127
+ Less,
128
+ LessOrEqual,
129
+ Greater,
130
+ GreaterOrEqual,
131
+ }
132
+
133
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
134
+ pub enum Arithmetic {
135
+ Add,
136
+ Subtract,
137
+ Multiply,
138
+ Divide,
139
+ Modulo,
140
+ }
141
+
142
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
143
+ pub enum Operator {
144
+ Compare(Comparison),
145
+ Arithmetic(Arithmetic),
146
+ }
147
+
148
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
149
+ pub enum Function {
150
+ Last,
151
+ Position,
152
+ Count,
153
+ Id,
154
+ LocalName,
155
+ NamespaceUri,
156
+ Name,
157
+ String,
158
+ Concat,
159
+ StartsWith,
160
+ Contains,
161
+ SubstringBefore,
162
+ SubstringAfter,
163
+ Substring,
164
+ StringLength,
165
+ NormalizeSpace,
166
+ Translate,
167
+ Boolean,
168
+ Not,
169
+ True,
170
+ False,
171
+ Lang,
172
+ Number,
173
+ Sum,
174
+ Floor,
175
+ Ceiling,
176
+ Round,
177
+ /// Not XPath 1.0. The result of the `substring(…)=…` test that Nokogiri
178
+ /// uses for `[a$=b]`.
179
+ EndsWith,
180
+ /// Nokogiri's `nokogiri-builtin:css-class`
181
+ CssClass,
182
+ /// Nokogiri's `nokogiri-builtin:local-name-is`
183
+ LocalNameIs,
184
+ /// `escape-uri` of libxml2, in the XQuery functions namespace.
185
+ EscapeUri,
186
+ }
187
+
188
+ impl Function {
189
+ pub fn named(name: &str) -> Option<Function> {
190
+ use Function::*;
191
+ Some(match name {
192
+ "last" => Last,
193
+ "position" => Position,
194
+ "count" => Count,
195
+ "id" => Id,
196
+ "local-name" => LocalName,
197
+ "namespace-uri" => NamespaceUri,
198
+ "name" => Name,
199
+ "string" => String,
200
+ "concat" => Concat,
201
+ "starts-with" => StartsWith,
202
+ "contains" => Contains,
203
+ "substring-before" => SubstringBefore,
204
+ "substring-after" => SubstringAfter,
205
+ "substring" => Substring,
206
+ "string-length" => StringLength,
207
+ "normalize-space" => NormalizeSpace,
208
+ "translate" => Translate,
209
+ "boolean" => Boolean,
210
+ "not" => Not,
211
+ "true" => True,
212
+ "false" => False,
213
+ "lang" => Lang,
214
+ "number" => Number,
215
+ "sum" => Sum,
216
+ "floor" => Floor,
217
+ "ceiling" => Ceiling,
218
+ "round" => Round,
219
+ _ => return None,
220
+ })
221
+ }
222
+
223
+ pub fn in_namespace(href: &str, local: &str) -> Option<Function> {
224
+ match (href, local) {
225
+ (super::NOKOGIRI_BUILTIN_URI, "css-class") => Some(Function::CssClass),
226
+ (super::NOKOGIRI_BUILTIN_URI, "local-name-is") => Some(Function::LocalNameIs),
227
+ (super::XQUERY_FUNCTIONS_URI, "escape-uri") => Some(Function::EscapeUri),
228
+ _ => None,
229
+ }
230
+ }
231
+
232
+ /// Whether it can return a number. A predicate compares a number
233
+ /// with the position.
234
+ fn may_be_number(self) -> bool {
235
+ use Function::*;
236
+ matches!(
237
+ self,
238
+ Last | Position | Count | StringLength | Number | Sum | Floor | Ceiling | Round
239
+ )
240
+ }
241
+ }
242
+
243
+ /// A filter expression: a primary expression, predicates that number its
244
+ /// nodes in document order, and a path from each node that passes.
245
+ #[derive(Clone, Debug)]
246
+ pub struct Filter {
247
+ pub primary: Expr,
248
+ pub predicates: Vec<Expr>,
249
+ pub steps: Vec<Step>,
250
+ }
251
+
252
+ #[derive(Clone, Debug)]
253
+ pub enum Expr {
254
+ Or(Vec<Expr>),
255
+ And(Vec<Expr>),
256
+ Operation(Box<Expr>, Vec<(Operator, Expr)>),
257
+ Negate(Box<Expr>),
258
+ Number(f64),
259
+ Literal(Vec<u8>),
260
+ /// `$name`: a variable that Nokogiri binds as a string.
261
+ Variable(QName),
262
+ Path(Path),
263
+ Filter(Box<Filter>),
264
+ Union(Vec<Expr>),
265
+ Call(Function, Vec<Expr>),
266
+ /// A function outside XPath 1.0, for example `nokogiri:name(…)`.
267
+ /// It is a namespaced builtin, or the handler of the caller answers
268
+ /// it. `site` numbers the call in its query, which names it.
269
+ Custom {
270
+ site: usize,
271
+ arguments: Vec<Expr>,
272
+ },
273
+ }
274
+
275
+ impl Expr {
276
+ pub fn compare(comparison: Comparison, left: Expr, right: Expr) -> Expr {
277
+ Expr::Operation(Box::new(left), vec![(Operator::Compare(comparison), right)])
278
+ }
279
+
280
+ pub fn arithmetic(operator: Arithmetic, left: Expr, right: Expr) -> Expr {
281
+ Expr::Operation(
282
+ Box::new(left),
283
+ vec![(Operator::Arithmetic(operator), right)],
284
+ )
285
+ }
286
+
287
+ /// The expressions that it evaluates in its own context: all operands
288
+ /// except the predicates and steps of paths and filters, which start
289
+ /// their own.
290
+ fn operands(&self) -> Box<dyn Iterator<Item = &Expr> + '_> {
291
+ match self {
292
+ Expr::Or(list) | Expr::And(list) | Expr::Union(list) => Box::new(list.iter()),
293
+ Expr::Operation(first, rest) => {
294
+ Box::new(std::iter::once(&**first).chain(rest.iter().map(|(_, e)| e)))
295
+ }
296
+ Expr::Negate(expr) => Box::new(std::iter::once(&**expr)),
297
+ Expr::Filter(filter) => Box::new(std::iter::once(&filter.primary)),
298
+ Expr::Call(_, arguments) | Expr::Custom { arguments, .. } => Box::new(arguments.iter()),
299
+ Expr::Number(_) | Expr::Literal(_) | Expr::Variable(_) | Expr::Path(_) => {
300
+ Box::new(std::iter::empty())
301
+ }
302
+ }
303
+ }
304
+
305
+ fn operands_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expr> + '_> {
306
+ match self {
307
+ Expr::Or(list) | Expr::And(list) | Expr::Union(list) => Box::new(list.iter_mut()),
308
+ Expr::Operation(first, rest) => {
309
+ Box::new(std::iter::once(&mut **first).chain(rest.iter_mut().map(|(_, e)| e)))
310
+ }
311
+ Expr::Negate(expr) => Box::new(std::iter::once(&mut **expr)),
312
+ Expr::Filter(filter) => Box::new(std::iter::once(&mut filter.primary)),
313
+ Expr::Call(_, arguments) | Expr::Custom { arguments, .. } => {
314
+ Box::new(arguments.iter_mut())
315
+ }
316
+ Expr::Number(_) | Expr::Literal(_) | Expr::Variable(_) | Expr::Path(_) => {
317
+ Box::new(std::iter::empty())
318
+ }
319
+ }
320
+ }
321
+
322
+ pub(super) fn for_each_step(&self, each: &mut dyn FnMut(&Step)) {
323
+ let walk = |steps: &[Step], each: &mut dyn FnMut(&Step)| {
324
+ for step in steps {
325
+ each(step);
326
+ for predicate in &step.predicates {
327
+ predicate.for_each_step(each);
328
+ }
329
+ }
330
+ };
331
+ match self {
332
+ Expr::Path(path) => walk(&path.steps, each),
333
+ Expr::Filter(filter) => {
334
+ filter.primary.for_each_step(each);
335
+ for predicate in &filter.predicates {
336
+ predicate.for_each_step(each);
337
+ }
338
+ walk(&filter.steps, each);
339
+ }
340
+ expr => expr.operands().for_each(|e| e.for_each_step(each)),
341
+ }
342
+ }
343
+
344
+ /// Rewrites `descendant-or-self::node()/child::x[p]`, which `//x[p]` stands
345
+ /// for, as `descendant::x[p]`. It finds the same nodes without visiting
346
+ /// each one twice.
347
+ pub(super) fn merge_descendant_steps(&mut self, merge: Merge) {
348
+ let merge_path = |path: &mut Vec<Step>| {
349
+ let mut merged = Vec::with_capacity(path.len());
350
+ let mut steps = std::mem::take(path).into_iter().peekable();
351
+ while let Some(mut step) = steps.next() {
352
+ for predicate in &mut step.predicates {
353
+ predicate.merge_descendant_steps(merge);
354
+ }
355
+ let mergeable = step.axis == Axis::DescendantOrSelf
356
+ && step.test == NodeTest::Node
357
+ && step.predicates.is_empty();
358
+ let axis = match steps.peek() {
359
+ Some(next) if mergeable => merge.axis(next),
360
+ _ => None,
361
+ };
362
+ match axis {
363
+ Some(axis) => {
364
+ let mut next = steps.next().expect("peeked");
365
+ for predicate in &mut next.predicates {
366
+ predicate.merge_descendant_steps(merge);
367
+ }
368
+ next.axis = axis;
369
+ merged.push(next);
370
+ }
371
+ None => merged.push(step),
372
+ }
373
+ }
374
+ *path = merged;
375
+ };
376
+ match self {
377
+ Expr::Path(path) => merge_path(&mut path.steps),
378
+ Expr::Filter(filter) => {
379
+ filter.primary.merge_descendant_steps(merge);
380
+ for predicate in &mut filter.predicates {
381
+ predicate.merge_descendant_steps(merge);
382
+ }
383
+ merge_path(&mut filter.steps);
384
+ }
385
+ expr => expr
386
+ .operands_mut()
387
+ .for_each(|e| e.merge_descendant_steps(merge)),
388
+ }
389
+ }
390
+
391
+ /// Whether the answer of a predicate can depend on the position of the node
392
+ /// it tests. A number tests the position itself, and `position()`
393
+ /// and `last()` read it. Paths start their own contexts.
394
+ pub fn is_positional(&self) -> bool {
395
+ self.may_be_number() || self.reads_position()
396
+ }
397
+
398
+ fn may_be_number(&self) -> bool {
399
+ match self {
400
+ Expr::Number(_) | Expr::Negate(_) | Expr::Custom { .. } => true,
401
+ Expr::Operation(_, rest) => {
402
+ matches!(rest.last(), Some((Operator::Arithmetic(_), _)))
403
+ }
404
+ Expr::Call(function, _) => function.may_be_number(),
405
+ _ => false,
406
+ }
407
+ }
408
+
409
+ fn reads_position(&self) -> bool {
410
+ match self {
411
+ Expr::Call(Function::Position | Function::Last, _) => true,
412
+ expr => expr.operands().any(Expr::reads_position),
413
+ }
414
+ }
415
+ }