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,22 @@
1
+ [package]
2
+ name = "lobzique"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ authors = ["Jury Razumau <mail@razumau.net>"]
6
+ license = "MIT"
7
+ publish = false
8
+
9
+ [lib]
10
+ crate-type = ["cdylib"]
11
+
12
+ [dependencies]
13
+ lobzique-core = { path = "../../crates/lobzique-core" }
14
+ magnus = { version = "0.9.4", features = ["rb-sys"] }
15
+ rb-sys = { version = "0.9", features = ["stable-api-compiled-fallback"] }
16
+
17
+ [features]
18
+ # Runs a full GC before and after every Ruby C API call (see `rake test:gc_stress`).
19
+ gc-stress = ["rb-sys/gc-stress"]
20
+
21
+ [build-dependencies]
22
+ rb-sys-env = "0.2.2"
@@ -0,0 +1,5 @@
1
+ pub fn main() -> Result<(), Box<dyn std::error::Error>> {
2
+ let _ = rb_sys_env::activate()?;
3
+
4
+ Ok(())
5
+ }
@@ -0,0 +1,15 @@
1
+ # Ways to reach Ruby without a handle, which code borrowing an arena must
2
+ # not have (lib.rs). `support` is the one module allowed `protect`.
3
+ disallowed-methods = [
4
+ { path = "magnus::Ruby::get", reason = "take `&Ruby` as an argument instead" },
5
+ { path = "magnus::Ruby::get_with", reason = "take `&Ruby` as an argument instead" },
6
+ { path = "magnus::eval", reason = "use `Ruby::eval`" },
7
+ { path = "magnus::rb_sys::protect", reason = "calls Ruby without a handle; wrap the call in `support`" },
8
+ ]
9
+ disallowed-macros = [
10
+ { path = "magnus::eval", reason = "fetches a handle itself" },
11
+ { path = "magnus::rb_assert", reason = "fetches a handle itself" },
12
+ ]
13
+ disallowed-types = [
14
+ { path = "magnus::value::LazyId", reason = "`Send`, and calls Ruby without a handle" },
15
+ ]
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mkmf"
4
+ require "rb_sys/mkmf"
5
+
6
+ create_rust_makefile("lobzique/lobzique")
@@ -0,0 +1,9 @@
1
+ pub mod parser;
2
+ pub mod selector;
3
+
4
+ use magnus::{Error, Ruby};
5
+
6
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
7
+ selector::init(ruby)?;
8
+ parser::init(ruby)
9
+ }
@@ -0,0 +1,44 @@
1
+ //! `CSS::Parser#xpath_for`. In Nokogiri it parses the selector
2
+ //! into `CSS::Node`s for the visitor to walk. Here the core does
3
+ //! both, so the visitor only configures it (ARCHITECTURE.md).
4
+
5
+ use crate::CSS;
6
+ use lobzique_core::css::{self, Visitor};
7
+ use magnus::{method, prelude::*, Error, RArray, RString, Ruby, Symbol, Value};
8
+
9
+ fn xpath_for(
10
+ ruby: &Ruby,
11
+ _rb_self: Value,
12
+ selector: RString,
13
+ visitor: Value,
14
+ ) -> Result<RArray, Error> {
15
+ let rule = String::from_utf8(crate::support::string_bytes(selector))
16
+ .map_err(|_| Error::new(ruby.exception_arg_error(), "invalid byte sequence in UTF-8"))?;
17
+ let builtins: Symbol = visitor.funcall("builtins", ())?;
18
+ let doctype: Symbol = visitor.funcall("doctype", ())?;
19
+ let prefix: RString = visitor.funcall("prefix", ())?;
20
+ let namespaces: Value = visitor.funcall("namespaces", ())?;
21
+ let visitor = Visitor {
22
+ // OPTIMAL asks Nokogiri.uses_libxml?, and lobzique has the builtins.
23
+ builtins: builtins.name()? != "never",
24
+ html5: doctype.name()? == "html5",
25
+ default_namespace: !namespaces.is_nil()
26
+ && namespaces.funcall::<_, _, bool>("key?", ("xmlns",))?,
27
+ prefix: prefix.to_string()?,
28
+ };
29
+ let paths = css::xpath_for(&rule, &visitor).map_err(|error| {
30
+ match ruby.get_inner(&CSS).const_get("SyntaxError") {
31
+ Ok(class) => Error::new(class, error.0),
32
+ Err(error) => error,
33
+ }
34
+ })?;
35
+ Ok(ruby.ary_from_iter(paths.iter().map(|path| ruby.str_new(path))))
36
+ }
37
+
38
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
39
+ let class = ruby
40
+ .get_inner(&CSS)
41
+ .define_class("Parser", ruby.class_object())?;
42
+ class.define_method("xpath_for", method!(xpath_for, 2))?;
43
+ Ok(())
44
+ }
@@ -0,0 +1,101 @@
1
+ //! `CSS::Selector`: a selector list compiled to the query
2
+ //! that the `XPathVisitor` of Nokogiri would write as an XPath string. Nokogiri
3
+ //! has no such class. `Searchable` makes one where it would make that string,
4
+ //! and `XPathContext#evaluate` runs it (ARCHITECTURE.md).
5
+
6
+ use crate::CSS;
7
+ use lobzique_core::css::{self, Options, Prefix};
8
+ use magnus::{
9
+ function, prelude::*, scan_args::get_kwargs, scan_args::scan_args, value::Lazy, Error, RArray,
10
+ RClass, RHash, RString, Ruby, Symbol, TypedData, Value,
11
+ };
12
+
13
+ pub static SELECTOR: Lazy<RClass> = Lazy::new(|ruby| {
14
+ ruby.get_inner(&CSS)
15
+ .define_class("Selector", ruby.class_object())
16
+ .unwrap()
17
+ });
18
+
19
+ #[derive(TypedData)]
20
+ #[magnus(class = "Lobzique::CSS::Selector", free_immediately)]
21
+ pub struct Selector {
22
+ pub compiled: css::Selector,
23
+ /// The selector as written. XPath errors quote it.
24
+ pub rule: String,
25
+ }
26
+
27
+ impl magnus::DataTypeFunctions for Selector {}
28
+
29
+ /// `CSS::Selector.new(rule, prefixes:, doctype:, namespaces: nil, builtins:
30
+ /// true, first: false)`: the arguments of `XPathVisitor.new`
31
+ /// and `CSS.xpath_for` in Nokogiri. `doctype:` is what `Document#xpath_doctype`
32
+ /// returns.
33
+ fn new(ruby: &Ruby, args: &[Value]) -> Result<Selector, Error> {
34
+ let args = scan_args::<(RString,), (), (), (), RHash, ()>(args)?;
35
+ let keywords =
36
+ get_kwargs::<_, (RArray, Symbol), (Option<Value>, Option<bool>, Option<bool>), ()>(
37
+ args.keywords,
38
+ &["prefixes", "doctype"],
39
+ &["namespaces", "builtins", "first"],
40
+ )?;
41
+ let (prefixes, doctype) = keywords.required;
42
+ let (namespaces, builtins, first) = keywords.optional;
43
+ let rule = String::from_utf8(crate::support::string_bytes(args.required.0))
44
+ .map_err(|_| Error::new(ruby.exception_arg_error(), "invalid byte sequence in UTF-8"))?;
45
+ let prefixes = prefixes
46
+ .into_iter()
47
+ .map(|prefix| {
48
+ let prefix = RString::try_convert(prefix)?.to_string()?;
49
+ Prefix::parse(&prefix).ok_or_else(|| {
50
+ Error::new(
51
+ ruby.exception_arg_error(),
52
+ format!("unknown XPath prefix {prefix:?}"),
53
+ )
54
+ })
55
+ })
56
+ .collect::<Result<Vec<_>, Error>>()?;
57
+ // HTML4 documents parse as HTML5 (plan.md decision 3), so their names have
58
+ // the namespaces of HTML5, which CSS queries ignore.
59
+ let html = match doctype.name()?.as_ref() {
60
+ "xml" => false,
61
+ "html4" | "html5" => true,
62
+ _ => {
63
+ let message = format!(
64
+ "Invalid values {} for doctype: keyword parameter",
65
+ doctype.inspect()
66
+ );
67
+ return Err(Error::new(ruby.exception_arg_error(), message));
68
+ }
69
+ };
70
+ let default_namespace = match namespaces.filter(|namespaces| !namespaces.is_nil()) {
71
+ Some(namespaces) => namespaces.funcall::<_, _, bool>("key?", ("xmlns",))?,
72
+ None => false,
73
+ };
74
+ let options = Options {
75
+ html,
76
+ builtins: builtins.unwrap_or(true),
77
+ default_namespace,
78
+ prefixes,
79
+ first_only: first.unwrap_or(false),
80
+ };
81
+ let compiled = css::compile(&rule, &options).map_err(|error| match syntax_error(ruby) {
82
+ Ok(class) => Error::new(class, error.0),
83
+ Err(error) => error,
84
+ })?;
85
+ Ok(Selector { compiled, rule })
86
+ }
87
+
88
+ fn syntax_error(ruby: &Ruby) -> Result<magnus::ExceptionClass, Error> {
89
+ ruby.get_inner(&CSS).const_get("SyntaxError")
90
+ }
91
+
92
+ fn rule(ruby: &Ruby, rb_self: &Selector) -> RString {
93
+ ruby.str_new(&rb_self.rule)
94
+ }
95
+
96
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
97
+ let class = ruby.get_inner(&SELECTOR);
98
+ class.define_singleton_method("new", function!(new, -1))?;
99
+ class.define_method("to_s", magnus::method!(rule, 0))?;
100
+ Ok(())
101
+ }
@@ -0,0 +1,31 @@
1
+ use crate::support::{c_string, call_initialize, optional_arg};
2
+ use crate::xml::document::{wrap_document, DOCUMENT};
3
+ use crate::HTML4;
4
+ use lobzique_core::dom;
5
+ use magnus::{method, prelude::*, value::Lazy, Error, RClass, Ruby, Value};
6
+
7
+ pub static HTML4_DOCUMENT: Lazy<RClass> = Lazy::new(|ruby| {
8
+ ruby.get_inner(&HTML4)
9
+ .define_class("Document", ruby.get_inner(&DOCUMENT))
10
+ .unwrap()
11
+ });
12
+
13
+ /// `HTML4::Document.new(uri = nil, external_id = nil, *rest)`. It starts
14
+ /// with the default HTML 4.0 doctype of libxml2. `HTML5::Document.new` inherits
15
+ /// it.
16
+ fn new(ruby: &Ruby, class: RClass, args: &[Value]) -> Result<Value, Error> {
17
+ let truthy_string = |index| -> Result<Option<Vec<u8>>, Error> {
18
+ let value = optional_arg(ruby, args, index);
19
+ value.to_bool().then(|| c_string(value)).transpose()
20
+ };
21
+ let arena = dom::Document::new_html4(truthy_string(0)?, truthy_string(1)?);
22
+ let document = wrap_document(ruby, class, arena)?;
23
+ call_initialize(document, args)?;
24
+ Ok(document)
25
+ }
26
+
27
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
28
+ let class = ruby.get_inner(&HTML4_DOCUMENT);
29
+ class.define_singleton_method("new", method!(new, -1))?;
30
+ Ok(())
31
+ }
@@ -0,0 +1,7 @@
1
+ pub mod document;
2
+
3
+ use magnus::{Error, Ruby};
4
+
5
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
6
+ document::init(ruby)
7
+ }
@@ -0,0 +1,16 @@
1
+ use crate::html4::document::HTML4_DOCUMENT;
2
+ use crate::HTML5;
3
+ use magnus::{value::Lazy, Error, Module, RClass, Ruby};
4
+
5
+ // Native, so that its superclass is fixed before the Ruby files load,
6
+ // as in gumbo.c of Nokogiri. All of its methods are Ruby.
7
+ pub static HTML5_DOCUMENT: Lazy<RClass> = Lazy::new(|ruby| {
8
+ ruby.get_inner(&HTML5)
9
+ .define_class("Document", ruby.get_inner(&HTML4_DOCUMENT))
10
+ .unwrap()
11
+ });
12
+
13
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
14
+ ruby.get_inner(&HTML5_DOCUMENT);
15
+ Ok(())
16
+ }
@@ -0,0 +1,278 @@
1
+ //! `Html5ever`, the `Gumbo` of Nokogiri (`ext/nokogiri/gumbo.c`): the entry
2
+ //! points of the HTML5 parser behind `HTML5::Document.parse`
3
+ //! and `HTML5::DocumentFragment#initialize`, and the parse behind
4
+ //! `Node#in_context`.
5
+
6
+ use crate::support::{c_string, call_initialize, check_interrupts, check_string, string_bytes};
7
+ use crate::xml::document::{self, wrap_document};
8
+ use crate::xml::node::{utf8_string, Node};
9
+ use crate::xml::node_set;
10
+ use crate::xml::syntax_error::{self, XmlError};
11
+ use crate::{HTML5EVER, XML};
12
+ use lobzique_core::html5::{
13
+ self, Context, ContextError, ContextNamespace, DocumentParser, FragmentParser, LimitError,
14
+ Options, ParseError, QuirksMode,
15
+ };
16
+ use magnus::{
17
+ function,
18
+ prelude::*,
19
+ scan_args::{get_kwargs, scan_args},
20
+ typed_data::Obj,
21
+ Error, RArray, RClass, RHash, RString, Ruby, Value,
22
+ };
23
+ use std::sync::OnceLock;
24
+
25
+ /// `Html5ever.parse(input, url, klass, **options)`: a document of `klass`,
26
+ /// initialized with no arguments, then given `@url`, `@quirks_mode`
27
+ /// and, if there were any, `@errors`.
28
+ fn parse(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
29
+ let args = scan_args::<(Value, Value, Value), (), (), (), RHash, ()>(args)?;
30
+ let (input, url, klass) = args.required;
31
+ let options = options(args.keywords)?;
32
+ let input = input_bytes(ruby, input)?;
33
+ let klass = RClass::try_convert(klass)?;
34
+
35
+ let mut parser = DocumentParser::new(input, &options);
36
+ run(|| parser.step())?;
37
+ let (arena, parsed) = parser.finish().map_err(|error| limit_error(ruby, error))?;
38
+ let document = wrap_document(ruby, klass, arena)?;
39
+ call_initialize(document, &[])?;
40
+ let object = Obj::<Node>::try_convert(document)?;
41
+ object.ivar_set("@url", url)?;
42
+ object.ivar_set("@quirks_mode", parsed.quirks_mode as u8)?;
43
+ add_errors(ruby, object, parsed.errors, url)?;
44
+ Ok(document)
45
+ }
46
+
47
+ /// `Html5ever.fragment(fragment, input, context, **options)`: parses `input`
48
+ /// in `context` (nil, a name such as `"svg:path"`, or a node) and appends
49
+ /// the result to `fragment`.
50
+ fn fragment(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
51
+ let args = scan_args::<(Value, Value, Value), (), (), (), RHash, ()>(args)?;
52
+ let (fragment, input, context_arg) = args.required;
53
+ let options = options(args.keywords)?;
54
+ let document: Value = fragment.funcall("document", ())?;
55
+ let context = context_for(ruby, context_arg, document)?;
56
+ let input = input_bytes(ruby, input)?;
57
+ let target = Obj::<Node>::try_convert(fragment)?;
58
+
59
+ let mut parser = FragmentParser::new(input, &context, &options);
60
+ run(|| parser.step())?;
61
+ let nodes = parser.finish().map_err(|error| limit_error(ruby, error))?;
62
+ // Nokogiri builds in the document that `fragment.document` names. The nodes
63
+ // can go only into the arena of the fragment itself, which another thread
64
+ // may have changed during the parse.
65
+ let parsed = target.with_arena_mut(ruby, move |arena, id| nodes.append_to(arena, id))?;
66
+ target.ivar_set("@quirks_mode", parsed.quirks_mode as u8)?;
67
+ add_errors(
68
+ ruby,
69
+ target,
70
+ parsed.errors,
71
+ utf8_string(ruby, "#fragment").as_value(),
72
+ )
73
+ }
74
+
75
+ /// The parse of `Node#in_context`: `input` as a fragment in the context
76
+ /// that `Context::for_node` finds for `node`. The top-level nodes come back
77
+ /// unlinked. The parse errors go to the `@errors` of the document.
78
+ pub fn in_context(ruby: &Ruby, node: &Node, input: Value) -> Result<Value, Error> {
79
+ let input = input_bytes(ruby, input)?;
80
+ let document_object = node.document(ruby)?;
81
+ let parsed = !document_object
82
+ .ivar_get::<_, Value>("@quirks_mode")?
83
+ .is_nil();
84
+ // Parsed as the serializer will write it, as for fragments.
85
+ let noscript_as_text = document_object
86
+ .ivar_get::<_, Value>("@parse_noscript_content_as_text")?
87
+ .to_bool();
88
+ let options = Options {
89
+ // libxml2 keeps at most 100 errors for a parse.
90
+ max_errors: Some(100),
91
+ parse_noscript_content_as_text: noscript_as_text,
92
+ // The in-context parse of libxml2 takes no byte order mark.
93
+ keep_bom: true,
94
+ ..default_options(ruby)?
95
+ };
96
+
97
+ let context = node.with_arena(ruby, |arena, id| Context::for_node(arena, id, parsed))?;
98
+ let mut parser = FragmentParser::new(input, &context, &options);
99
+ run(|| parser.step())?;
100
+ let nodes = parser.finish().map_err(|error| limit_error(ruby, error))?;
101
+ // The current document of the node. Another thread may have changed
102
+ // it during the parse.
103
+ let document = node.document(ruby)?;
104
+ let (ids, parsed) = document::with_arena_mut(ruby, document, move |arena| nodes.import(arena))?;
105
+ let errors = document.ivar_get::<_, RArray>("@errors")?;
106
+ errors.concat(syntax_errors(ruby, parsed.errors, ruby.qnil().as_value())?)?;
107
+ node_set::wrap(ruby, document, ids)
108
+ }
109
+
110
+ /// Parses the input up to the end, so that the `finish` of the parser only ends
111
+ /// the tree. Between chunks, Ruby handles interrupts and can switch threads,
112
+ /// as between Ruby calls. The parser borrows no document, so nothing is locked
113
+ /// meanwhile.
114
+ fn run(mut step: impl FnMut() -> bool) -> Result<(), Error> {
115
+ while step() {
116
+ check_interrupts()?;
117
+ }
118
+ Ok(())
119
+ }
120
+
121
+ fn default_options(ruby: &Ruby) -> Result<Options, Error> {
122
+ static DEFAULTS: OnceLock<Options> = OnceLock::new();
123
+ if let Some(options) = DEFAULTS.get() {
124
+ return Ok(options.clone());
125
+ }
126
+ let module = ruby.get_inner(&HTML5EVER);
127
+ let default = |name: &str| module.const_get::<_, i32>(name).map(limit);
128
+ let options = Options {
129
+ max_attributes: default("DEFAULT_MAX_ATTRIBUTES")?,
130
+ max_errors: default("DEFAULT_MAX_ERRORS")?,
131
+ max_tree_depth: default("DEFAULT_MAX_TREE_DEPTH")?,
132
+ parse_noscript_content_as_text: false,
133
+ keep_bom: false,
134
+ };
135
+ Ok(DEFAULTS.get_or_init(|| options).clone())
136
+ }
137
+
138
+ /// The options of gumbo: three required keywords and one optional keyword, plus
139
+ /// `keep_bom` for the HTML4 names, which parse as libxml2 decodes.
140
+ fn options(keywords: RHash) -> Result<Options, Error> {
141
+ let keywords = get_kwargs::<_, (i32, i32, i32), (Option<Value>, Option<Value>), ()>(
142
+ keywords,
143
+ &["max_attributes", "max_errors", "max_tree_depth"],
144
+ &["parse_noscript_content_as_text", "keep_bom"],
145
+ )?;
146
+ let (max_attributes, max_errors, max_tree_depth) = keywords.required;
147
+ let (noscript_as_text, keep_bom) = keywords.optional;
148
+ Ok(Options {
149
+ max_attributes: limit(max_attributes),
150
+ max_errors: limit(max_errors),
151
+ max_tree_depth: limit(max_tree_depth),
152
+ parse_noscript_content_as_text: noscript_as_text.is_some_and(|value| value.to_bool()),
153
+ keep_bom: keep_bom.is_some_and(|value| value.to_bool()),
154
+ })
155
+ }
156
+
157
+ fn limit(value: i32) -> Option<usize> {
158
+ usize::try_from(value).ok()
159
+ }
160
+
161
+ /// The whole string, with zero bytes, as gumbo reads it.
162
+ fn input_bytes(ruby: &Ruby, input: Value) -> Result<Vec<u8>, Error> {
163
+ check_string(ruby, input)?;
164
+ let input = RString::from_value(input).expect("checked to be a String");
165
+ Ok(string_bytes(input))
166
+ }
167
+
168
+ fn limit_error(ruby: &Ruby, error: LimitError) -> Error {
169
+ Error::new(ruby.exception_arg_error(), error.to_string())
170
+ }
171
+
172
+ /// gumbo.c walks a node context through Ruby calls. lobzique reads the arena
173
+ /// of the node, so the context must be a lobzique node.
174
+ fn context_for(ruby: &Ruby, context: Value, document: Value) -> Result<Context, Error> {
175
+ if context.is_nil() {
176
+ return Ok(Context::new(ContextNamespace::Html, "body"));
177
+ }
178
+ if RString::from_value(context).is_some() {
179
+ return named_context(ruby, &c_string(context)?);
180
+ }
181
+ let node = Obj::<Node>::try_convert(context)?;
182
+ let context = node
183
+ .with_arena(ruby, Context::of_node)?
184
+ .map_err(|error| context_error(ruby, error))?;
185
+ Ok(context.with_quirks_mode(quirks_mode_for(ruby, document)?))
186
+ }
187
+
188
+ fn context_error(ruby: &Ruby, error: ContextError) -> Error {
189
+ match error {
190
+ ContextError::NoName => Error::new(
191
+ ruby.exception_type_error(),
192
+ "wrong argument type nil (expected String)",
193
+ ),
194
+ ContextError::UnknownNamespace(href) => Error::new(
195
+ ruby.exception_arg_error(),
196
+ format!("Unexpected namespace URI \"{href}\""),
197
+ ),
198
+ }
199
+ }
200
+
201
+ /// A context given by name: `"tr"`, `"svg:path"`, or `"svg"` and `"math"`,
202
+ /// which name their own namespace.
203
+ fn named_context(ruby: &Ruby, tag: &[u8]) -> Result<Context, Error> {
204
+ let tag = String::from_utf8_lossy(tag);
205
+ let (namespace, name) = match tag.split_once(':') {
206
+ Some((prefix, name)) => {
207
+ let namespace = match prefix.to_ascii_lowercase().as_str() {
208
+ "svg" => ContextNamespace::Svg,
209
+ "html" => ContextNamespace::Html,
210
+ "math" => ContextNamespace::MathMl,
211
+ _ => {
212
+ // The "%*s" of gumbo.c pads to the length of the prefix,
213
+ // so the whole name is shown.
214
+ let message = format!("Invalid context namespace '{tag}'");
215
+ return Err(Error::new(ruby.exception_arg_error(), message));
216
+ }
217
+ };
218
+ (namespace, name)
219
+ }
220
+ None if tag.eq_ignore_ascii_case("svg") => (ContextNamespace::Svg, &*tag),
221
+ None if tag.eq_ignore_ascii_case("math") => (ContextNamespace::MathMl, &*tag),
222
+ None => (ContextNamespace::Html, &*tag),
223
+ };
224
+ let form = namespace == ContextNamespace::Html && name.eq_ignore_ascii_case("form");
225
+ Ok(Context::new(namespace, name).with_form_ancestor(form))
226
+ }
227
+
228
+ /// For a node context: no quirks mode, unless the document of the fragment was
229
+ /// parsed. Then it is the quirks mode of its doctype.
230
+ fn quirks_mode_for(ruby: &Ruby, document: Value) -> Result<QuirksMode, Error> {
231
+ let document = document::unwrap(ruby, document)?;
232
+ let parsed = !document.ivar_get::<_, Value>("@quirks_mode")?.is_nil();
233
+ if !parsed {
234
+ return Ok(QuirksMode::NoQuirks);
235
+ }
236
+ document::with_arena(ruby, document, html5::doctype_quirks_mode)
237
+ }
238
+
239
+ /// The `add_errors` of gumbo.c: one `XML::SyntaxError` for each parse error.
240
+ /// Set only if there were any.
241
+ fn add_errors(
242
+ ruby: &Ruby,
243
+ target: Obj<Node>,
244
+ errors: Vec<ParseError>,
245
+ file: Value,
246
+ ) -> Result<(), Error> {
247
+ if errors.is_empty() {
248
+ return Ok(());
249
+ }
250
+ target.ivar_set("@errors", syntax_errors(ruby, errors, file)?)
251
+ }
252
+
253
+ /// The errors of html5ever have no gumbo error code (gumbo.c puts it in `str1`)
254
+ /// and no column.
255
+ fn syntax_errors(ruby: &Ruby, errors: Vec<ParseError>, file: Value) -> Result<RArray, Error> {
256
+ let class: RClass = ruby.get_inner(&XML).const_get("SyntaxError")?;
257
+ let array = ruby.ary_new_capa(errors.len());
258
+ for error in errors {
259
+ let error = XmlError {
260
+ domain: 1, // XML_FROM_PARSER
261
+ code: 1, // XML_ERR_INTERNAL_ERROR
262
+ message: &error.message,
263
+ level: 2, // XML_ERR_ERROR
264
+ file,
265
+ line: error.line,
266
+ str1: None,
267
+ };
268
+ array.push(syntax_error::wrap(ruby, class, &error)?)?;
269
+ }
270
+ Ok(array)
271
+ }
272
+
273
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
274
+ let module = ruby.get_inner(&HTML5EVER);
275
+ module.define_singleton_method("parse", function!(parse, -1))?;
276
+ module.define_singleton_method("fragment", function!(fragment, -1))?;
277
+ Ok(())
278
+ }
@@ -0,0 +1,45 @@
1
+ //! Ruby bindings: the native classes and methods that the C extension
2
+ //! of Nokogiri defines, with the same names. Each is a thin call
3
+ //! into lobzique-core. Files mirror `lib/lobzique/`. See ARCHITECTURE.md.
4
+ //!
5
+ //! Code that borrows an arena must not reach Ruby (ARCHITECTURE.md, "Memory
6
+ //! model"). The borrow closures must be `Send`. The lints here
7
+ //! and in `clippy.toml` close the known ways around that: `unsafe` only
8
+ //! in `support`, and no magnus API that fetches a Ruby handle itself.
9
+ #![deny(unsafe_code, deprecated)]
10
+
11
+ mod css;
12
+ mod html4;
13
+ mod html5;
14
+ mod html5ever;
15
+ mod support;
16
+ mod xml;
17
+
18
+ use magnus::{value::Lazy, Error, Module, RModule, Ruby};
19
+
20
+ // The root is named only through the `Lobzique` constant, which a facade can
21
+ // point at its own module (plan.md decision 1).
22
+ pub static LOBZIQUE: Lazy<RModule> = Lazy::new(|ruby| ruby.define_module("Lobzique").unwrap());
23
+ pub static XML: Lazy<RModule> =
24
+ Lazy::new(|ruby| ruby.get_inner(&LOBZIQUE).define_module("XML").unwrap());
25
+ pub static HTML4: Lazy<RModule> =
26
+ Lazy::new(|ruby| ruby.get_inner(&LOBZIQUE).define_module("HTML4").unwrap());
27
+ pub static HTML5: Lazy<RModule> =
28
+ Lazy::new(|ruby| ruby.get_inner(&LOBZIQUE).define_module("HTML5").unwrap());
29
+ pub static CSS: Lazy<RModule> =
30
+ Lazy::new(|ruby| ruby.get_inner(&LOBZIQUE).define_module("CSS").unwrap());
31
+ pub static HTML5EVER: Lazy<RModule> = Lazy::new(|ruby| {
32
+ ruby.get_inner(&LOBZIQUE)
33
+ .define_module("Html5ever")
34
+ .unwrap()
35
+ });
36
+
37
+ #[magnus::init]
38
+ fn init(ruby: &Ruby) -> Result<(), Error> {
39
+ xml::init(ruby)?;
40
+ html4::init(ruby)?;
41
+ html5::init(ruby)?;
42
+ html5ever::init(ruby)?;
43
+ css::init(ruby)?;
44
+ Ok(())
45
+ }