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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +5 -0
- data/Cargo.lock +520 -0
- data/Cargo.toml +11 -0
- data/LICENSE-NOKOGIRI.md +15 -0
- data/LICENSE.txt +21 -0
- data/README.md +144 -0
- data/crates/lobzique-core/Cargo.toml +14 -0
- data/crates/lobzique-core/src/css/mod.rs +127 -0
- data/crates/lobzique-core/src/css/parser.rs +805 -0
- data/crates/lobzique-core/src/css/tables.rs +282 -0
- data/crates/lobzique-core/src/css/tests.rs +476 -0
- data/crates/lobzique-core/src/css/tokenizer.rs +215 -0
- data/crates/lobzique-core/src/css/translate.rs +806 -0
- data/crates/lobzique-core/src/css/write.rs +370 -0
- data/crates/lobzique-core/src/dom/attribute.rs +144 -0
- data/crates/lobzique-core/src/dom/check.rs +160 -0
- data/crates/lobzique-core/src/dom/copy.rs +229 -0
- data/crates/lobzique-core/src/dom/mod.rs +298 -0
- data/crates/lobzique-core/src/dom/namespace.rs +134 -0
- data/crates/lobzique-core/src/dom/node.rs +129 -0
- data/crates/lobzique-core/src/dom/path.rs +116 -0
- data/crates/lobzique-core/src/dom/reparent.rs +308 -0
- data/crates/lobzique-core/src/dom/tests.rs +1057 -0
- data/crates/lobzique-core/src/dom/text.rs +159 -0
- data/crates/lobzique-core/src/dom/tree.rs +446 -0
- data/crates/lobzique-core/src/html5/mod.rs +28 -0
- data/crates/lobzique-core/src/html5/parse.rs +838 -0
- data/crates/lobzique-core/src/html5/serialize.rs +181 -0
- data/crates/lobzique-core/src/html5/tests.rs +548 -0
- data/crates/lobzique-core/src/lib.rs +12 -0
- data/crates/lobzique-core/src/work.rs +26 -0
- data/crates/lobzique-core/src/xml/mod.rs +8 -0
- data/crates/lobzique-core/src/xml/serialize.rs +681 -0
- data/crates/lobzique-core/src/xml/tests.rs +174 -0
- data/crates/lobzique-core/src/xpath/ast.rs +415 -0
- data/crates/lobzique-core/src/xpath/chars.rs +139 -0
- data/crates/lobzique-core/src/xpath/eval.rs +1305 -0
- data/crates/lobzique-core/src/xpath/mod.rs +118 -0
- data/crates/lobzique-core/src/xpath/parse.rs +729 -0
- data/crates/lobzique-core/src/xpath/tests.rs +921 -0
- data/ext/lobzique/Cargo.toml +22 -0
- data/ext/lobzique/build.rs +5 -0
- data/ext/lobzique/clippy.toml +15 -0
- data/ext/lobzique/extconf.rb +6 -0
- data/ext/lobzique/src/css/mod.rs +9 -0
- data/ext/lobzique/src/css/parser.rs +44 -0
- data/ext/lobzique/src/css/selector.rs +101 -0
- data/ext/lobzique/src/html4/document.rs +31 -0
- data/ext/lobzique/src/html4/mod.rs +7 -0
- data/ext/lobzique/src/html5/mod.rs +16 -0
- data/ext/lobzique/src/html5ever.rs +278 -0
- data/ext/lobzique/src/lib.rs +45 -0
- data/ext/lobzique/src/support.rs +156 -0
- data/ext/lobzique/src/xml/attr.rs +27 -0
- data/ext/lobzique/src/xml/cdata.rs +33 -0
- data/ext/lobzique/src/xml/comment.rs +34 -0
- data/ext/lobzique/src/xml/document.rs +199 -0
- data/ext/lobzique/src/xml/document_fragment.rs +27 -0
- data/ext/lobzique/src/xml/dtd.rs +37 -0
- data/ext/lobzique/src/xml/mod.rs +44 -0
- data/ext/lobzique/src/xml/namespace.rs +56 -0
- data/ext/lobzique/src/xml/node.rs +944 -0
- data/ext/lobzique/src/xml/node_set.rs +20 -0
- data/ext/lobzique/src/xml/syntax_error.rs +33 -0
- data/ext/lobzique/src/xml/text.rs +44 -0
- data/ext/lobzique/src/xml/xpath_context.rs +305 -0
- data/lib/lobzique/action_text.rb +29 -0
- data/lib/lobzique/class_resolver.rb +33 -0
- data/lib/lobzique/css/selector_cache.rb +36 -0
- data/lib/lobzique/css/syntax_error.rb +12 -0
- data/lib/lobzique/css/xpath_visitor.rb +60 -0
- data/lib/lobzique/css.rb +57 -0
- data/lib/lobzique/extension.rb +31 -0
- data/lib/lobzique/html.rb +14 -0
- data/lib/lobzique/html4/document.rb +235 -0
- data/lib/lobzique/html4/document_fragment.rb +75 -0
- data/lib/lobzique/html4/encoding_reader.rb +374 -0
- data/lib/lobzique/html4.rb +35 -0
- data/lib/lobzique/html5/document.rb +106 -0
- data/lib/lobzique/html5/document_fragment.rb +113 -0
- data/lib/lobzique/html5/node.rb +66 -0
- data/lib/lobzique/html5.rb +92 -0
- data/lib/lobzique/html5ever.rb +14 -0
- data/lib/lobzique/rails_dom_testing.rb +95 -0
- data/lib/lobzique/sanitizer/concerns.rb +110 -0
- data/lib/lobzique/sanitizer/document.rb +14 -0
- data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
- data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
- data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
- data/lib/lobzique/sanitizer.rb +96 -0
- data/lib/lobzique/syntax_error.rb +8 -0
- data/lib/lobzique/version.rb +6 -0
- data/lib/lobzique/xml/attr.rb +23 -0
- data/lib/lobzique/xml/cdata.rb +13 -0
- data/lib/lobzique/xml/character_data.rb +11 -0
- data/lib/lobzique/xml/document.rb +149 -0
- data/lib/lobzique/xml/document_fragment.rb +109 -0
- data/lib/lobzique/xml/dtd.rb +28 -0
- data/lib/lobzique/xml/namespace.rb +19 -0
- data/lib/lobzique/xml/node/save_options.rb +52 -0
- data/lib/lobzique/xml/node.rb +629 -0
- data/lib/lobzique/xml/node_set.rb +329 -0
- data/lib/lobzique/xml/parse_options.rb +89 -0
- data/lib/lobzique/xml/pp/character_data.rb +22 -0
- data/lib/lobzique/xml/pp/node.rb +73 -0
- data/lib/lobzique/xml/pp.rb +6 -0
- data/lib/lobzique/xml/searchable.rb +123 -0
- data/lib/lobzique/xml/syntax_error.rb +77 -0
- data/lib/lobzique/xml/text.rb +14 -0
- data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
- data/lib/lobzique/xml/xpath.rb +16 -0
- data/lib/lobzique/xml/xpath_context.rb +27 -0
- data/lib/lobzique/xml.rb +22 -0
- data/lib/lobzique.rb +15 -0
- metadata +177 -0
data/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# lobzique
|
|
2
|
+
|
|
3
|
+
This will be an implementation of a subset of Nokogiri that used by Rails and related libraries with a Rust extension in place of libxml.
|
|
4
|
+
|
|
5
|
+
## Sanitizing in Rails
|
|
6
|
+
|
|
7
|
+
`Lobzique::Sanitizer` is a rails-html-sanitizer vendor: `sanitize`,
|
|
8
|
+
`strip_tags`, `strip_links` and Action Text parse, scrub and serialize with
|
|
9
|
+
lobzique, so user HTML never reaches libxml2. Its output matches
|
|
10
|
+
`Rails::HTML5::Sanitizer`'s byte for byte, except for one known gap (below).
|
|
11
|
+
|
|
12
|
+
```ruby
|
|
13
|
+
# config/application.rb, after require "rails/all"
|
|
14
|
+
require "lobzique/sanitizer"
|
|
15
|
+
|
|
16
|
+
config.action_view.sanitizer_vendor = Lobzique::Sanitizer
|
|
17
|
+
config.action_text.sanitizer_vendor = Lobzique::Sanitizer
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
It needs `loofah` and `rails-html-sanitizer`, which every Rails app already
|
|
21
|
+
has, and raises at `require` on a rails-html-sanitizer outside 1.7.1–1.7.x:
|
|
22
|
+
the vendor is built from that gem's internal modules. Loofah's and Rails'
|
|
23
|
+
scrubbers run unchanged, and so do app scrubbers passed with `scrubber:` or
|
|
24
|
+
set as `ActionText::ContentHelper.scrubber`, with these limits:
|
|
25
|
+
|
|
26
|
+
- A scrubber that checks `is_a?(Nokogiri::XML::Element)` (or another
|
|
27
|
+
Nokogiri class) or builds nodes with `Nokogiri::XML::Text.new` and the like fails on
|
|
28
|
+
lobzique nodes. Build nodes through `node.document` (`create_element`,
|
|
29
|
+
`create_text_node`) or with `node.add_next_sibling("<b>…</b>")`.
|
|
30
|
+
- The vendor is HTML5 only. An app on `load_defaults` below 7.1, whose
|
|
31
|
+
default vendor is `Rails::HTML4::Sanitizer`, sanitizes with an HTML5
|
|
32
|
+
parser after switching.
|
|
33
|
+
- The parser keeps markup inside `<select>`, as the 2025 HTML standard's
|
|
34
|
+
customizable select does; Nokogiri's parser, and browsers without
|
|
35
|
+
customizable select, drop or move it. So output differs from
|
|
36
|
+
`Rails::HTML5` when `select` is in the allowed tags. The text of `style`,
|
|
37
|
+
`xmp`, `iframe`, `noembed`, `noframes` and `plaintext` inside a `select` is
|
|
38
|
+
escaped, as Loofah escapes it on libxml2, so the output is safe with either
|
|
39
|
+
set of rules.
|
|
40
|
+
- Loofah's `text` and `to_text` and its document-level comment removal
|
|
41
|
+
aren't ported; Rails' sanitizers call neither.
|
|
42
|
+
|
|
43
|
+
## Action Text
|
|
44
|
+
|
|
45
|
+
With the sanitizer vendor above, Action Text still parses stored rich text
|
|
46
|
+
with Nokogiri to find attachments, convert Trix markup and build plain text.
|
|
47
|
+
To parse it with lobzique as well:
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
# config/application.rb, after require "rails/all"
|
|
51
|
+
require "lobzique/action_text"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`ActionText::Content#fragment.source` and the nodes passed to
|
|
55
|
+
`Fragment#replace` blocks are then lobzique nodes, with the limits listed
|
|
56
|
+
for scrubbers above. Stored content reads the same as on
|
|
57
|
+
`Nokogiri::HTML5`, apart from the `<select>` difference above.
|
|
58
|
+
|
|
59
|
+
## Tests: assert_dom and parsed_body
|
|
60
|
+
|
|
61
|
+
rails-dom-testing parses HTML for `assert_dom` (`assert_select`),
|
|
62
|
+
`assert_dom_equal`, `css_select`, `response.parsed_body`, and
|
|
63
|
+
`rendered.html` in view tests. To parse it with lobzique:
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
# test/test_helper.rb, after require "rails/test_help"
|
|
67
|
+
require "lobzique/rails_dom_testing"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Wherever rails-dom-testing would use `Nokogiri::HTML5`, it then uses
|
|
71
|
+
lobzique: on `load_defaults` 7.1 and later, or with
|
|
72
|
+
`config.dom_testing_default_html_version = :html5`. `:html4` stays on
|
|
73
|
+
Nokogiri, and so do XML responses. It raises at `require` on a
|
|
74
|
+
rails-dom-testing outside 2.3.x, because it replaces one of that gem's
|
|
75
|
+
private methods. Limits:
|
|
76
|
+
|
|
77
|
+
- Selected elements, `parsed_body` and `rendered.html` are lobzique
|
|
78
|
+
objects, so a test asserting `Nokogiri::…` classes fails.
|
|
79
|
+
- An invalid selector raises `Lobzique::CSS::SyntaxError`, not
|
|
80
|
+
`Nokogiri::CSS::SyntaxError`.
|
|
81
|
+
|
|
82
|
+
## Development
|
|
83
|
+
|
|
84
|
+
`bundle exec rake` compiles the extension, runs the tests and lints.
|
|
85
|
+
|
|
86
|
+
Library code goes in `crates/lobzique-core`, which must not depend on Ruby, so the checks below can run it without a Ruby VM. `ext/lobzique` holds only the Ruby bindings.
|
|
87
|
+
|
|
88
|
+
The CI workflow runs these checks on every PR and daily. Locally they need nightly Rust (`rustup toolchain install nightly --component miri,rust-src`) `cargo install cargo-fuzz` and `cargo install cargo-deny`.
|
|
89
|
+
|
|
90
|
+
| Check | Locally | Catches |
|
|
91
|
+
| --- | --- | --- |
|
|
92
|
+
| Miri | `cargo +nightly miri test -p lobzique-core` | undefined behavior in unsafe code, ours or our dependencies' |
|
|
93
|
+
| ASan (Rust) | `RUSTFLAGS=-Zsanitizer=address cargo +nightly test -Zbuild-std --target aarch64-apple-darwin -p lobzique-core` | memory errors in the core crate |
|
|
94
|
+
| ASan (Ruby) | CI only: ASan builds of Ruby exist for Linux x64 only | memory errors in the extension and at the Ruby boundary |
|
|
95
|
+
| GC.stress | `bundle exec rake test:gc_stress` | Ruby objects that Rust holds without the GC knowing |
|
|
96
|
+
| Fuzzing | `cargo +nightly fuzz run <target>` | panics and failed assertions on arbitrary input |
|
|
97
|
+
| cargo-deny | `cargo deny check` | dependencies with RustSec advisories (vulnerable, unmaintained, unsound or yanked), disallowed licenses, duplicate versions, crates from outside crates.io |
|
|
98
|
+
| Fuzzing the Ruby API | `bundle exec rake fuzz:ruby` (Linux, see below) | memory errors in the extension, GC and compaction mistakes, and errors Nokogiri doesn't raise, on fuzzed sequences of Ruby calls |
|
|
99
|
+
|
|
100
|
+
`rake test:gc_stress` and `rake fuzz:ruby` leave a special build in `lib/`; `rake compile` replaces it. `rake test:stress` runs GC.stress on whatever build is in `lib/` (the ASan job's, for one), each test file in its own process, `STRESS_JOBS` at a time.
|
|
101
|
+
|
|
102
|
+
Every entry point that takes untrusted input gets a fuzz target in `fuzz/fuzz_targets/`, plus a `[[bin]]` entry in `fuzz/Cargo.toml`. CI fuzzes each target for 60 seconds on PRs; for a long run, dispatch the Fuzz workflow (`gh workflow run fuzz.yml -f seconds=7200`). A target's libFuzzer dictionary goes in `fuzz/<target>.dict`. CI also passes `-timeout=10 -malloc_limit_mb=512`, so a slow input or a single huge allocation fails. Slowness under the timeout is `html5_scaling`'s job: it repeats its input and fails if the work the core counts under `cfg(fuzzing)` (`lobzique_core::work`) grows faster than linearly in the input times the tree's depth.
|
|
103
|
+
|
|
104
|
+
The Rust targets never reach the bindings or the Ruby layer. `fuzz/ruby/api.rb` does: with [Ruzzy](https://github.com/trailofbits/ruzzy), it runs fuzzed sequences of Ruby calls (editing, copying, searching, scrubbing and serializing nodes, XPath functions that edit the tree, GC and compaction in between) on an extension built with ASan and coverage instrumentation. It fails on a crash, an ASan report or a panic; on an exception that Nokogiri doesn't raise on the same calls from the same tree, apart from the departures in `ARCHITECTURE.md`; and on sanitized output that isn't idempotent or doesn't survive a reparse where Rails::HTML5's does. Nokogiri runs in a child process, only to judge an input; trees it builds differently (as `known.yml` lists) aren't compared from where they differ, and neither are the sanitizer's properties on markup it parses differently, though a sanitizer exception still is. Ruzzy is Linux-only and needs clang with its sanitizer runtimes (`libclang-rt-18-dev` on Ubuntu) and nightly Rust:
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
bundle config set --local with fuzz
|
|
108
|
+
CC=clang CXX=clang++ LDSHARED="clang -shared" LDSHAREDXX="clang++ -shared" \
|
|
109
|
+
MAKE="make --environment-overrides" bundle install
|
|
110
|
+
bundle exec rake fuzz:ruby FUZZOPTS="-max_total_time=600 -fork=4"
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Failing inputs go to `fuzz/artifacts/ruby_api/`. To run one again, after `rake fuzz:ruby` has built the extension:
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
LD_PRELOAD=$(ruby -e 'require "ruzzy"; print Ruzzy::ASAN_PATH') ASAN_OPTIONS=detect_leaks=0:use_sigaltstack=0 \
|
|
117
|
+
bundle exec fuzz/ruby/trace.rb fuzz/artifacts/ruby_api/crash-...
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
CI runs it next to the Rust targets.
|
|
121
|
+
|
|
122
|
+
### Differential test against Nokogiri::HTML5
|
|
123
|
+
|
|
124
|
+
`script/differential` parses the same inputs with Nokogiri (a development dependency) and with lobzique and compares `to_html` and the tree.
|
|
125
|
+
|
|
126
|
+
| Corpus | Command | When CI runs it |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| fixtures: WPT, html5lib, DOMPurify and asset inputs from `test/fixtures` | `script/differential` | every push |
|
|
129
|
+
| small hand-written cases in `test/differential/cases.yml` | `script/differential` | every push |
|
|
130
|
+
| a pinned Common Crawl sample (~3,100 pages) | `script/fetch_crawl`, then `script/differential --corpus crawl` | weekly |
|
|
131
|
+
|
|
132
|
+
`--mode sanitize` sends the inputs from the fixtures (DOMPurify, the WPT sanitizer and tree-construction tests, Loofah's sanitizer data, html5lib) or the crawl through `Rails::HTML5`'s sanitizers and through `Lobzique::Sanitizer`, in several configurations. It compares the output, the output sanitized again, and the output parsed and serialized again. Rails::HTML5 itself isn't idempotent on every input, so lobzique has to break these properties exactly where it does; the report counts both. CI runs it next to the parse mode.
|
|
133
|
+
|
|
134
|
+
`--mode action_text` reads the sanitize mode's inputs, and the markup in Action Text's tests, as `ActionText::Content` with Action Text's document classes set to Nokogiri's and then to lobzique's, and compares `to_html`, `to_trix_html` (and what saving it back stores), `to_plain_text`, the attachments, galleries and links. CI runs it next to the other modes.
|
|
135
|
+
|
|
136
|
+
Crawled pages aren't committed: `test/differential/crawl.yml` pins byte ranges of WARC files with their SHA-256, and `script/fetch_crawl` downloads them into `tmp/crawl/`. A difference found on a crawled page becomes a small case in `cases.yml`. Accepted differences go in `test/differential/known.yml` with a reason.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
141
|
+
|
|
142
|
+
## Code of Conduct
|
|
143
|
+
|
|
144
|
+
Everyone interacting in the Lobzique project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/lobzique/blob/main/CODE_OF_CONDUCT.md).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "lobzique-core"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
authors = ["Jury Razumau <mail@razumau.net>"]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
publish = false
|
|
8
|
+
|
|
9
|
+
[dependencies]
|
|
10
|
+
html5ever = "0.40"
|
|
11
|
+
|
|
12
|
+
[lints.rust]
|
|
13
|
+
# cargo-fuzz builds with --cfg fuzzing, which turns on `work` counting
|
|
14
|
+
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(fuzzing)"] }
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
//! Nokogiri's CSS dialect, compiled to the XPath that the visitor of Nokogiri
|
|
2
|
+
//! would write for it (ARCHITECTURE.md). The tokenizer, the tables
|
|
3
|
+
//! of the parser and the visitor are ported from Nokogiri. A selector thus
|
|
4
|
+
//! selects what it selects there, quirks included: `a:first` is the first
|
|
5
|
+
//! `a` among its siblings, `node.css("div p")` finds only `div`s inside `node`,
|
|
6
|
+
//! and `[x^=""]` matches elements without `x`.
|
|
7
|
+
|
|
8
|
+
mod parser;
|
|
9
|
+
mod tables;
|
|
10
|
+
#[cfg(test)]
|
|
11
|
+
mod tests;
|
|
12
|
+
mod tokenizer;
|
|
13
|
+
mod translate;
|
|
14
|
+
mod write;
|
|
15
|
+
|
|
16
|
+
use crate::xpath::{self, Expr, Query};
|
|
17
|
+
use std::fmt;
|
|
18
|
+
use translate::{Failure, Translator};
|
|
19
|
+
|
|
20
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
21
|
+
pub struct SyntaxError(pub String);
|
|
22
|
+
|
|
23
|
+
impl fmt::Display for SyntaxError {
|
|
24
|
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
25
|
+
f.write_str(&self.0)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl std::error::Error for SyntaxError {}
|
|
30
|
+
|
|
31
|
+
/// The XPath prefixes that Nokogiri puts before a selector: the implied
|
|
32
|
+
/// contexts of each searchable class.
|
|
33
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
34
|
+
pub enum Prefix {
|
|
35
|
+
Global,
|
|
36
|
+
Subtree,
|
|
37
|
+
Current,
|
|
38
|
+
Root,
|
|
39
|
+
/// `self::`, which node sets and fragments add to `.//`.
|
|
40
|
+
Self_,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl Prefix {
|
|
44
|
+
pub fn parse(prefix: &str) -> Option<Prefix> {
|
|
45
|
+
Some(match prefix {
|
|
46
|
+
"//" => Prefix::Global,
|
|
47
|
+
".//" => Prefix::Subtree,
|
|
48
|
+
"./" => Prefix::Current,
|
|
49
|
+
"/" => Prefix::Root,
|
|
50
|
+
"self::" => Prefix::Self_,
|
|
51
|
+
_ => return None,
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#[derive(Clone, Debug)]
|
|
57
|
+
pub struct Options {
|
|
58
|
+
/// Names without a prefix match in any namespace, as for HTML5 documents.
|
|
59
|
+
pub html: bool,
|
|
60
|
+
pub builtins: bool,
|
|
61
|
+
/// The namespace bindings have an `xmlns` key. It is the default namespace
|
|
62
|
+
/// for names without a prefix (outside HTML).
|
|
63
|
+
pub default_namespace: bool,
|
|
64
|
+
pub prefixes: Vec<Prefix>,
|
|
65
|
+
/// Only the first selector of a list, as `Searchable#>` takes it. The
|
|
66
|
+
/// others are still translated, so their syntax errors are raised.
|
|
67
|
+
pub first_only: bool,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// A compiled selector list. `query` holds the error that libxml2 would raise
|
|
71
|
+
/// for the XPath that Nokogiri builds. It appears only on evaluation.
|
|
72
|
+
#[derive(Debug)]
|
|
73
|
+
pub struct Selector {
|
|
74
|
+
pub query: Result<Query, xpath::Error>,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pub fn compile(rule: &str, options: &Options) -> Result<Selector, SyntaxError> {
|
|
78
|
+
if rule.is_empty() {
|
|
79
|
+
return Err(SyntaxError("empty CSS selector".into()));
|
|
80
|
+
}
|
|
81
|
+
let selectors = parser::parse(rule)?;
|
|
82
|
+
let mut translator = Translator::new(options);
|
|
83
|
+
let mut paths = Vec::new();
|
|
84
|
+
let mut invalid = false;
|
|
85
|
+
for prefix in &options.prefixes {
|
|
86
|
+
for (index, selector) in selectors.iter().enumerate() {
|
|
87
|
+
// `.first` comes after the visitor has translated every selector.
|
|
88
|
+
let kept = index == 0 || !options.first_only;
|
|
89
|
+
match translator.selector(selector, *prefix) {
|
|
90
|
+
Ok(path) if kept => paths.push(path),
|
|
91
|
+
Err(Failure::Syntax(error)) => return Err(error),
|
|
92
|
+
Err(Failure::Invalid) if kept => invalid = true,
|
|
93
|
+
Ok(_) | Err(Failure::Invalid) => {}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let query = if invalid {
|
|
98
|
+
Err(xpath::Error::InvalidExpression)
|
|
99
|
+
} else {
|
|
100
|
+
let paths = paths.into_iter().map(Expr::Path).collect();
|
|
101
|
+
Ok(Query::new(Expr::Union(paths), translator.functions))
|
|
102
|
+
};
|
|
103
|
+
Ok(Selector { query })
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#[derive(Clone, Debug)]
|
|
107
|
+
pub struct Visitor {
|
|
108
|
+
pub builtins: bool,
|
|
109
|
+
/// Names without a prefix match in any namespace. Unlike [`Options::html`],
|
|
110
|
+
/// not for HTML4: the HTML4 documents of Nokogiri have no namespaces.
|
|
111
|
+
pub html5: bool,
|
|
112
|
+
pub default_namespace: bool,
|
|
113
|
+
pub prefix: String,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// `CSS::Parser#xpath_for`: an XPath string for each selector of the list,
|
|
117
|
+
/// as the visitor of Nokogiri writes it.
|
|
118
|
+
pub fn xpath_for(rule: &str, visitor: &Visitor) -> Result<Vec<String>, SyntaxError> {
|
|
119
|
+
if rule.is_empty() {
|
|
120
|
+
return Err(SyntaxError("empty CSS selector".into()));
|
|
121
|
+
}
|
|
122
|
+
let writer = write::Writer::new(visitor);
|
|
123
|
+
parser::parse(rule)?
|
|
124
|
+
.iter()
|
|
125
|
+
.map(|selector| writer.selector(selector))
|
|
126
|
+
.collect()
|
|
127
|
+
}
|