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,20 @@
1
+ //! `XML::NodeSet`. Here it is Ruby over an Array (ARCHITECTURE.md, departures).
2
+ //! Natively there is only the wrapping of a result.
3
+
4
+ use super::node::{wrap_all, Node};
5
+ use crate::XML;
6
+ use lobzique_core::dom::NodeId;
7
+ use magnus::{prelude::*, typed_data::Obj, value::Lazy, Error, RClass, Ruby, Value};
8
+
9
+ pub static NODE_SET: Lazy<RClass> = Lazy::new(|ruby| {
10
+ ruby.get_inner(&XML)
11
+ .const_get("NodeSet")
12
+ .expect("lib/lobzique/xml/node_set.rb defines XML::NodeSet")
13
+ });
14
+
15
+ /// A NodeSet of the node objects for `ids`: `noko_xml_node_set_wrap`,
16
+ /// which is `NodeSet.wrap` in Ruby here.
17
+ pub fn wrap(ruby: &Ruby, document: Obj<Node>, ids: Vec<NodeId>) -> Result<Value, Error> {
18
+ let nodes = wrap_all(ruby, document, ids)?;
19
+ ruby.get_inner(&NODE_SET).funcall("wrap", (document, nodes))
20
+ }
@@ -0,0 +1,33 @@
1
+ //! `XML::SyntaxError` and its subclasses, made as `noko_xml_syntax_error__wrap`
2
+ //! of Nokogiri makes them from the `xmlError` of libxml2.
3
+
4
+ use super::node::utf8_string;
5
+ use magnus::{prelude::*, Error, Exception, RClass, RObject, Ruby, Value};
6
+
7
+ /// The parts of the `xmlError` of libxml2 that an error here has.
8
+ pub struct XmlError<'a> {
9
+ pub domain: i32,
10
+ pub code: i32,
11
+ pub message: &'a str,
12
+ pub level: i32,
13
+ pub file: Value,
14
+ pub line: u64,
15
+ pub str1: Option<&'a [u8]>,
16
+ }
17
+
18
+ /// An instance of `class`, with every instance variable Nokogiri sets.
19
+ pub fn wrap(ruby: &Ruby, class: RClass, error: &XmlError) -> Result<Exception, Error> {
20
+ let exception: Value = class.new_instance((utf8_string(ruby, error.message),))?;
21
+ let object = RObject::from_value(exception).expect("an exception is an object");
22
+ object.ivar_set("@domain", error.domain)?;
23
+ object.ivar_set("@code", error.code)?;
24
+ object.ivar_set("@level", error.level)?;
25
+ object.ivar_set("@file", error.file)?;
26
+ object.ivar_set("@line", error.line)?;
27
+ object.ivar_set("@str1", error.str1.map(|str1| utf8_string(ruby, str1)))?;
28
+ object.ivar_set("@str2", ruby.qnil())?;
29
+ object.ivar_set("@str3", ruby.qnil())?;
30
+ object.ivar_set("@int1", 0)?;
31
+ object.ivar_set("@column", 0)?;
32
+ Ok(Exception::from_value(exception).expect("an instance of an exception class"))
33
+ }
@@ -0,0 +1,44 @@
1
+ use super::node::{document_for_new_node, finish_new, NODE};
2
+ use super::{document, CHARACTER_DATA};
3
+ use crate::support::{c_string, check_string, obj_class};
4
+ use crate::XML;
5
+ use magnus::{method, prelude::*, value::Lazy, Error, RClass, Ruby, Value};
6
+
7
+ pub static TEXT: Lazy<RClass> = Lazy::new(|ruby| {
8
+ ruby.get_inner(&XML)
9
+ .define_class("Text", ruby.get_inner(&CHARACTER_DATA))
10
+ .unwrap()
11
+ });
12
+
13
+ /// `Text.new(string, document, *rest)`.
14
+ fn new(ruby: &Ruby, class: RClass, args: &[Value]) -> Result<Value, Error> {
15
+ ruby.check_arity(args.len(), 2..)?;
16
+ check_string(ruby, args[0])?;
17
+ let document = expect_document_or_node(ruby, args[1], "second")?;
18
+ let document = document_for_new_node(
19
+ ruby,
20
+ document,
21
+ "Passing a Node as the second parameter to Text.new is deprecated. Please pass a Document instead.",
22
+ )?;
23
+ let content = c_string(args[0])?;
24
+ let id = document::with_arena_mut(ruby, document, |arena| arena.create_text(content))?;
25
+ finish_new(ruby, document, id, class, args)
26
+ }
27
+
28
+ pub fn expect_document_or_node(ruby: &Ruby, value: Value, position: &str) -> Result<Value, Error> {
29
+ if value.is_kind_of(ruby.get_inner(&NODE)) {
30
+ return Ok(value);
31
+ }
32
+ let message = format!(
33
+ "expected {position} parameter to be a {}, received {}",
34
+ ruby.get_inner(&document::DOCUMENT).inspect(),
35
+ obj_class(value).inspect()
36
+ );
37
+ Err(Error::new(ruby.exception_type_error(), message))
38
+ }
39
+
40
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
41
+ let class = ruby.get_inner(&TEXT);
42
+ class.define_singleton_method("new", method!(new, -1))?;
43
+ Ok(())
44
+ }
@@ -0,0 +1,305 @@
1
+ //! `XML::XPathContext`: a context node, namespace and variable bindings,
2
+ //! and `evaluate`. It evaluates the selectors that `Searchable` compiles
3
+ //! from CSS, and XPath strings (plan.md decision 2).
4
+
5
+ use super::document;
6
+ use super::node::{utf8_string, Node, NODE};
7
+ use super::node_set::{self, NODE_SET};
8
+ use super::syntax_error::{self, XmlError};
9
+ use crate::css::selector::Selector;
10
+ use crate::support::{apply, c_string, obj_class, optional_arg, warn_deprecated};
11
+ use crate::XML;
12
+ use lobzique_core::dom::NodeId;
13
+ use lobzique_core::xpath::{self, Answer, Call, Outcome, ParseError, Query};
14
+ use magnus::{
15
+ function, gc, method, prelude::*, rb_sys::AsRawValue, typed_data::Obj, value::Lazy,
16
+ value::Opaque, DataTypeFunctions, Error, Exception, Float, Integer, IntoValue, RArray, RClass,
17
+ RString, Ruby, TypedData, Value,
18
+ };
19
+ use std::borrow::Cow;
20
+ use std::cell::{Cell, RefCell};
21
+ use std::collections::{HashMap, HashSet};
22
+
23
+ pub static XPATH_CONTEXT: Lazy<RClass> = Lazy::new(|ruby| {
24
+ ruby.get_inner(&XML)
25
+ .define_class("XPathContext", ruby.class_object())
26
+ .unwrap()
27
+ });
28
+
29
+ #[derive(TypedData)]
30
+ #[magnus(class = "Lobzique::XML::XPathContext", mark, compact, free_immediately)]
31
+ pub struct XPathContext {
32
+ /// The object of the context node. It follows the node across documents.
33
+ node: Cell<Opaque<Value>>,
34
+ namespaces: RefCell<HashMap<String, String>>,
35
+ variables: RefCell<HashMap<String, Vec<u8>>>,
36
+ }
37
+
38
+ impl DataTypeFunctions for XPathContext {
39
+ fn mark(&self, marker: &gc::Marker) {
40
+ marker.mark_movable(self.node.get());
41
+ }
42
+
43
+ fn compact(&self, compactor: &gc::Compactor) {
44
+ self.node.set(compactor.location(self.node.get()));
45
+ }
46
+ }
47
+
48
+ fn new(ruby: &Ruby, node: Value) -> Result<XPathContext, Error> {
49
+ expect_node(ruby, node)?;
50
+ Ok(XPathContext {
51
+ node: Cell::new(node.into()),
52
+ namespaces: RefCell::new(HashMap::new()),
53
+ variables: RefCell::new(HashMap::new()),
54
+ })
55
+ }
56
+
57
+ fn expect_node(ruby: &Ruby, node: Value) -> Result<(), Error> {
58
+ let node_class = ruby.get_inner(&NODE);
59
+ if node.is_kind_of(node_class) {
60
+ return Ok(());
61
+ }
62
+ let message = format!(
63
+ "expected a {}, received {}",
64
+ node_class.inspect(),
65
+ obj_class(node).inspect()
66
+ );
67
+ Err(Error::new(ruby.exception_type_error(), message))
68
+ }
69
+
70
+ impl XPathContext {
71
+ fn set_node(ruby: &Ruby, rb_self: &Self, node: Value) -> Result<Value, Error> {
72
+ expect_node(ruby, node)?;
73
+ rb_self.node.set(node.into());
74
+ Ok(node)
75
+ }
76
+
77
+ /// `register_ns(prefix, uri)`. A `nil` URI unbinds the prefix.
78
+ fn register_ns(rb_self: Obj<Self>, prefix: Value, uri: Value) -> Result<Obj<Self>, Error> {
79
+ let prefix = String::from_utf8_lossy(&c_string(prefix)?).into_owned();
80
+ let mut namespaces = rb_self.namespaces.borrow_mut();
81
+ if uri.is_nil() {
82
+ namespaces.remove(&prefix);
83
+ } else {
84
+ let uri = String::from_utf8_lossy(&c_string(uri)?).into_owned();
85
+ namespaces.insert(prefix, uri);
86
+ }
87
+ drop(namespaces);
88
+ Ok(rb_self)
89
+ }
90
+
91
+ /// `register_variable(name, value)`: a string variable, or none for `nil`.
92
+ fn register_variable(
93
+ rb_self: Obj<Self>,
94
+ name: Value,
95
+ value: Value,
96
+ ) -> Result<Obj<Self>, Error> {
97
+ let name = String::from_utf8_lossy(&c_string(name)?).into_owned();
98
+ let mut variables = rb_self.variables.borrow_mut();
99
+ if value.is_nil() {
100
+ variables.remove(&name);
101
+ } else {
102
+ variables.insert(name, c_string(value)?);
103
+ }
104
+ drop(variables);
105
+ Ok(rb_self)
106
+ }
107
+
108
+ /// `evaluate(expression, handler = nil)`. Custom functions are methods
109
+ /// of the handler, called with the arguments that libxml2 would pass. They
110
+ /// run between evaluations, not during one: each evaluation records
111
+ /// the calls that it has no result for, and runs again after they are made
112
+ /// (ARCHITECTURE.md, departures).
113
+ fn evaluate(ruby: &Ruby, rb_self: &Self, args: &[Value]) -> Result<Value, Error> {
114
+ ruby.check_arity(args.len(), 1..=2)?;
115
+ let handler = optional_arg(ruby, args, 1);
116
+ let (selector, expression, parsed);
117
+ let (query, rule): (&Query, &[u8]) = match Obj::<Selector>::try_convert(args[0]) {
118
+ Ok(compiled) => {
119
+ selector = compiled;
120
+ let rule = selector.rule.as_bytes();
121
+ match &selector.compiled.query {
122
+ Ok(query) => (query, rule),
123
+ Err(error) => return Err(xpath_error(ruby, *error, rule)),
124
+ }
125
+ }
126
+ Err(_) => {
127
+ expression = c_string(args[0])?;
128
+ parsed = xpath::parse(&expression).map_err(|error| match error {
129
+ ParseError::Syntax(error) => xpath_error(ruby, error, &expression),
130
+ ParseError::Unsupported(construct) => {
131
+ unsupported_error(ruby, &construct, &expression)
132
+ }
133
+ })?;
134
+ (&parsed, &expression)
135
+ }
136
+ };
137
+ let node = <&Node>::try_convert(ruby.get_inner(rb_self.node.get()))?;
138
+ let (document, id) = (node.document(ruby)?, node.id(ruby)?);
139
+ let namespaces = rb_self.namespaces.borrow().clone();
140
+ let variables = rb_self.variables.borrow().clone();
141
+ let mut answers = HashMap::new();
142
+ let mut warned = HashSet::new();
143
+ loop {
144
+ let outcome = document::with_arena(ruby, document, |arena| {
145
+ xpath::evaluate(arena, query, id, &namespaces, &variables, &answers)
146
+ })?
147
+ .map_err(|error| xpath_error(ruby, error, rule))?;
148
+ match outcome {
149
+ Outcome::Value(value) => return to_ruby(ruby, document, value),
150
+ Outcome::Calls(calls) => {
151
+ for call in calls {
152
+ let handler = Handler {
153
+ object: handler,
154
+ warned: &mut warned,
155
+ };
156
+ let answer = call_handler(ruby, document, handler, query, &call)?;
157
+ answers.insert(call, answer);
158
+ }
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ /// The object whose methods are the custom functions, and the call sites
166
+ /// that it has warned about.
167
+ struct Handler<'a> {
168
+ object: Value,
169
+ warned: &'a mut HashSet<usize>,
170
+ }
171
+
172
+ /// `_noko_xml_xpath_context_handler_lookup` of Nokogiri, then
173
+ /// `Nokogiri_marshal_xpath_funcall_and_return_values`.
174
+ fn call_handler(
175
+ ruby: &Ruby,
176
+ document: Obj<Node>,
177
+ handler: Handler,
178
+ query: &Query,
179
+ call: &Call,
180
+ ) -> Result<Answer, Error> {
181
+ let function = query.function(call.site);
182
+ let name = function.local.as_str();
183
+ // libxml2 raises this only if it reaches the call.
184
+ if handler.object.is_nil() || !handler.object.respond_to(name, false)? {
185
+ return Ok(Err(xpath::Error::UnregisteredFunction));
186
+ }
187
+ // libxml2 looks up a function once for each call site.
188
+ if function.prefix.is_none() && handler.warned.insert(call.site) {
189
+ warn_deprecated(&format!(
190
+ "A custom XPath or CSS handler function named '{name}' is being invoked without a namespace. \
191
+ Please update your query to reference this function as 'nokogiri:{name}'. \
192
+ Invoking custom handler functions without a namespace is deprecated and will become an error in Nokogiri v1.17.0."
193
+ ))?;
194
+ }
195
+ let arguments = ruby.ary_new_capa(call.arguments.len());
196
+ for argument in &call.arguments {
197
+ arguments.push(to_ruby(ruby, document, argument.clone())?)?;
198
+ }
199
+ let result = apply(ruby, handler.object, name, arguments)?;
200
+ if result.is_nil() {
201
+ return Ok(Err(xpath::Error::StackUsage));
202
+ }
203
+ if Float::from_value(result).is_some() || Integer::from_value(result).is_some() {
204
+ return Ok(Ok(xpath::Value::Number(f64::try_convert(result)?)));
205
+ }
206
+ if RString::from_value(result).is_some() {
207
+ return Ok(Ok(xpath::Value::String(Cow::Owned(c_string(result)?))));
208
+ }
209
+ if result.is_kind_of(ruby.class_true_class()) || result.is_kind_of(ruby.class_false_class()) {
210
+ return Ok(Ok(xpath::Value::Boolean(result.to_bool())));
211
+ }
212
+ let node_set_class = ruby.get_inner(&NODE_SET);
213
+ let set = if RArray::from_value(result).is_some() {
214
+ node_set_class.new_instance((document, result))?
215
+ } else if result.is_kind_of(node_set_class) {
216
+ result
217
+ } else {
218
+ return Err(Error::new(
219
+ ruby.exception_runtime_error(),
220
+ "Invalid return type",
221
+ ));
222
+ };
223
+ let members: RArray = set.funcall("to_a", ())?;
224
+ let mut ids = Vec::with_capacity(members.len());
225
+ for member in members {
226
+ let Ok(node) = <&Node>::try_convert(member) else {
227
+ continue; // A Namespace.
228
+ };
229
+ if node.document(ruby)?.as_raw() != document.as_raw() {
230
+ return Err(Error::new(
231
+ ruby.exception_runtime_error(),
232
+ "Invalid return type: node from another document",
233
+ ));
234
+ }
235
+ ids.push(node.id(ruby)?);
236
+ }
237
+ let ids = document::with_arena(ruby, document, move |arena| {
238
+ let mut ids: Vec<NodeId> = ids;
239
+ arena.sort_in_document_order(&mut ids);
240
+ ids
241
+ })?;
242
+ Ok(Ok(xpath::Value::NodeSet(ids)))
243
+ }
244
+
245
+ fn to_ruby(ruby: &Ruby, document: Obj<Node>, value: xpath::Value<'static>) -> Result<Value, Error> {
246
+ Ok(match value {
247
+ xpath::Value::NodeSet(ids) => node_set::wrap(ruby, document, ids)?,
248
+ xpath::Value::Boolean(b) => b.into_value_with(ruby),
249
+ xpath::Value::Number(n) => ruby.float_from_f64(n).as_value(),
250
+ xpath::Value::String(s) => utf8_string(ruby, s).as_value(),
251
+ })
252
+ }
253
+
254
+ /// An `XPath::SyntaxError` as Nokogiri makes it from the error of libxml2:
255
+ /// level ERROR, domain XPath, the expression in `str1`. For CSS, lobzique
256
+ /// quotes the rule, where Nokogiri quotes the XPath that it became.
257
+ fn xpath_error(ruby: &Ruby, error: xpath::Error, rule: &[u8]) -> Error {
258
+ syntax_error(ruby, "SyntaxError", error.message(), error.code(), rule)
259
+ }
260
+
261
+ /// `XPath::UnsupportedError`: valid XPath that lobzique leaves out.
262
+ /// It is raised as libxml2 would raise an invalid expression, and names
263
+ /// the construct.
264
+ fn unsupported_error(ruby: &Ruby, construct: &str, expression: &[u8]) -> Error {
265
+ let message = format!("Unsupported XPath: {construct}");
266
+ let code = xpath::Error::InvalidExpression.code();
267
+ syntax_error(ruby, "UnsupportedError", &message, code, expression)
268
+ }
269
+
270
+ fn syntax_error(ruby: &Ruby, class: &str, message: &str, code: i32, rule: &[u8]) -> Error {
271
+ let build = || -> Result<Exception, Error> {
272
+ let class: RClass = ruby
273
+ .get_inner(&XML)
274
+ .const_get::<_, magnus::RModule>("XPath")?
275
+ .const_get(class)?;
276
+ let error = XmlError {
277
+ domain: 12, // XML_FROM_XPATH
278
+ code,
279
+ message,
280
+ level: 2, // XML_ERR_ERROR
281
+ file: ruby.qnil().as_value(),
282
+ line: 0,
283
+ str1: Some(rule),
284
+ };
285
+ syntax_error::wrap(ruby, class, &error)
286
+ };
287
+ match build() {
288
+ Ok(exception) => Error::from(exception),
289
+ Err(error) => error,
290
+ }
291
+ }
292
+
293
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
294
+ let class = ruby.get_inner(&XPATH_CONTEXT);
295
+ class.undef_default_alloc_func();
296
+ class.define_singleton_method("new", function!(new, 1))?;
297
+ class.define_method("node=", method!(XPathContext::set_node, 1))?;
298
+ class.define_method("register_ns", method!(XPathContext::register_ns, 2))?;
299
+ class.define_method(
300
+ "register_variable",
301
+ method!(XPathContext::register_variable, 2),
302
+ )?;
303
+ class.define_method("evaluate", method!(XPathContext::evaluate, -1))?;
304
+ Ok(())
305
+ }
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Action Text on lobzique (plan.md decision 1, seam mode):
4
+ #
5
+ # require "lobzique/action_text"
6
+ #
7
+ # Action Text memoizes its document classes in instance variables,
8
+ # which is its own seam. Fragment.wrap knows only the fragment class
9
+ # of Nokogiri. Without the patch it would serialize a lobzique fragment
10
+ # and parse it again.
11
+
12
+ require "lobzique"
13
+ require "action_text"
14
+
15
+ module Lobzique
16
+ module ActionText
17
+ module Fragment
18
+ def wrap(fragment_or_html)
19
+ return new(fragment_or_html) if fragment_or_html.is_a?(XML::DocumentFragment)
20
+
21
+ super
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+ ActionText.instance_variable_set(:@html_document_class, Lobzique::HTML5::Document)
28
+ ActionText.instance_variable_set(:@html_document_fragment_class, Lobzique::HTML5::DocumentFragment)
29
+ ActionText::Fragment.singleton_class.prepend(Lobzique::ActionText::Fragment)
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/class_resolver.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ # Finds the class with a given name in the namespace of the receiver's
7
+ # class or of its nearest ancestor class, so a subclass such as
8
+ # `Loofah::HTML5::Document` gets `Loofah::HTML5::DocumentFragment`.
9
+ module ClassResolver
10
+ VALID_NAMESPACES = Set.new(["HTML", "HTML4", "HTML5", "XML", "SAX"])
11
+
12
+ def related_class(class_name)
13
+ klass = nil
14
+ inspecting = self.class
15
+
16
+ while inspecting
17
+ namespace_path = inspecting.name.split("::")[0..-2]
18
+ inspecting = inspecting.superclass
19
+
20
+ next unless VALID_NAMESPACES.include?(namespace_path.last)
21
+
22
+ related_class_name = (namespace_path << class_name).join("::")
23
+ klass = begin
24
+ Object.const_get(related_class_name)
25
+ rescue NameError
26
+ nil
27
+ end
28
+ break if klass
29
+ end
30
+ klass
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/selector_cache.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ module CSS
7
+ module SelectorCache # :nodoc:
8
+ @cache = {}
9
+ @mutex = Mutex.new
10
+
11
+ class << self
12
+ def [](key)
13
+ @mutex.synchronize { @cache[key] }
14
+ end
15
+
16
+ def []=(key, value)
17
+ @mutex.synchronize { @cache[key] = value }
18
+ end
19
+
20
+ def clear_cache(create_new_object = false)
21
+ @mutex.synchronize do
22
+ if create_new_object
23
+ @cache = {}
24
+ else
25
+ @cache.clear
26
+ end
27
+ end
28
+ end
29
+
30
+ def key(selector:, visitor:)
31
+ [selector, visitor.config]
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/syntax_error.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ require_relative "../syntax_error"
6
+
7
+ module Lobzique
8
+ module CSS
9
+ class SyntaxError < Lobzique::SyntaxError
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css/xpath_visitor.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ module CSS
7
+ # lobzique: the configuration only. The visit_* methods are in the core
8
+ # (crates/lobzique-core/src/css/write.rs). CSS::Parser#xpath_for runs them
9
+ # with this configuration, so a subclass cannot override them.
10
+ class XPathVisitor
11
+ module BuiltinsConfig
12
+ NEVER = :never
13
+ ALWAYS = :always
14
+ # lobzique: the same as ALWAYS, as in Nokogiri on libxml2.
15
+ OPTIMAL = :optimal
16
+
17
+ VALUES = [NEVER, ALWAYS, OPTIMAL]
18
+ end
19
+
20
+ module DoctypeConfig
21
+ XML = :xml
22
+ HTML4 = :html4
23
+ HTML5 = :html5
24
+
25
+ VALUES = [XML, HTML4, HTML5]
26
+ end
27
+
28
+ attr_reader :builtins
29
+
30
+ attr_reader :doctype
31
+
32
+ attr_reader :prefix
33
+
34
+ attr_reader :namespaces
35
+
36
+ def initialize(
37
+ builtins: BuiltinsConfig::NEVER,
38
+ doctype: DoctypeConfig::XML,
39
+ prefix: XML::XPath::GLOBAL_SEARCH_PREFIX,
40
+ namespaces: nil
41
+ )
42
+ unless BuiltinsConfig::VALUES.include?(builtins)
43
+ raise(ArgumentError, "Invalid values #{builtins.inspect} for builtins: keyword parameter")
44
+ end
45
+ unless DoctypeConfig::VALUES.include?(doctype)
46
+ raise(ArgumentError, "Invalid values #{doctype.inspect} for doctype: keyword parameter")
47
+ end
48
+
49
+ @builtins = builtins
50
+ @doctype = doctype
51
+ @prefix = prefix
52
+ @namespaces = namespaces
53
+ end
54
+
55
+ def config
56
+ {builtins: @builtins, doctype: @doctype, prefix: @prefix, namespaces: @namespaces}
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/css.rb (MIT, see
4
+ # LICENSE-NOKOGIRI.md). Searchable does not use this module: it compiles
5
+ # selectors to CSS::Selector (ARCHITECTURE.md). xpath_for is for callers
6
+ # that want the XPath strings, which the core writes as the visitor of Nokogiri
7
+ # does.
8
+
9
+ module Lobzique
10
+ module CSS
11
+ class << self
12
+ # lobzique: no CSS.parse. It is deprecated and returns CSS::Nodes.
13
+
14
+ def xpath_for(
15
+ selector, options = nil,
16
+ prefix: options&.delete(:prefix),
17
+ visitor: options&.delete(:visitor),
18
+ ns: options&.delete(:ns),
19
+ cache: true
20
+ )
21
+ unless options.nil?
22
+ # lobzique: Nokogiri names itself
23
+ warn("#{self}.xpath_for: Passing options as an explicit hash is deprecated. Use keyword arguments instead. This will become an error in a future release.", uplevel: 1, category: :deprecated)
24
+ end
25
+
26
+ raise(TypeError, "no implicit conversion of #{selector.inspect} to String") unless selector.respond_to?(:to_str)
27
+
28
+ selector = selector.to_str
29
+ raise(CSS::SyntaxError, "empty CSS selector") if selector.empty?
30
+
31
+ if visitor
32
+ raise ArgumentError, "cannot provide both :prefix and :visitor" if prefix
33
+ raise ArgumentError, "cannot provide both :ns and :visitor" if ns
34
+ end
35
+
36
+ visitor ||= begin
37
+ visitor_kw = {}
38
+ visitor_kw[:prefix] = prefix if prefix
39
+ visitor_kw[:namespaces] = ns if ns
40
+
41
+ CSS::XPathVisitor.new(**visitor_kw)
42
+ end
43
+
44
+ if cache
45
+ key = SelectorCache.key(selector: selector, visitor: visitor)
46
+ SelectorCache[key] ||= Parser.new.xpath_for(selector, visitor)
47
+ else
48
+ Parser.new.xpath_for(selector, visitor)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ require_relative "css/selector_cache"
56
+ require_relative "css/xpath_visitor"
57
+ require_relative "css/syntax_error"
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/extension.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ begin
6
+ # A native gem has a binary per Ruby ABI
7
+ RUBY_VERSION =~ /(\d+\.\d+)/
8
+ require_relative "#{Regexp.last_match(1)}/lobzique"
9
+ rescue LoadError => e
10
+ if e.message.include?("GLIBC")
11
+ # lobzique: no installation guide to link to
12
+ warn(<<~EOM)
13
+
14
+ ERROR: It looks like you're trying to use lobzique as a precompiled native gem on a system
15
+ with an unsupported version of glibc.
16
+
17
+ #{e.message}
18
+
19
+ If that's the case, then please install lobzique via the `ruby` platform gem:
20
+ gem install lobzique --platform=ruby
21
+ or:
22
+ bundle config set force_ruby_platform true
23
+
24
+ EOM
25
+ raise e
26
+ end
27
+
28
+ # Not require_relative: the source gem compiles into its extension_dir,
29
+ # which is on $LOAD_PATH but not next to this file.
30
+ require "lobzique/lobzique"
31
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/html.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ require_relative "html4"
6
+
7
+ module Lobzique
8
+ # Alias for Nokogiri::HTML4
9
+ HTML = HTML4
10
+
11
+ # :singleton-method: HTML
12
+ # Parse HTML. Convenience method for Nokogiri::HTML4::Document.parse
13
+ define_singleton_method(:HTML, Lobzique.method(:HTML4))
14
+ end