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,156 @@
1
+ //! Calls into Ruby that magnus has no direct helper for. This is the only
2
+ //! module that can use `unsafe` and `rb_sys::protect` (see `lib.rs`).
3
+ #![allow(unsafe_code)]
4
+ #![allow(clippy::disallowed_methods)]
5
+
6
+ use magnus::{
7
+ prelude::*,
8
+ rb_sys::{protect, AsRawId, AsRawValue, FromRawValue},
9
+ Error, RArray, RClass, RString, Ruby, Value,
10
+ };
11
+ use std::ffi::CString;
12
+
13
+ /// `rb_thread_check_ints`: lets Ruby handle interrupts (`Timeout`,
14
+ /// `Thread#raise`, signals) and switch threads if the time slice of this thread
15
+ /// is over, as it does between Ruby calls. Nothing here runs without the GVL.
16
+ pub fn check_interrupts() -> Result<(), Error> {
17
+ // SAFETY: `protect` turns what an interrupt raises into an `Err`.
18
+ protect(|| unsafe {
19
+ rb_sys::rb_thread_check_ints();
20
+ rb_sys::Qnil as rb_sys::VALUE
21
+ })?;
22
+ Ok(())
23
+ }
24
+
25
+ /// Ruby's `rb_obj_call_init`: runs `initialize` with the arguments and block
26
+ /// that the native constructor received, as the constructors of Nokogiri do.
27
+ pub fn call_initialize(object: Value, args: &[Value]) -> Result<(), Error> {
28
+ let argc = i32::try_from(args.len()).expect("argument count fits in an int");
29
+ let argv = args.as_ptr().cast::<rb_sys::VALUE>();
30
+ // SAFETY: `object` and `args` are live Ruby values on the stack, and
31
+ // `protect` turns an exception raised by `initialize` into an `Err`.
32
+ protect(|| unsafe {
33
+ rb_sys::rb_obj_call_init_kw(object.as_raw(), argc, argv, 0);
34
+ rb_sys::Qnil as rb_sys::VALUE
35
+ })?;
36
+ Ok(())
37
+ }
38
+
39
+ /// Ruby's `rb_apply`: calls `method` on `receiver`, private
40
+ /// or not, as `rb_funcall2` does, with the elements of `arguments`. An Array
41
+ /// keeps the arguments where the GC sees them. magnus has no call that takes
42
+ /// one.
43
+ pub fn apply(
44
+ ruby: &Ruby,
45
+ receiver: Value,
46
+ method: &str,
47
+ arguments: RArray,
48
+ ) -> Result<Value, Error> {
49
+ let id = ruby.intern(method).as_raw();
50
+ // SAFETY: `receiver` and `arguments` are live values on the stack, and
51
+ // `protect` turns an exception raised by the method into an `Err`.
52
+ let result =
53
+ protect(|| unsafe { rb_sys::rb_apply(receiver.as_raw(), id, arguments.as_raw()) })?;
54
+ // SAFETY: `rb_apply` returns a live value.
55
+ Ok(unsafe { Value::from_raw(result) })
56
+ }
57
+
58
+ pub fn yield_to_block(ruby: &Ruby, object: Value) -> Result<(), Error> {
59
+ if ruby.block_given() {
60
+ ruby.yield_value::<_, Value>(object)?;
61
+ }
62
+ Ok(())
63
+ }
64
+
65
+ /// Nokogiri's `NOKO_WARN_DEPRECATION`: prints only when `$VERBOSE` is true
66
+ /// and `Warning[:deprecated]` is on, with the location of the caller as prefix.
67
+ pub fn warn_deprecated(message: &str) -> Result<(), Error> {
68
+ // %s stops at a zero byte, as it does for the C strings of Nokogiri.
69
+ let message = message.split('\0').next().unwrap_or_default();
70
+ let message = CString::new(message).expect("no zero bytes left");
71
+ // SAFETY: the format takes one C string, and `protect` turns what a
72
+ // `Warning.warn` override raises into an `Err`.
73
+ protect(|| unsafe {
74
+ rb_sys::rb_category_warning(
75
+ rb_sys::rb_warning_category_t::RB_WARN_CATEGORY_DEPRECATED,
76
+ c"%s".as_ptr(),
77
+ message.as_ptr(),
78
+ );
79
+ rb_sys::Qnil as rb_sys::VALUE
80
+ })?;
81
+ Ok(())
82
+ }
83
+
84
+ pub fn optional_arg(ruby: &Ruby, args: &[Value], index: usize) -> Value {
85
+ args.get(index)
86
+ .copied()
87
+ .unwrap_or_else(|| ruby.qnil().as_value())
88
+ }
89
+
90
+ /// `rb_obj_class`: the class without singleton classes. Every decorated node
91
+ /// has one.
92
+ pub fn obj_class(value: Value) -> RClass {
93
+ // SAFETY: `rb_obj_class` takes any object and returns a class.
94
+ let class = unsafe { Value::from_raw(rb_sys::rb_obj_class(value.as_raw())) };
95
+ RClass::from_value(class).expect("rb_obj_class returns a class")
96
+ }
97
+
98
+ /// How the type errors of Ruby (`Check_Type`, `TypedData_Get_Struct`) name
99
+ /// the class of a wrong argument.
100
+ pub fn displayed_class(value: Value) -> String {
101
+ let raw = value.as_raw();
102
+ if raw == rb_sys::Qnil as rb_sys::VALUE {
103
+ "nil".into()
104
+ } else if raw == rb_sys::Qtrue as rb_sys::VALUE {
105
+ "true".into()
106
+ } else if raw == rb_sys::Qfalse as rb_sys::VALUE {
107
+ "false".into()
108
+ } else {
109
+ obj_class(value).inspect()
110
+ }
111
+ }
112
+
113
+ pub fn check_string(ruby: &Ruby, value: Value) -> Result<(), Error> {
114
+ if RString::from_value(value).is_some() {
115
+ return Ok(());
116
+ }
117
+ let message = format!(
118
+ "wrong argument type {} (expected String)",
119
+ displayed_class(value)
120
+ );
121
+ Err(Error::new(ruby.exception_type_error(), message))
122
+ }
123
+
124
+ /// A string as Nokogiri gives it to libxml2 through `StringValueCStr`:
125
+ /// converted with `to_str`, refused with `ArgumentError` if it has a NUL
126
+ /// character, then read as a C string up to the first zero byte. The bytes keep
127
+ /// their encoding.
128
+ pub fn c_string(value: Value) -> Result<Vec<u8>, Error> {
129
+ let mut bytes = c_string_with_length(value)?;
130
+ if let Some(end) = bytes.iter().position(|&byte| byte == 0) {
131
+ bytes.truncate(end);
132
+ }
133
+ Ok(bytes)
134
+ }
135
+
136
+ /// Like [`c_string`], but read with the length of the string,
137
+ /// as `xmlNewCDataBlock` reads it. Zero bytes stay, as in UTF-16.
138
+ pub fn c_string_with_length(value: Value) -> Result<Vec<u8>, Error> {
139
+ let mut raw = value.as_raw();
140
+ // SAFETY: `raw` is a live value on the stack. `protect` turns the TypeError
141
+ // or ArgumentError that `rb_string_value_cstr` raises into an `Err`.
142
+ // It replaces `raw` with the converted string.
143
+ let string = protect(|| unsafe {
144
+ rb_sys::rb_string_value_cstr(&mut raw);
145
+ raw
146
+ })?;
147
+ // SAFETY: the converted string is a live String on the stack.
148
+ let string = RString::from_value(unsafe { Value::from_raw(string) })
149
+ .expect("rb_string_value_cstr returns a String");
150
+ Ok(string_bytes(string))
151
+ }
152
+
153
+ pub fn string_bytes(string: RString) -> Vec<u8> {
154
+ // SAFETY: the bytes are copied before any Ruby code could change them.
155
+ unsafe { string.as_slice() }.to_vec()
156
+ }
@@ -0,0 +1,27 @@
1
+ use super::node::{Node, NODE};
2
+ use crate::support::c_string;
3
+ use crate::XML;
4
+ use magnus::{method, prelude::*, value::Lazy, Error, Module, RClass, Ruby, Value};
5
+
6
+ pub static ATTR: Lazy<RClass> = Lazy::new(|ruby| {
7
+ ruby.get_inner(&XML)
8
+ .define_class("Attr", ruby.get_inner(&NODE))
9
+ .unwrap()
10
+ });
11
+
12
+ /// `Attr#value=`. `nil` empties the value.
13
+ fn set_value(ruby: &Ruby, rb_self: &Node, content: Value) -> Result<Value, Error> {
14
+ let value = if content.is_nil() {
15
+ Vec::new()
16
+ } else {
17
+ c_string(content)?
18
+ };
19
+ rb_self.with_arena_mut(ruby, move |arena, id| arena.set_attribute_value(id, value))?;
20
+ Ok(content)
21
+ }
22
+
23
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
24
+ let class = ruby.get_inner(&ATTR);
25
+ class.define_method("value=", method!(set_value, 1))?;
26
+ Ok(())
27
+ }
@@ -0,0 +1,33 @@
1
+ use super::document;
2
+ use super::node::{document_for_new_node, finish_new};
3
+ use super::text::{expect_document_or_node, TEXT};
4
+ use crate::support::{c_string_with_length, check_string};
5
+ use crate::XML;
6
+ use magnus::{method, prelude::*, value::Lazy, Error, RClass, Ruby, Value};
7
+
8
+ pub static CDATA: Lazy<RClass> = Lazy::new(|ruby| {
9
+ ruby.get_inner(&XML)
10
+ .define_class("CDATA", ruby.get_inner(&TEXT))
11
+ .unwrap()
12
+ });
13
+
14
+ /// `CDATA.new(document, content, *rest)`.
15
+ fn new(ruby: &Ruby, class: RClass, args: &[Value]) -> Result<Value, Error> {
16
+ ruby.check_arity(args.len(), 2..)?;
17
+ check_string(ruby, args[1])?;
18
+ let document = expect_document_or_node(ruby, args[0], "first")?;
19
+ let document = document_for_new_node(
20
+ ruby,
21
+ document,
22
+ "Passing a Node as the first parameter to CDATA.new is deprecated. Please pass a Document instead.",
23
+ )?;
24
+ let content = c_string_with_length(args[1])?;
25
+ let id = document::with_arena_mut(ruby, document, |arena| arena.create_cdata(content))?;
26
+ finish_new(ruby, document, id, class, args)
27
+ }
28
+
29
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
30
+ let class = ruby.get_inner(&CDATA);
31
+ class.define_singleton_method("new", method!(new, -1))?;
32
+ Ok(())
33
+ }
@@ -0,0 +1,34 @@
1
+ use super::document;
2
+ use super::node::{finish_new, NODE};
3
+ use super::CHARACTER_DATA;
4
+ use crate::support::{c_string, check_string};
5
+ use crate::XML;
6
+ use magnus::{method, prelude::*, value::Lazy, Error, RClass, Ruby, Value};
7
+
8
+ pub static COMMENT: Lazy<RClass> = Lazy::new(|ruby| {
9
+ ruby.get_inner(&XML)
10
+ .define_class("Comment", ruby.get_inner(&CHARACTER_DATA))
11
+ .unwrap()
12
+ });
13
+
14
+ /// `Comment.new(document_or_node, content, *rest)`.
15
+ fn new(ruby: &Ruby, class: RClass, args: &[Value]) -> Result<Value, Error> {
16
+ ruby.check_arity(args.len(), 2..)?;
17
+ check_string(ruby, args[1])?;
18
+ if !args[0].is_kind_of(ruby.get_inner(&NODE)) {
19
+ return Err(Error::new(
20
+ ruby.exception_arg_error(),
21
+ "first argument must be a XML::Document or XML::Node",
22
+ ));
23
+ }
24
+ let document = document::unwrap(ruby, args[0].funcall("document", ())?)?;
25
+ let content = c_string(args[1])?;
26
+ let id = document::with_arena_mut(ruby, document, |arena| arena.create_comment(content))?;
27
+ finish_new(ruby, document, id, class, args)
28
+ }
29
+
30
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
31
+ let class = ruby.get_inner(&COMMENT);
32
+ class.define_singleton_method("new", method!(new, -1))?;
33
+ Ok(())
34
+ }
@@ -0,0 +1,199 @@
1
+ use super::node::{utf8_string, wrap, Node, NODE};
2
+ use super::ELEMENT;
3
+ use crate::support::{c_string, call_initialize, displayed_class, obj_class, optional_arg};
4
+ use crate::XML;
5
+ use lobzique_core::dom::{self, CopyDepth, DocumentKind, NodeId, NodeType};
6
+ use magnus::{
7
+ method, prelude::*, rb_sys::AsRawValue, typed_data::Obj, value::Lazy, Error, RClass, RString,
8
+ Ruby, Value,
9
+ };
10
+
11
+ pub static DOCUMENT: Lazy<RClass> = Lazy::new(|ruby| {
12
+ ruby.get_inner(&XML)
13
+ .define_class("Document", ruby.get_inner(&NODE))
14
+ .unwrap()
15
+ });
16
+
17
+ /// A document object of `class` that owns `arena`, before `initialize` has run:
18
+ /// `noko_xml_document_wrap` of Nokogiri.
19
+ pub fn wrap_document(ruby: &Ruby, class: RClass, arena: dom::Document) -> Result<Value, Error> {
20
+ let document = ruby.obj_wrap_as(Node::new_document(arena), class);
21
+ Node::complete_document(ruby, document);
22
+ document.ivar_set("@decorators", ruby.qnil())?;
23
+ document.ivar_set("@errors", ruby.qnil())?;
24
+ Ok(document.as_value())
25
+ }
26
+
27
+ /// `Document.new(version = "1.0", *rest)`.
28
+ fn new(ruby: &Ruby, class: RClass, args: &[Value]) -> Result<Value, Error> {
29
+ let version = optional_arg(ruby, args, 0);
30
+ let version = if version.is_nil() {
31
+ b"1.0".to_vec()
32
+ } else {
33
+ c_string(version)?
34
+ };
35
+ let mut arena = dom::Document::new(DocumentKind::Xml);
36
+ arena.set_version(Some(version));
37
+ let document = wrap_document(ruby, class, arena)?;
38
+ call_initialize(document, args)?;
39
+ Ok(document)
40
+ }
41
+
42
+ /// A document object that Ruby code gave. Raises as `noko_xml_document_unwrap`
43
+ /// does. Nodes keep their document in this form, so only arguments need
44
+ /// the check.
45
+ pub fn unwrap(ruby: &Ruby, document: Value) -> Result<Obj<Node>, Error> {
46
+ let class = ruby.get_inner(&DOCUMENT);
47
+ if !document.is_kind_of(class) {
48
+ let message = format!(
49
+ "wrong argument type {} (expected {})",
50
+ displayed_class(document),
51
+ class.inspect()
52
+ );
53
+ return Err(Error::new(ruby.exception_type_error(), message));
54
+ }
55
+ Obj::try_convert(document)
56
+ }
57
+
58
+ /// Runs `f` on the arena of the document. The borrow ends when `f` returns.
59
+ ///
60
+ /// `f` must be `Send`. Ruby handles are not `Send`, so `f` can neither call
61
+ /// Ruby nor return a Ruby object (ARCHITECTURE.md, "Memory model"). Copy
62
+ /// in beforehand what `f` needs from Ruby. Copy out what Ruby needs
63
+ /// from the arena.
64
+ pub fn with_arena<R: Send>(
65
+ ruby: &Ruby,
66
+ document: Obj<Node>,
67
+ f: impl FnOnce(&dom::Document) -> R + Send,
68
+ ) -> Result<R, Error> {
69
+ let arena = document.arena(ruby)?;
70
+ let arena = arena.try_borrow().map_err(|_| busy(ruby))?;
71
+ Ok(f(&arena))
72
+ }
73
+
74
+ /// [`with_arena`] with a mutable borrow.
75
+ pub fn with_arena_mut<R: Send>(
76
+ ruby: &Ruby,
77
+ document: Obj<Node>,
78
+ f: impl FnOnce(&mut dom::Document) -> R + Send,
79
+ ) -> Result<R, Error> {
80
+ let arena = document.arena(ruby)?;
81
+ let mut arena = arena.try_borrow_mut().map_err(|_| busy(ruby))?;
82
+ Ok(f(&mut arena))
83
+ }
84
+
85
+ /// [`with_arena_mut`] on two different documents at once.
86
+ pub fn with_arenas_mut<R: Send>(
87
+ ruby: &Ruby,
88
+ first: Obj<Node>,
89
+ second: Obj<Node>,
90
+ f: impl FnOnce(&mut dom::Document, &mut dom::Document) -> R + Send,
91
+ ) -> Result<R, Error> {
92
+ let (first, second) = (first.arena(ruby)?, second.arena(ruby)?);
93
+ let mut first = first.try_borrow_mut().map_err(|_| busy(ruby))?;
94
+ let mut second = second.try_borrow_mut().map_err(|_| busy(ruby))?;
95
+ Ok(f(&mut first, &mut second))
96
+ }
97
+
98
+ // Unreachable while no borrow outlives a call into Ruby. A guard,
99
+ // not a feature.
100
+ fn busy(ruby: &Ruby) -> Error {
101
+ Error::new(
102
+ ruby.exception_runtime_error(),
103
+ "document is in use by a native call",
104
+ )
105
+ }
106
+
107
+ fn root(ruby: &Ruby, rb_self: Obj<Node>) -> Result<Option<Value>, Error> {
108
+ let root = with_arena(ruby, rb_self, |arena| {
109
+ arena.element_children(NodeId::DOCUMENT).next()
110
+ })?;
111
+ root.map(|id| wrap(ruby, rb_self, id)).transpose()
112
+ }
113
+
114
+ /// `Document#root=`. A root from another document is copied. The argument
115
+ /// is returned as given, still in its own document.
116
+ fn set_root(ruby: &Ruby, rb_self: Obj<Node>, new_root: Value) -> Result<Value, Error> {
117
+ if new_root.is_nil() {
118
+ with_arena_mut(ruby, rb_self, |arena| arena.set_root(None))?
119
+ .expect("no root is always allowed");
120
+ return Ok(new_root);
121
+ }
122
+ let node_class = ruby.get_inner(&NODE);
123
+ if !new_root.is_kind_of(node_class) {
124
+ let message = format!(
125
+ "expected {} but received {}",
126
+ node_class.inspect(),
127
+ obj_class(new_root).inspect()
128
+ );
129
+ return Err(Error::new(ruby.exception_arg_error(), message));
130
+ }
131
+ let root = <&Node>::try_convert(new_root)?;
132
+ let (root_document, id) = (root.document(ruby)?, root.id(ruby)?);
133
+ if root.with_arena(ruby, |arena, id| arena.node_type(id))? != NodeType::Element {
134
+ let message = format!("root must be a {}", ruby.get_inner(&ELEMENT).inspect());
135
+ return Err(Error::new(ruby.exception_type_error(), message));
136
+ }
137
+ let set = if root_document.as_raw() == rb_self.as_raw() {
138
+ with_arena_mut(ruby, rb_self, |arena| arena.set_root(Some(id)))?
139
+ } else {
140
+ with_arenas_mut(ruby, rb_self, root_document, |arena, source| {
141
+ let copy = arena.import(source, id, CopyDepth::Deep);
142
+ arena.set_root(copy)
143
+ })?
144
+ };
145
+ set.expect("checked to be an element");
146
+ Ok(new_root)
147
+ }
148
+
149
+ /// `Document#initialize_copy_with_args(other, level)`, after `Object#dup` has
150
+ /// allocated the copy and copied the instance variables. The arena is copied,
151
+ /// as `xmlCopyDoc` copies the document, with a new node cache.
152
+ fn initialize_copy_with_args(
153
+ ruby: &Ruby,
154
+ rb_self: Obj<Node>,
155
+ other: Value,
156
+ level: i32,
157
+ ) -> Result<Value, Error> {
158
+ let other = unwrap(ruby, other)?;
159
+ let copy = with_arena(ruby, other, move |arena| arena.copy_document(level != 0))?;
160
+ if !rb_self.adopt_arena(copy) {
161
+ return Err(Error::new(
162
+ ruby.exception_runtime_error(),
163
+ "document is already initialized",
164
+ ));
165
+ }
166
+ Node::complete_document(ruby, rb_self);
167
+ Ok(rb_self.as_value())
168
+ }
169
+
170
+ fn encoding(ruby: &Ruby, rb_self: Obj<Node>) -> Result<Option<RString>, Error> {
171
+ let encoding = with_arena(ruby, rb_self, |arena| arena.encoding().map(<[u8]>::to_vec))?;
172
+ Ok(encoding.map(|encoding| utf8_string(ruby, encoding)))
173
+ }
174
+
175
+ fn set_encoding(ruby: &Ruby, rb_self: Obj<Node>, encoding: Value) -> Result<Value, Error> {
176
+ let label = c_string(encoding)?;
177
+ with_arena_mut(ruby, rb_self, |arena| arena.set_encoding(Some(label)))?;
178
+ Ok(encoding)
179
+ }
180
+
181
+ fn version(ruby: &Ruby, rb_self: Obj<Node>) -> Result<Option<RString>, Error> {
182
+ let version = with_arena(ruby, rb_self, |arena| arena.version().map(<[u8]>::to_vec))?;
183
+ Ok(version.map(|version| utf8_string(ruby, version)))
184
+ }
185
+
186
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
187
+ let class = ruby.get_inner(&DOCUMENT);
188
+ class.define_singleton_method("new", method!(new, -1))?;
189
+ class.define_method("root", method!(root, 0))?;
190
+ class.define_method("root=", method!(set_root, 1))?;
191
+ class.define_method("encoding", method!(encoding, 0))?;
192
+ class.define_method("encoding=", method!(set_encoding, 1))?;
193
+ class.define_method("version", method!(version, 0))?;
194
+ class.define_protected_method(
195
+ "initialize_copy_with_args",
196
+ method!(initialize_copy_with_args, 2),
197
+ )?;
198
+ Ok(())
199
+ }
@@ -0,0 +1,27 @@
1
+ //! `XML::DocumentFragment`. `DocumentFragment.new` of Ruby calls `native_new`
2
+ //! and then `initialize`, so subclasses override only the latter.
3
+
4
+ use super::document;
5
+ use super::node::{wrap_as, NODE};
6
+ use crate::XML;
7
+ use magnus::{method, prelude::*, value::Lazy, Error, RClass, Ruby, Value};
8
+
9
+ pub static DOCUMENT_FRAGMENT: Lazy<RClass> = Lazy::new(|ruby| {
10
+ ruby.get_inner(&XML)
11
+ .define_class("DocumentFragment", ruby.get_inner(&NODE))
12
+ .unwrap()
13
+ });
14
+
15
+ /// `DocumentFragment.native_new(document)`: a fragment of the receiving
16
+ /// class, wrapped and decorated, before `initialize`.
17
+ fn native_new(ruby: &Ruby, class: RClass, document: Value) -> Result<Value, Error> {
18
+ let document = document::unwrap(ruby, document)?;
19
+ let id = document::with_arena_mut(ruby, document, |arena| arena.create_fragment())?;
20
+ wrap_as(ruby, document, id, Some(class))
21
+ }
22
+
23
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
24
+ let class = ruby.get_inner(&DOCUMENT_FRAGMENT);
25
+ class.define_singleton_method("native_new", method!(native_new, 1))?;
26
+ Ok(())
27
+ }
@@ -0,0 +1,37 @@
1
+ use super::node::{utf8_string, Node, NODE};
2
+ use crate::XML;
3
+ use lobzique_core::dom::{Doctype, NodeKind};
4
+ use magnus::{method, value::Lazy, Error, Module, RClass, RString, Ruby};
5
+
6
+ pub static DTD: Lazy<RClass> = Lazy::new(|ruby| {
7
+ ruby.get_inner(&XML)
8
+ .define_class("DTD", ruby.get_inner(&NODE))
9
+ .unwrap()
10
+ });
11
+
12
+ fn doctype_field(
13
+ ruby: &Ruby,
14
+ rb_self: &Node,
15
+ field: fn(&Doctype) -> &Option<Vec<u8>>,
16
+ ) -> Result<Option<RString>, Error> {
17
+ let value = rb_self.with_arena(ruby, move |arena, id| match arena.node_kind(id) {
18
+ NodeKind::Doctype(doctype) => field(doctype).clone(),
19
+ _ => None,
20
+ })?;
21
+ Ok(value.map(|value| utf8_string(ruby, value)))
22
+ }
23
+
24
+ fn system_id(ruby: &Ruby, rb_self: &Node) -> Result<Option<RString>, Error> {
25
+ doctype_field(ruby, rb_self, |doctype| &doctype.system_id)
26
+ }
27
+
28
+ fn external_id(ruby: &Ruby, rb_self: &Node) -> Result<Option<RString>, Error> {
29
+ doctype_field(ruby, rb_self, |doctype| &doctype.public_id)
30
+ }
31
+
32
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
33
+ let class = ruby.get_inner(&DTD);
34
+ class.define_method("system_id", method!(system_id, 0))?;
35
+ class.define_method("external_id", method!(external_id, 0))?;
36
+ Ok(())
37
+ }
@@ -0,0 +1,44 @@
1
+ pub mod attr;
2
+ pub mod cdata;
3
+ pub mod comment;
4
+ pub mod document;
5
+ pub mod document_fragment;
6
+ pub mod dtd;
7
+ pub mod namespace;
8
+ pub mod node;
9
+ pub mod node_set;
10
+ pub mod syntax_error;
11
+ pub mod text;
12
+ pub mod xpath_context;
13
+
14
+ use crate::XML;
15
+ use magnus::{value::Lazy, Error, Module, RClass, Ruby};
16
+ use node::NODE;
17
+
18
+ // Nokogiri defines these two in nokogiri.c, with no native methods.
19
+ pub static ELEMENT: Lazy<RClass> = Lazy::new(|ruby| {
20
+ ruby.get_inner(&XML)
21
+ .define_class("Element", ruby.get_inner(&NODE))
22
+ .unwrap()
23
+ });
24
+ pub static CHARACTER_DATA: Lazy<RClass> = Lazy::new(|ruby| {
25
+ ruby.get_inner(&XML)
26
+ .define_class("CharacterData", ruby.get_inner(&NODE))
27
+ .unwrap()
28
+ });
29
+
30
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
31
+ namespace::init(ruby)?;
32
+ node::init(ruby)?;
33
+ attr::init(ruby)?;
34
+ dtd::init(ruby)?;
35
+ ruby.get_inner(&ELEMENT);
36
+ ruby.get_inner(&CHARACTER_DATA);
37
+ comment::init(ruby)?;
38
+ text::init(ruby)?;
39
+ cdata::init(ruby)?;
40
+ document_fragment::init(ruby)?;
41
+ document::init(ruby)?;
42
+ xpath_context::init(ruby)?;
43
+ Ok(())
44
+ }
@@ -0,0 +1,56 @@
1
+ use super::node::utf8_string;
2
+ use crate::XML;
3
+ use magnus::{
4
+ method, prelude::*, value::Lazy, DataTypeFunctions, Error, RClass, RString, Ruby, TypedData,
5
+ Value,
6
+ };
7
+
8
+ pub static NAMESPACE: Lazy<RClass> = Lazy::new(|ruby| {
9
+ ruby.get_inner(&XML)
10
+ .define_class("Namespace", ruby.class_object())
11
+ .unwrap()
12
+ });
13
+
14
+ /// A copy of the prefix and URI. libxml2 shares one `xmlNs` among the nodes
15
+ /// that use it, and Nokogiri one object. Here each call makes a new one
16
+ /// (ARCHITECTURE.md, departures).
17
+ #[derive(TypedData)]
18
+ #[magnus(class = "Lobzique::XML::Namespace", free_immediately)]
19
+ pub struct Namespace {
20
+ prefix: Option<String>,
21
+ href: String,
22
+ }
23
+
24
+ impl DataTypeFunctions for Namespace {}
25
+
26
+ impl Namespace {
27
+ fn prefix(ruby: &Ruby, rb_self: &Self) -> Option<RString> {
28
+ rb_self
29
+ .prefix
30
+ .as_ref()
31
+ .map(|prefix| utf8_string(ruby, prefix))
32
+ }
33
+
34
+ fn href(ruby: &Ruby, rb_self: &Self) -> RString {
35
+ utf8_string(ruby, &rb_self.href)
36
+ }
37
+ }
38
+
39
+ pub fn wrap(
40
+ ruby: &Ruby,
41
+ document: Value,
42
+ prefix: Option<String>,
43
+ href: String,
44
+ ) -> Result<Value, Error> {
45
+ let namespace = ruby.obj_wrap_as(Namespace { prefix, href }, ruby.get_inner(&NAMESPACE));
46
+ namespace.ivar_set("@document", document)?;
47
+ Ok(namespace.as_value())
48
+ }
49
+
50
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
51
+ let class = ruby.get_inner(&NAMESPACE);
52
+ class.undef_default_alloc_func();
53
+ class.define_method("prefix", method!(Namespace::prefix, 0))?;
54
+ class.define_method("href", method!(Namespace::href, 0))?;
55
+ Ok(())
56
+ }