@dvaji/cheerox 0.0.0-stage → 0.1.2

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 (268) hide show
  1. package/CONTRIBUTING.md +74 -0
  2. package/Cargo.lock +1091 -0
  3. package/Cargo.toml +47 -0
  4. package/LICENSE +21 -0
  5. package/README.md +121 -2
  6. package/RELEASING.md +114 -0
  7. package/THIRD_PARTY_NOTICES.md +7581 -0
  8. package/build.rs +3 -0
  9. package/cheerox.darwin-arm64.node +0 -0
  10. package/cheerox.darwin-x64.node +0 -0
  11. package/cheerox.linux-arm64-gnu.node +0 -0
  12. package/cheerox.linux-arm64-musl.node +0 -0
  13. package/cheerox.linux-x64-gnu.node +0 -0
  14. package/cheerox.linux-x64-musl.node +0 -0
  15. package/cheerox.win32-arm64-msvc.node +0 -0
  16. package/cheerox.win32-x64-msvc.node +0 -0
  17. package/dist/cheerio-compat-BKkfJEAr.mjs +1648 -0
  18. package/dist/cheerio-compat-BKkfJEAr.mjs.map +1 -0
  19. package/dist/cheerio-compat-DRLPzBdX.d.mts +88 -0
  20. package/dist/cheerio-compat-DRsINTwV.d.cts +88 -0
  21. package/dist/cheerio-compat-DRsINTwV.d.ts +88 -0
  22. package/dist/cheerio-compat-DcnYK9OB.cjs +1719 -0
  23. package/dist/cheerio-compat-DcnYK9OB.cjs.map +1 -0
  24. package/dist/cheerio-compat.cjs +18 -0
  25. package/dist/cheerio-compat.d.cts +2 -0
  26. package/dist/cheerio-compat.d.mts +2 -0
  27. package/dist/cheerio-compat.d.ts +2 -0
  28. package/dist/cheerio-compat.mjs +1 -0
  29. package/dist/index.cjs +13 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +28 -0
  32. package/dist/index.d.mts +6 -0
  33. package/dist/index.d.ts +28 -0
  34. package/dist/index.mjs +53 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/dist/legacy-parse.cjs +5 -0
  37. package/dist/legacy-parse.d.mts +8 -0
  38. package/dist/legacy-parse.d.ts +7 -0
  39. package/dist/legacy-parse.mjs +1 -0
  40. package/dist/modern-B7hyW4cI.d.cts +102 -0
  41. package/dist/modern-B7hyW4cI.d.ts +102 -0
  42. package/dist/modern-CHQGP0Yt.cjs +2858 -0
  43. package/dist/modern-CHQGP0Yt.cjs.map +1 -0
  44. package/dist/modern-CJvSD_y5.d.mts +102 -0
  45. package/dist/modern-CvXcTn82.mjs +2769 -0
  46. package/dist/modern-CvXcTn82.mjs.map +1 -0
  47. package/dist/modern.cjs +19 -0
  48. package/dist/modern.d.cts +3 -0
  49. package/dist/modern.d.mts +3 -0
  50. package/dist/modern.d.ts +3 -0
  51. package/dist/modern.mjs +3 -0
  52. package/dist/nodes-jbWWhssj.cjs +4210 -0
  53. package/dist/nodes-jbWWhssj.cjs.map +1 -0
  54. package/dist/nodes-sYxb5qyZ.mjs +3803 -0
  55. package/dist/nodes-sYxb5qyZ.mjs.map +1 -0
  56. package/dist/slim.cjs +16 -0
  57. package/dist/slim.cjs.map +1 -0
  58. package/dist/slim.d.cts +6 -0
  59. package/dist/slim.d.mts +6 -0
  60. package/dist/slim.d.ts +6 -0
  61. package/dist/slim.mjs +12 -0
  62. package/dist/slim.mjs.map +1 -0
  63. package/dist/types-CA01Zg3r.d.cts +526 -0
  64. package/dist/types-CA01Zg3r.d.mts +526 -0
  65. package/dist/types-CA01Zg3r.d.ts +526 -0
  66. package/dist/utils.cjs +31 -0
  67. package/dist/utils.cjs.map +1 -0
  68. package/dist/utils.d.cts +8 -0
  69. package/dist/utils.d.mts +8 -0
  70. package/dist/utils.d.ts +8 -0
  71. package/dist/utils.mjs +25 -0
  72. package/dist/utils.mjs.map +1 -0
  73. package/native/src/arena.rs +2109 -0
  74. package/native/src/attributes.rs +946 -0
  75. package/native/src/codec.rs +298 -0
  76. package/native/src/diagnostics.rs +1249 -0
  77. package/native/src/document_order.rs +711 -0
  78. package/native/src/extraction.rs +321 -0
  79. package/native/src/gc.rs +175 -0
  80. package/native/src/hook_sink.rs +801 -0
  81. package/native/src/hook_stream.rs +513 -0
  82. package/native/src/id_hash.rs +42 -0
  83. package/native/src/immutable.rs +333 -0
  84. package/native/src/lib.rs +4120 -0
  85. package/native/src/location.rs +392 -0
  86. package/native/src/markup_tokenizer.rs +668 -0
  87. package/native/src/runtime.rs +368 -0
  88. package/native/src/selector.rs +1596 -0
  89. package/native/src/sink.rs +274 -0
  90. package/native/src/snapshot.rs +672 -0
  91. package/native/src/stream.rs +334 -0
  92. package/native/src/tokenizer.rs +581 -0
  93. package/native/src/tracker.rs +232 -0
  94. package/native/vendor/README.md +35 -0
  95. package/native/vendor/html5ever-0.35.0/.cargo_vcs_info.json +6 -0
  96. package/native/vendor/html5ever-0.35.0/Cargo.lock +828 -0
  97. package/native/vendor/html5ever-0.35.0/Cargo.toml +85 -0
  98. package/native/vendor/html5ever-0.35.0/LICENSE-APACHE +201 -0
  99. package/native/vendor/html5ever-0.35.0/LICENSE-MIT +25 -0
  100. package/native/vendor/html5ever-0.35.0/README.md +60 -0
  101. package/native/vendor/html5ever-0.35.0/benches/html5ever.rs +86 -0
  102. package/native/vendor/html5ever-0.35.0/data/bench/lipsum-zh.html +19 -0
  103. package/native/vendor/html5ever-0.35.0/data/bench/lipsum.html +40 -0
  104. package/native/vendor/html5ever-0.35.0/data/bench/medium-fragment.html +24 -0
  105. package/native/vendor/html5ever-0.35.0/data/bench/small-fragment.html +7 -0
  106. package/native/vendor/html5ever-0.35.0/data/bench/strong.html +1 -0
  107. package/native/vendor/html5ever-0.35.0/data/bench/tiny-fragment.html +1 -0
  108. package/native/vendor/html5ever-0.35.0/examples/arena.rs +356 -0
  109. package/native/vendor/html5ever-0.35.0/examples/capi/tokenize.c +74 -0
  110. package/native/vendor/html5ever-0.35.0/examples/noop-tokenize.rs +47 -0
  111. package/native/vendor/html5ever-0.35.0/examples/noop-tree-builder.rs +132 -0
  112. package/native/vendor/html5ever-0.35.0/examples/print-tree-actions.rs +185 -0
  113. package/native/vendor/html5ever-0.35.0/examples/tokenize.rs +111 -0
  114. package/native/vendor/html5ever-0.35.0/src/driver.rs +148 -0
  115. package/native/vendor/html5ever-0.35.0/src/lib.rs +30 -0
  116. package/native/vendor/html5ever-0.35.0/src/macros.rs +34 -0
  117. package/native/vendor/html5ever-0.35.0/src/serialize/mod.rs +255 -0
  118. package/native/vendor/html5ever-0.35.0/src/tokenizer/char_ref/mod.rs +530 -0
  119. package/native/vendor/html5ever-0.35.0/src/tokenizer/interface.rs +99 -0
  120. package/native/vendor/html5ever-0.35.0/src/tokenizer/mod.rs +2628 -0
  121. package/native/vendor/html5ever-0.35.0/src/tokenizer/states.rs +97 -0
  122. package/native/vendor/html5ever-0.35.0/src/tree_builder/data.rs +170 -0
  123. package/native/vendor/html5ever-0.35.0/src/tree_builder/mod.rs +1848 -0
  124. package/native/vendor/html5ever-0.35.0/src/tree_builder/rules.rs +1494 -0
  125. package/native/vendor/html5ever-0.35.0/src/tree_builder/tag_sets.rs +114 -0
  126. package/native/vendor/html5ever-0.35.0/src/tree_builder/types.rs +91 -0
  127. package/native/vendor/html5ever-0.35.0/src/util/str.rs +52 -0
  128. package/native/vendor/html5gum-0.8.4/Cargo.lock +1006 -0
  129. package/native/vendor/html5gum-0.8.4/Cargo.toml +109 -0
  130. package/native/vendor/html5gum-0.8.4/LICENSE +19 -0
  131. package/native/vendor/html5gum-0.8.4/README.md +110 -0
  132. package/native/vendor/html5gum-0.8.4/benches/files/0050.html +2131 -0
  133. package/native/vendor/html5gum-0.8.4/benches/files/6D30.html +1004 -0
  134. package/native/vendor/html5gum-0.8.4/benches/files.rs +32 -0
  135. package/native/vendor/html5gum-0.8.4/benches/patterns.rs +31 -0
  136. package/native/vendor/html5gum-0.8.4/src/arrayvec.rs +29 -0
  137. package/native/vendor/html5gum-0.8.4/src/char_validator.rs +134 -0
  138. package/native/vendor/html5gum-0.8.4/src/emitters/callback.rs +676 -0
  139. package/native/vendor/html5gum-0.8.4/src/emitters/default.rs +207 -0
  140. package/native/vendor/html5gum-0.8.4/src/emitters/emitter.rs +344 -0
  141. package/native/vendor/html5gum-0.8.4/src/emitters/html5ever.rs +306 -0
  142. package/native/vendor/html5gum-0.8.4/src/emitters/mod.rs +25 -0
  143. package/native/vendor/html5gum-0.8.4/src/entities.rs +3342 -0
  144. package/native/vendor/html5gum-0.8.4/src/error.rs +96 -0
  145. package/native/vendor/html5gum-0.8.4/src/htmlstring.rs +130 -0
  146. package/native/vendor/html5gum-0.8.4/src/lib.rs +66 -0
  147. package/native/vendor/html5gum-0.8.4/src/machine.rs +2136 -0
  148. package/native/vendor/html5gum-0.8.4/src/machine_helper.rs +277 -0
  149. package/native/vendor/html5gum-0.8.4/src/read_helper.rs +244 -0
  150. package/native/vendor/html5gum-0.8.4/src/reader.rs +440 -0
  151. package/native/vendor/html5gum-0.8.4/src/span.rs +98 -0
  152. package/native/vendor/html5gum-0.8.4/src/state.rs +16 -0
  153. package/native/vendor/html5gum-0.8.4/src/testutils.rs +71 -0
  154. package/native/vendor/html5gum-0.8.4/src/tokenizer.rs +189 -0
  155. package/native/vendor/html5gum-0.8.4/src/utils.rs +88 -0
  156. package/native/vendor/markup5ever-0.35.0/.cargo_vcs_info.json +6 -0
  157. package/native/vendor/markup5ever-0.35.0/Cargo.toml +45 -0
  158. package/native/vendor/markup5ever-0.35.0/LICENSE-APACHE +201 -0
  159. package/native/vendor/markup5ever-0.35.0/LICENSE-MIT +25 -0
  160. package/native/vendor/markup5ever-0.35.0/interface/mod.rs +422 -0
  161. package/native/vendor/markup5ever-0.35.0/interface/tree_builder.rs +280 -0
  162. package/native/vendor/markup5ever-0.35.0/lib.rs +59 -0
  163. package/native/vendor/markup5ever-0.35.0/serialize.rs +77 -0
  164. package/native/vendor/markup5ever-0.35.0/util/buffer_queue.rs +333 -0
  165. package/native/vendor/markup5ever-0.35.0/util/smallcharset.rs +88 -0
  166. package/native/vendor/scraper-0.24.0/Cargo.toml +52 -0
  167. package/native/vendor/scraper-0.24.0/LICENSE +15 -0
  168. package/native/vendor/scraper-0.24.0/src/element_ref/element.rs +212 -0
  169. package/native/vendor/scraper-0.24.0/src/element_ref/mod.rs +236 -0
  170. package/native/vendor/scraper-0.24.0/src/element_ref/serializable.rs +15 -0
  171. package/native/vendor/scraper-0.24.0/src/error/utils.rs +91 -0
  172. package/native/vendor/scraper-0.24.0/src/error.rs +118 -0
  173. package/native/vendor/scraper-0.24.0/src/html/mod.rs +270 -0
  174. package/native/vendor/scraper-0.24.0/src/html/serializable.rs +27 -0
  175. package/native/vendor/scraper-0.24.0/src/html/tree_sink.rs +285 -0
  176. package/native/vendor/scraper-0.24.0/src/lib.rs +180 -0
  177. package/native/vendor/scraper-0.24.0/src/node/serializable.rs +52 -0
  178. package/native/vendor/scraper-0.24.0/src/node.rs +465 -0
  179. package/native/vendor/scraper-0.24.0/src/selectable.rs +70 -0
  180. package/native/vendor/scraper-0.24.0/src/selector.rs +290 -0
  181. package/package.json +167 -4
  182. package/scripts/check-native.mjs +15 -0
  183. package/scripts/check-release.mjs +234 -0
  184. package/scripts/fix-declarations.mjs +39 -0
  185. package/scripts/generate-notices.mjs +194 -0
  186. package/scripts/notices/README.md +13 -0
  187. package/scripts/notices/cheerio-MIT.txt +21 -0
  188. package/scripts/notices/html5ever-AUTHORS.txt +20 -0
  189. package/scripts/notices/html5ever-COPYRIGHT.txt +8 -0
  190. package/scripts/notices/html5ever-LICENSE-APACHE.txt +201 -0
  191. package/scripts/notices/html5ever-LICENSE-MIT.txt +25 -0
  192. package/scripts/notices/htmlparser2-MIT.txt +18 -0
  193. package/scripts/notices/napi-rs-MIT.txt +43 -0
  194. package/scripts/notices/neon-MIT.txt +19 -0
  195. package/scripts/notices/runtime-01c266bced4a434da005.txt +3 -0
  196. package/scripts/notices/runtime-0a54e647fe54104658b5.txt +14 -0
  197. package/scripts/notices/runtime-0b74dfa0bcee5c420c6b.txt +25 -0
  198. package/scripts/notices/runtime-0d542e0c8804e39aa7f3.txt +177 -0
  199. package/scripts/notices/runtime-0f96a83840e146e43c0e.txt +21 -0
  200. package/scripts/notices/runtime-123a331b5dbf04c30097.txt +25 -0
  201. package/scripts/notices/runtime-172020dbfd5b53a226df.txt +34 -0
  202. package/scripts/notices/runtime-209fbbe0ad52d9235e37.txt +26 -0
  203. package/scripts/notices/runtime-23f18e03dc49df91622f.txt +23 -0
  204. package/scripts/notices/runtime-268872b9816f90fd8e85.txt +220 -0
  205. package/scripts/notices/runtime-35242e7a83f69875e6ed.txt +176 -0
  206. package/scripts/notices/runtime-378f5840b258e2779c39.txt +25 -0
  207. package/scripts/notices/runtime-4108245a1f2df9d4e94d.txt +25 -0
  208. package/scripts/notices/runtime-4455bf75a91154108304.txt +21 -0
  209. package/scripts/notices/runtime-553fffcd9b1cb158bc3e.txt +13 -0
  210. package/scripts/notices/runtime-62c7a1e35f56406896d7.txt +176 -0
  211. package/scripts/notices/runtime-6485b8ed310d3f0340bf.txt +25 -0
  212. package/scripts/notices/runtime-69fef7b0f322a6555415.txt +201 -0
  213. package/scripts/notices/runtime-6df43f6f4b5d4587f3d8.txt +187 -0
  214. package/scripts/notices/runtime-799e9ca9d179295ef372.txt +24 -0
  215. package/scripts/notices/runtime-7b63ecd5f1902af1b637.txt +25 -0
  216. package/scripts/notices/runtime-7bc7d5de2a0b793d4e1a.txt +21 -0
  217. package/scripts/notices/runtime-7e12e5df4bae12cb2158.txt +24 -0
  218. package/scripts/notices/runtime-861399f8c21c042b1105.txt +12 -0
  219. package/scripts/notices/runtime-8ada45cd9f843acf64e4.txt +201 -0
  220. package/scripts/notices/runtime-90eb64f0279b0d9432ac.txt +12 -0
  221. package/scripts/notices/runtime-a60eea817514531668d7.txt +201 -0
  222. package/scripts/notices/runtime-a7c936ff1ed8fa340172.txt +25 -0
  223. package/scripts/notices/runtime-ab6eec6caf0fa5775e41.txt +275 -0
  224. package/scripts/notices/runtime-b1181a40b2a7b25cf66f.txt +19 -0
  225. package/scripts/notices/runtime-b71bd43a069ca0641a9e.txt +25 -0
  226. package/scripts/notices/runtime-c16f8dcf1a368b83be78.txt +201 -0
  227. package/scripts/notices/runtime-c2cfccb812fe482101a8.txt +21 -0
  228. package/scripts/notices/runtime-e99d88d232bf57d70f0f.txt +25 -0
  229. package/scripts/notices/runtime-f32fb3b417a194167cfa.txt +9 -0
  230. package/scripts/notices/runtime-f5062c9a188d81dfe66b.txt +39 -0
  231. package/scripts/notices/runtime-f9070a832833fa7488fd.txt +4 -0
  232. package/scripts/notices/runtime-fab3dd6bdab226f1c086.txt +373 -0
  233. package/scripts/notices/runtime-fba3318d0c600380177e.txt +62 -0
  234. package/scripts/notices/runtime-ff8f68cb076caf8cefe7.txt +25 -0
  235. package/scripts/notices/runtime-ff92bed461f50338dd70.txt +74 -0
  236. package/scripts/notices/runtime.json +1632 -0
  237. package/scripts/notices/sources.json +561 -0
  238. package/scripts/notices/xray-MIT.txt +21 -0
  239. package/src/attribute-object.ts +71 -0
  240. package/src/attributes.ts +308 -0
  241. package/src/cheerio-compat/css.ts +58 -0
  242. package/src/cheerio-compat/render.ts +106 -0
  243. package/src/cheerio-compat/selectors.ts +51 -0
  244. package/src/cheerio-compat/types.ts +52 -0
  245. package/src/cheerio-compat.ts +2055 -0
  246. package/src/codec.ts +96 -0
  247. package/src/dom.ts +87 -0
  248. package/src/extract-plan.ts +97 -0
  249. package/src/extract.ts +322 -0
  250. package/src/hooks.ts +369 -0
  251. package/src/index.ts +48 -0
  252. package/src/io.ts +491 -0
  253. package/src/match.ts +207 -0
  254. package/src/modern.ts +259 -0
  255. package/src/native.ts +149 -0
  256. package/src/nodes.ts +831 -0
  257. package/src/parse.ts +53 -0
  258. package/src/parser-types.ts +157 -0
  259. package/src/router.ts +1129 -0
  260. package/src/selection.ts +682 -0
  261. package/src/slim.ts +12 -0
  262. package/src/snapshot.ts +291 -0
  263. package/src/transport.ts +113 -0
  264. package/src/types.ts +186 -0
  265. package/src/utils.ts +29 -0
  266. package/src/workers.ts +21 -0
  267. package/tsconfig.json +15 -0
  268. package/tsdown.config.mjs +17 -0
@@ -0,0 +1,1596 @@
1
+ //! Cheerio-compatible CSS and jQuery selection over the native mutable DOM.
2
+
3
+ use crate::id_hash::{IdMap, IdSet};
4
+ use napi::{Error, Result, Status};
5
+
6
+ pub(crate) trait SelectDom {
7
+ fn kind(&self, id: u32) -> &str;
8
+ fn name(&self, id: u32) -> Option<&str>;
9
+ fn attr(&self, id: u32, name: &str) -> Option<&str>;
10
+ fn parent(&self, id: u32) -> Option<u32>;
11
+ fn children(&self, id: u32) -> &[u32];
12
+ fn text(&self, id: u32) -> String;
13
+ fn xml_mode(&self) -> bool;
14
+ fn lower_case_tags(&self) -> bool {
15
+ !self.xml_mode()
16
+ }
17
+ fn lower_case_attribute_names(&self) -> bool {
18
+ !self.xml_mode()
19
+ }
20
+ fn custom_pseudo(&self, _id: u32, _name: &str, _argument: Option<&str>) -> Option<bool> {
21
+ None
22
+ }
23
+ fn pseudo_alias(&self, _name: &str) -> Option<&str> {
24
+ None
25
+ }
26
+ /// Every element whose ASCII-lowercased name is `lowercase_name`, in
27
+ /// document order, when the tree keeps such an index.
28
+ fn elements_named(&self, _lowercase_name: &str) -> Option<&[u32]> {
29
+ None
30
+ }
31
+ /// Whether ascending ids are document order for every node.
32
+ fn is_id_order_document_order(&self) -> bool {
33
+ false
34
+ }
35
+ }
36
+
37
+ /// Attributes whose values css-select compares case-insensitively in HTML
38
+ /// documents when a selector has no `i` or `s` flag.
39
+ pub(crate) const CASE_INSENSITIVE_ATTRIBUTES: &[&str] = &[
40
+ "accept",
41
+ "accept-charset",
42
+ "align",
43
+ "alink",
44
+ "axis",
45
+ "bgcolor",
46
+ "charset",
47
+ "checked",
48
+ "clear",
49
+ "codetype",
50
+ "color",
51
+ "compact",
52
+ "declare",
53
+ "defer",
54
+ "dir",
55
+ "direction",
56
+ "disabled",
57
+ "enctype",
58
+ "face",
59
+ "frame",
60
+ "hreflang",
61
+ "http-equiv",
62
+ "lang",
63
+ "language",
64
+ "link",
65
+ "media",
66
+ "method",
67
+ "multiple",
68
+ "nohref",
69
+ "noresize",
70
+ "noshade",
71
+ "nowrap",
72
+ "readonly",
73
+ "rel",
74
+ "rev",
75
+ "rules",
76
+ "scope",
77
+ "scrolling",
78
+ "selected",
79
+ "shape",
80
+ "target",
81
+ "text",
82
+ "type",
83
+ "valign",
84
+ "valuetype",
85
+ "vlink",
86
+ ];
87
+
88
+ const KNOWN: &[&str] = &[
89
+ "not",
90
+ "is",
91
+ "where",
92
+ "matches",
93
+ "has",
94
+ "contains",
95
+ "icontains",
96
+ "first",
97
+ "last",
98
+ "eq",
99
+ "nth",
100
+ "lt",
101
+ "gt",
102
+ "even",
103
+ "odd",
104
+ "root",
105
+ "scope",
106
+ "empty",
107
+ "parent",
108
+ "first-child",
109
+ "last-child",
110
+ "only-child",
111
+ "nth-child",
112
+ "nth-last-child",
113
+ "first-of-type",
114
+ "last-of-type",
115
+ "only-of-type",
116
+ "nth-of-type",
117
+ "nth-last-of-type",
118
+ "header",
119
+ "input",
120
+ "button",
121
+ "text",
122
+ "checkbox",
123
+ "file",
124
+ "password",
125
+ "radio",
126
+ "reset",
127
+ "image",
128
+ "submit",
129
+ "selected",
130
+ "checked",
131
+ "disabled",
132
+ "enabled",
133
+ "link",
134
+ "any-link",
135
+ "visited",
136
+ "active",
137
+ "hover",
138
+ "required",
139
+ "optional",
140
+ ];
141
+
142
+ #[derive(Clone, Copy)]
143
+ enum Combinator {
144
+ Descendant,
145
+ Child,
146
+ Next,
147
+ Following,
148
+ }
149
+
150
+ #[derive(Clone)]
151
+ enum Test {
152
+ Tag(String),
153
+ Id(String),
154
+ Class(String),
155
+ Attribute {
156
+ name: String,
157
+ op: String,
158
+ value: String,
159
+ flag: Option<char>,
160
+ },
161
+ Pseudo(String, String),
162
+ }
163
+
164
+ #[derive(Clone)]
165
+ struct Complex {
166
+ parts: Vec<Vec<Test>>,
167
+ combinators: Vec<Combinator>,
168
+ leading: Option<Combinator>,
169
+ }
170
+
171
+ fn validate<D: SelectDom>(dom: &D, complex: &Complex) -> Result<()> {
172
+ for part in &complex.parts {
173
+ for test in part {
174
+ if let Test::Pseudo(name, argument) = test {
175
+ if !KNOWN.contains(&name.as_str())
176
+ && dom.custom_pseudo(0, name, Some(argument)).is_none()
177
+ && dom.pseudo_alias(name).is_none()
178
+ {
179
+ return Err(invalid(format!("Unknown pseudo-class :{name}")));
180
+ }
181
+ if matches!(name.as_str(), "not" | "is" | "where" | "matches" | "has") {
182
+ for nested in parse(argument)?.iter() {
183
+ validate(dom, nested)?;
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
189
+ Ok(())
190
+ }
191
+
192
+ fn invalid(message: impl Into<String>) -> Error {
193
+ Error::new(Status::InvalidArg, message.into())
194
+ }
195
+
196
+ fn tag<D: SelectDom>(dom: &D, id: u32) -> bool {
197
+ matches!(dom.kind(id), "tag" | "script" | "style")
198
+ }
199
+
200
+ fn escape_end(chars: &[char], start: usize) -> usize {
201
+ let mut i = start + 1;
202
+ if i >= chars.len() {
203
+ return i;
204
+ }
205
+ if chars[i].is_ascii_hexdigit() {
206
+ let end = (i + 6).min(chars.len());
207
+ while i < end && chars[i].is_ascii_hexdigit() {
208
+ i += 1;
209
+ }
210
+ if i < chars.len() && chars[i].is_whitespace() {
211
+ i += 1;
212
+ }
213
+ i
214
+ } else {
215
+ i + 1
216
+ }
217
+ }
218
+
219
+ fn unescape(value: &str) -> String {
220
+ if !value.contains('\\') {
221
+ return value.to_owned();
222
+ }
223
+ let chars: Vec<char> = value.chars().collect();
224
+ let mut result = String::new();
225
+ let mut i = 0;
226
+ while i < chars.len() {
227
+ if chars[i] != '\\' {
228
+ result.push(chars[i]);
229
+ i += 1;
230
+ continue;
231
+ }
232
+ let end = escape_end(&chars, i);
233
+ let hexadecimal: String = chars[i + 1..end]
234
+ .iter()
235
+ .take_while(|c| c.is_ascii_hexdigit())
236
+ .collect();
237
+ if hexadecimal.is_empty() {
238
+ if i + 1 < chars.len() {
239
+ result.push(chars[i + 1]);
240
+ }
241
+ } else {
242
+ let code = u32::from_str_radix(&hexadecimal, 16).unwrap_or(0);
243
+ // css-what decodes escapes with JavaScript String.fromCharCode,
244
+ // including lone surrogate code units and paired escapes.
245
+ let units = if code <= 0xffff {
246
+ vec![code as u16]
247
+ } else {
248
+ let high = code - 0x10000;
249
+ vec![
250
+ ((high >> 10) | 0xd800) as u16,
251
+ ((high & 0x3ff) | 0xdc00) as u16,
252
+ ]
253
+ };
254
+ result.push_str(&crate::codec::from_units(&units));
255
+ }
256
+ i = end;
257
+ }
258
+ if crate::codec::has_encoding(&result) {
259
+ crate::codec::from_units(&crate::codec::to_units(&result))
260
+ } else {
261
+ result
262
+ }
263
+ }
264
+
265
+ fn equal_strings(left: &str, right: &str) -> bool {
266
+ left == right
267
+ || !(left.is_ascii() && right.is_ascii())
268
+ && (crate::codec::has_encoding(left) || crate::codec::has_encoding(right))
269
+ && crate::codec::to_units(left) == crate::codec::to_units(right)
270
+ }
271
+
272
+ fn starts_with(text: &str, value: &str) -> bool {
273
+ if crate::codec::has_encoding(text) || crate::codec::has_encoding(value) {
274
+ crate::codec::to_units(text).starts_with(&crate::codec::to_units(value))
275
+ } else {
276
+ text.starts_with(value)
277
+ }
278
+ }
279
+
280
+ fn ends_with(text: &str, value: &str) -> bool {
281
+ if crate::codec::has_encoding(text) || crate::codec::has_encoding(value) {
282
+ crate::codec::to_units(text).ends_with(&crate::codec::to_units(value))
283
+ } else {
284
+ text.ends_with(value)
285
+ }
286
+ }
287
+
288
+ fn contains(text: &str, value: &str) -> bool {
289
+ if crate::codec::has_encoding(text) || crate::codec::has_encoding(value) {
290
+ let text = crate::codec::to_units(text);
291
+ let value = crate::codec::to_units(value);
292
+ value.is_empty() || text.windows(value.len()).any(|window| window == value)
293
+ } else {
294
+ text.contains(value)
295
+ }
296
+ }
297
+
298
+ fn identifier(chars: &[char], i: &mut usize) -> String {
299
+ let start = *i;
300
+ while *i < chars.len() {
301
+ let c = chars[*i];
302
+ if c == '\\' {
303
+ *i = escape_end(chars, *i);
304
+ } else if c.is_alphanumeric() || c == '-' || c == '_' || !c.is_ascii() {
305
+ *i += 1;
306
+ } else {
307
+ break;
308
+ }
309
+ }
310
+ unescape(&chars[start..*i].iter().collect::<String>())
311
+ }
312
+
313
+ fn split_groups(source: &str) -> Result<Vec<String>> {
314
+ let chars: Vec<char> = source.chars().collect();
315
+ let mut groups = Vec::new();
316
+ let (mut i, mut start, mut brackets, mut parentheses) = (0, 0, 0i32, 0i32);
317
+ let mut quote = None;
318
+ while i < chars.len() {
319
+ let c = chars[i];
320
+ if c == '\\' {
321
+ i = escape_end(&chars, i);
322
+ continue;
323
+ }
324
+ if let Some(q) = quote {
325
+ if c == q {
326
+ quote = None;
327
+ }
328
+ i += 1;
329
+ continue;
330
+ }
331
+ match c {
332
+ '\'' | '"' => quote = Some(c),
333
+ '[' => brackets += 1,
334
+ ']' => brackets -= 1,
335
+ '(' if brackets == 0 => parentheses += 1,
336
+ ')' if brackets == 0 => parentheses -= 1,
337
+ ',' if brackets == 0 && parentheses == 0 => {
338
+ groups.push(
339
+ chars[start..i]
340
+ .iter()
341
+ .collect::<String>()
342
+ .trim()
343
+ .to_string(),
344
+ );
345
+ start = i + 1;
346
+ }
347
+ _ => {}
348
+ }
349
+ if brackets < 0 || parentheses < 0 {
350
+ return Err(invalid("Unmatched selector delimiter"));
351
+ }
352
+ i += 1;
353
+ }
354
+ if brackets != 0 || parentheses != 0 || quote.is_some() {
355
+ return Err(invalid("Unmatched selector delimiter"));
356
+ }
357
+ groups.push(chars[start..].iter().collect::<String>().trim().to_string());
358
+ if groups.iter().any(String::is_empty) {
359
+ return Err(invalid("Empty sub-selector"));
360
+ }
361
+ Ok(groups)
362
+ }
363
+
364
+ fn parse_attribute(source: &str) -> Result<Test> {
365
+ let chars: Vec<char> = source.trim().chars().collect();
366
+ let mut i = 0;
367
+ let mut name = identifier(&chars, &mut i);
368
+ if i < chars.len() && chars[i] == ':' {
369
+ i += 1;
370
+ name.push(':');
371
+ name.push_str(&identifier(&chars, &mut i));
372
+ }
373
+ if name.is_empty() {
374
+ return Err(invalid("Malformed attribute selector"));
375
+ }
376
+ while i < chars.len() && chars[i].is_whitespace() {
377
+ i += 1;
378
+ }
379
+ if i == chars.len() {
380
+ return Ok(Test::Attribute {
381
+ name,
382
+ op: String::new(),
383
+ value: String::new(),
384
+ flag: None,
385
+ });
386
+ }
387
+ let mut op = String::new();
388
+ if "!~|^$*".contains(chars[i]) {
389
+ op.push(chars[i]);
390
+ i += 1;
391
+ }
392
+ if chars.get(i) != Some(&'=') {
393
+ return Err(invalid("Attribute selector is missing an operator"));
394
+ }
395
+ op.push('=');
396
+ i += 1;
397
+ while i < chars.len() && chars[i].is_whitespace() {
398
+ i += 1;
399
+ }
400
+ let value;
401
+ if matches!(chars.get(i), Some('\'' | '"')) {
402
+ let quote = chars[i];
403
+ i += 1;
404
+ let start = i;
405
+ while i < chars.len() && chars[i] != quote {
406
+ i = if chars[i] == '\\' {
407
+ escape_end(&chars, i)
408
+ } else {
409
+ i + 1
410
+ };
411
+ }
412
+ if i >= chars.len() {
413
+ return Err(invalid("Unmatched attribute quote"));
414
+ }
415
+ value = unescape(&chars[start..i].iter().collect::<String>());
416
+ i += 1;
417
+ } else {
418
+ let start = i;
419
+ while i < chars.len() && !chars[i].is_whitespace() {
420
+ i = if chars[i] == '\\' {
421
+ escape_end(&chars, i)
422
+ } else {
423
+ i + 1
424
+ };
425
+ }
426
+ value = unescape(&chars[start..i].iter().collect::<String>());
427
+ }
428
+ while i < chars.len() && chars[i].is_whitespace() {
429
+ i += 1;
430
+ }
431
+ let flag = chars.get(i).copied().map(|c| c.to_ascii_lowercase());
432
+ if flag.is_some_and(|c| c != 'i' && c != 's') || i + usize::from(flag.is_some()) < chars.len() {
433
+ return Err(invalid("Invalid attribute selector flag"));
434
+ }
435
+ Ok(Test::Attribute {
436
+ name,
437
+ op,
438
+ value,
439
+ flag,
440
+ })
441
+ }
442
+
443
+ fn parse_compound(source: &str) -> Result<Vec<Test>> {
444
+ let chars: Vec<char> = source.chars().collect();
445
+ let mut tests = Vec::new();
446
+ let mut i = 0;
447
+ if chars.first() == Some(&'*') {
448
+ i += 1;
449
+ } else if chars
450
+ .first()
451
+ .is_some_and(|c| *c != '#' && *c != '.' && *c != '[' && *c != ':')
452
+ {
453
+ let name = identifier(&chars, &mut i);
454
+ if name.is_empty() {
455
+ return Err(invalid(format!("Unexpected selector {source:?}")));
456
+ }
457
+ tests.push(Test::Tag(name));
458
+ }
459
+ while i < chars.len() {
460
+ let marker = chars[i];
461
+ i += 1;
462
+ match marker {
463
+ '#' | '.' => {
464
+ let name = identifier(&chars, &mut i);
465
+ if name.is_empty() {
466
+ return Err(invalid("Expected selector identifier"));
467
+ }
468
+ tests.push(if marker == '#' {
469
+ Test::Id(name)
470
+ } else {
471
+ Test::Class(name)
472
+ });
473
+ }
474
+ '[' => {
475
+ let start = i;
476
+ let mut quote = None;
477
+ while i < chars.len() {
478
+ let c = chars[i];
479
+ if c == '\\' {
480
+ i = escape_end(&chars, i);
481
+ continue;
482
+ }
483
+ if let Some(q) = quote {
484
+ if c == q {
485
+ quote = None;
486
+ }
487
+ } else if c == '\'' || c == '"' {
488
+ quote = Some(c);
489
+ } else if c == ']' {
490
+ break;
491
+ }
492
+ i += 1;
493
+ }
494
+ if i == chars.len() {
495
+ return Err(invalid("Unmatched attribute selector"));
496
+ }
497
+ tests.push(parse_attribute(
498
+ &chars[start..i].iter().collect::<String>(),
499
+ )?);
500
+ i += 1;
501
+ }
502
+ ':' => {
503
+ let name = identifier(&chars, &mut i).to_ascii_lowercase();
504
+ if name.is_empty() {
505
+ return Err(invalid("Expected pseudo-class name"));
506
+ }
507
+ let mut argument = String::new();
508
+ if chars.get(i) == Some(&'(') {
509
+ i += 1;
510
+ let start = i;
511
+ let mut depth = 1;
512
+ let mut quote = None;
513
+ while i < chars.len() {
514
+ let c = chars[i];
515
+ if c == '\\' {
516
+ i = escape_end(&chars, i);
517
+ continue;
518
+ }
519
+ if let Some(q) = quote {
520
+ if c == q {
521
+ quote = None;
522
+ }
523
+ } else if c == '\'' || c == '"' {
524
+ quote = Some(c);
525
+ } else if c == '(' {
526
+ depth += 1;
527
+ } else if c == ')' {
528
+ depth -= 1;
529
+ if depth == 0 {
530
+ break;
531
+ }
532
+ }
533
+ i += 1;
534
+ }
535
+ if depth != 0 {
536
+ return Err(invalid("Unmatched pseudo-class argument"));
537
+ }
538
+ argument = chars[start..i]
539
+ .iter()
540
+ .collect::<String>()
541
+ .trim()
542
+ .to_string();
543
+ i += 1;
544
+ }
545
+ tests.push(Test::Pseudo(name, argument));
546
+ }
547
+ _ => return Err(invalid(format!("Unexpected selector character {marker:?}"))),
548
+ }
549
+ }
550
+ Ok(tests)
551
+ }
552
+
553
+ thread_local! {
554
+ /// Parsed selectors by source; queries reuse a handful of selectors many times.
555
+ /// A two-generation cache avoids the cliff of clearing all 512 entries at once.
556
+ static PARSED_CURRENT: std::cell::RefCell<std::collections::HashMap<String, std::rc::Rc<Vec<Complex>>>> =
557
+ std::cell::RefCell::new(std::collections::HashMap::new());
558
+ static PARSED_PREVIOUS: std::cell::RefCell<std::collections::HashMap<String, std::rc::Rc<Vec<Complex>>>> =
559
+ std::cell::RefCell::new(std::collections::HashMap::new());
560
+ }
561
+ const PARSED_LIMIT: usize = 512;
562
+
563
+ fn parse(source: &str) -> Result<std::rc::Rc<Vec<Complex>>> {
564
+ if let Some(parsed) = PARSED_CURRENT.with(|cache| cache.borrow().get(source).cloned()) {
565
+ return Ok(parsed);
566
+ }
567
+ if let Some(parsed) = PARSED_PREVIOUS.with(|cache| cache.borrow().get(source).cloned()) {
568
+ return Ok(parsed);
569
+ }
570
+ let parsed = std::rc::Rc::new(parse_uncached(source)?);
571
+ PARSED_CURRENT.with(|cache| {
572
+ let mut cache = cache.borrow_mut();
573
+ if cache.len() >= PARSED_LIMIT {
574
+ let previous = std::mem::take(&mut *cache);
575
+ PARSED_PREVIOUS.with(|p| *p.borrow_mut() = previous);
576
+ }
577
+ cache.insert(source.to_owned(), parsed.clone());
578
+ });
579
+ Ok(parsed)
580
+ }
581
+
582
+ fn parse_uncached(source: &str) -> Result<Vec<Complex>> {
583
+ split_groups(source)?
584
+ .iter()
585
+ .map(|group| {
586
+ let chars: Vec<char> = group.chars().collect();
587
+ let mut parts = Vec::new();
588
+ let mut combinators = Vec::new();
589
+ let mut leading = None;
590
+ let (mut i, mut start, mut brackets, mut parentheses) = (0, 0, 0i32, 0i32);
591
+ let mut quote = None;
592
+ while i < chars.len() {
593
+ let c = chars[i];
594
+ if c == '\\' {
595
+ i = escape_end(&chars, i);
596
+ continue;
597
+ }
598
+ if let Some(q) = quote {
599
+ if c == q {
600
+ quote = None;
601
+ }
602
+ i += 1;
603
+ continue;
604
+ }
605
+ match c {
606
+ '\'' | '"' => quote = Some(c),
607
+ '[' => brackets += 1,
608
+ ']' => brackets -= 1,
609
+ '(' => parentheses += 1,
610
+ ')' => parentheses -= 1,
611
+ _ => {}
612
+ }
613
+ if brackets == 0 && parentheses == 0 && (c.is_whitespace() || ">+~".contains(c)) {
614
+ if start < i {
615
+ parts.push(parse_compound(&chars[start..i].iter().collect::<String>())?);
616
+ }
617
+ let mut combinator = Combinator::Descendant;
618
+ while i < chars.len() && chars[i].is_whitespace() {
619
+ i += 1;
620
+ }
621
+ if i < chars.len() && ">+~".contains(chars[i]) {
622
+ combinator = match chars[i] {
623
+ '>' => Combinator::Child,
624
+ '+' => Combinator::Next,
625
+ _ => Combinator::Following,
626
+ };
627
+ i += 1;
628
+ while i < chars.len() && chars[i].is_whitespace() {
629
+ i += 1;
630
+ }
631
+ if i == chars.len() {
632
+ return Err(invalid("Selector cannot end with a combinator"));
633
+ }
634
+ }
635
+ if parts.is_empty() {
636
+ leading = Some(combinator);
637
+ } else if i < chars.len() {
638
+ combinators.push(combinator);
639
+ }
640
+ start = i;
641
+ continue;
642
+ }
643
+ i += 1;
644
+ }
645
+ if start < i {
646
+ parts.push(parse_compound(&chars[start..i].iter().collect::<String>())?);
647
+ }
648
+ if parts.is_empty() || combinators.len() + 1 != parts.len() {
649
+ return Err(invalid("Invalid combinator in selector"));
650
+ }
651
+ Ok(Complex {
652
+ parts,
653
+ combinators,
654
+ leading,
655
+ })
656
+ })
657
+ .collect()
658
+ }
659
+
660
+ fn unique(ids: impl IntoIterator<Item = u32>) -> Vec<u32> {
661
+ let mut seen = IdSet::default();
662
+ ids.into_iter().filter(|id| seen.insert(*id)).collect()
663
+ }
664
+
665
+ fn descendants<D: SelectDom>(dom: &D, roots: &[u32]) -> Vec<u32> {
666
+ let mut output = Vec::new();
667
+ for root in roots {
668
+ let scope_barrier = tag(dom, *root);
669
+ let mut stack: Vec<u32> = dom.children(*root).iter().rev().copied().collect();
670
+ while let Some(id) = stack.pop() {
671
+ if scope_barrier && dom.kind(id) == "root" {
672
+ continue;
673
+ }
674
+ if tag(dom, id) {
675
+ output.push(id);
676
+ }
677
+ stack.extend(dom.children(id).iter().rev().copied());
678
+ }
679
+ }
680
+ // One root's descendants are distinct; only overlapping roots repeat.
681
+ if roots.len() > 1 {
682
+ unique(output)
683
+ } else {
684
+ output
685
+ }
686
+ }
687
+
688
+ /// Visits the elements below `root` in document order, as `descendants` lists
689
+ /// them for one root, until `visit` returns false.
690
+ fn for_each_descendant<D: SelectDom>(dom: &D, root: u32, mut visit: impl FnMut(u32) -> bool) {
691
+ let scope_barrier = tag(dom, root);
692
+ let mut stack: Vec<u32> = dom.children(root).iter().rev().copied().collect();
693
+ while let Some(id) = stack.pop() {
694
+ let kind = dom.kind(id);
695
+ if scope_barrier && kind == "root" {
696
+ continue;
697
+ }
698
+ if matches!(kind, "tag" | "script" | "style") && !visit(id) {
699
+ return;
700
+ }
701
+ stack.extend(dom.children(id).iter().rev().copied());
702
+ }
703
+ }
704
+
705
+ fn siblings<D: SelectDom>(dom: &D, id: u32) -> Vec<u32> {
706
+ dom.parent(id).map_or_else(Vec::new, |parent| {
707
+ dom.children(parent)
708
+ .iter()
709
+ .copied()
710
+ .filter(|id| tag(dom, *id))
711
+ .collect()
712
+ })
713
+ }
714
+
715
+ fn expand<D: SelectDom>(dom: &D, ids: &[u32], combinator: Combinator) -> Vec<u32> {
716
+ match combinator {
717
+ Combinator::Descendant => descendants(dom, ids),
718
+ Combinator::Child => unique(
719
+ ids.iter()
720
+ .flat_map(|id| dom.children(*id))
721
+ .copied()
722
+ .filter(|id| tag(dom, *id)),
723
+ ),
724
+ Combinator::Next | Combinator::Following => unique(ids.iter().flat_map(|id| {
725
+ let siblings = siblings(dom, *id);
726
+ let offset = siblings
727
+ .iter()
728
+ .position(|other| other == id)
729
+ .map_or(siblings.len(), |i| i + 1);
730
+ let limit = if matches!(combinator, Combinator::Next) {
731
+ 1
732
+ } else {
733
+ siblings.len()
734
+ };
735
+ siblings
736
+ .into_iter()
737
+ .skip(offset)
738
+ .take(limit)
739
+ .collect::<Vec<_>>()
740
+ })),
741
+ }
742
+ }
743
+
744
+ fn position(name: &str) -> bool {
745
+ matches!(
746
+ name,
747
+ "first" | "last" | "eq" | "nth" | "lt" | "gt" | "even" | "odd"
748
+ )
749
+ }
750
+
751
+ fn has_position(source: &str) -> Result<bool> {
752
+ for complex in parse(source)?.iter() {
753
+ for part in &complex.parts {
754
+ for test in part {
755
+ if let Test::Pseudo(name, argument) = test {
756
+ if position(name)
757
+ || (matches!(name.as_str(), "not" | "is" | "where" | "matches")
758
+ && has_position(argument)?)
759
+ {
760
+ return Ok(true);
761
+ }
762
+ }
763
+ }
764
+ }
765
+ }
766
+ Ok(false)
767
+ }
768
+
769
+ fn nth(argument: &str, index: usize, total: usize, reverse: bool) -> bool {
770
+ let expression = argument
771
+ .to_ascii_lowercase()
772
+ .replace(char::is_whitespace, "");
773
+ let n = if reverse { total - index } else { index + 1 } as i64;
774
+ if expression == "odd" {
775
+ return n % 2 == 1;
776
+ }
777
+ if expression == "even" {
778
+ return n % 2 == 0;
779
+ }
780
+ if let Some(at) = expression.find('n') {
781
+ let coefficient = match &expression[..at] {
782
+ "" | "+" => Some(1),
783
+ "-" => Some(-1),
784
+ other => other.parse::<i64>().ok(),
785
+ };
786
+ let offset = if at + 1 == expression.len() {
787
+ Some(0)
788
+ } else {
789
+ expression[at + 1..].parse::<i64>().ok()
790
+ };
791
+ match (coefficient, offset) {
792
+ (Some(0), Some(b)) => n == b,
793
+ (Some(a), Some(b)) => (n - b) * a >= 0 && (n - b) % a == 0,
794
+ _ => false,
795
+ }
796
+ } else {
797
+ expression.parse::<i64>().ok() == Some(n)
798
+ }
799
+ }
800
+
801
+ fn disabled<D: SelectDom>(dom: &D, id: u32) -> bool {
802
+ let name = dom.name(id).unwrap_or("");
803
+ if name == "option"
804
+ && dom.parent(id).is_some_and(|parent| {
805
+ dom.name(parent) == Some("optgroup") && dom.attr(parent, "disabled").is_some()
806
+ })
807
+ {
808
+ return true;
809
+ }
810
+ if dom.attr(id, "disabled").is_none() {
811
+ return false;
812
+ }
813
+ if matches!(
814
+ name,
815
+ "button" | "input" | "select" | "textarea" | "optgroup" | "option"
816
+ ) {
817
+ return true;
818
+ }
819
+ if name != "fieldset" {
820
+ return false;
821
+ }
822
+ // Follow Cheerio/css-select's alias, including its fieldset/legend rule.
823
+ let mut parent = dom.parent(id);
824
+ while let Some(ancestor) = parent {
825
+ if dom.name(ancestor) == Some("legend") {
826
+ if let Some(fieldset) = dom.parent(ancestor) {
827
+ if dom.name(fieldset) == Some("fieldset")
828
+ && dom.attr(fieldset, "disabled").is_some()
829
+ && dom
830
+ .children(fieldset)
831
+ .iter()
832
+ .copied()
833
+ .find(|id| dom.name(*id) == Some("legend"))
834
+ == Some(ancestor)
835
+ {
836
+ return false;
837
+ }
838
+ }
839
+ }
840
+ parent = dom.parent(ancestor);
841
+ }
842
+ true
843
+ }
844
+
845
+ fn selected<D: SelectDom>(dom: &D, id: u32) -> bool {
846
+ if dom.name(id) != Some("option") {
847
+ return false;
848
+ }
849
+ if dom.attr(id, "selected").is_some() {
850
+ return true;
851
+ }
852
+ let Some(parent) = dom.parent(id) else {
853
+ return false;
854
+ };
855
+ if dom.name(parent) != Some("select") || dom.attr(parent, "multiple").is_some() {
856
+ return false;
857
+ }
858
+ let options: Vec<_> = dom
859
+ .children(parent)
860
+ .iter()
861
+ .copied()
862
+ .filter(|id| dom.name(*id) == Some("option"))
863
+ .collect();
864
+ options.first() == Some(&id) && !options.iter().any(|id| dom.attr(*id, "selected").is_some())
865
+ }
866
+
867
+ fn attr_matches<D: SelectDom>(
868
+ dom: &D,
869
+ id: u32,
870
+ name: &str,
871
+ op: &str,
872
+ value: &str,
873
+ flag: Option<char>,
874
+ ) -> bool {
875
+ let name = if !dom.lower_case_attribute_names() {
876
+ name.to_string()
877
+ } else {
878
+ name.to_ascii_lowercase()
879
+ };
880
+ let attribute = dom.attr(id, &name);
881
+ if op.is_empty() {
882
+ return attribute.is_some();
883
+ }
884
+ let Some(attribute) = attribute else {
885
+ return op == "!=" && !value.is_empty();
886
+ };
887
+ let insensitive = flag == Some('i')
888
+ || (flag != Some('s')
889
+ && !dom.xml_mode()
890
+ && CASE_INSENSITIVE_ATTRIBUTES.contains(&name.as_str()));
891
+ let (attribute, value) = if insensitive {
892
+ (attribute.to_lowercase(), value.to_lowercase())
893
+ } else {
894
+ (attribute.to_string(), value.to_string())
895
+ };
896
+ match op {
897
+ "=" => equal_strings(&attribute, &value),
898
+ "!=" => !equal_strings(&attribute, &value),
899
+ "~=" => {
900
+ !value.is_empty()
901
+ && attribute
902
+ .split_whitespace()
903
+ .any(|part| equal_strings(part, &value))
904
+ }
905
+ "|=" => equal_strings(&attribute, &value) || starts_with(&attribute, &(value + "-")),
906
+ "^=" => !value.is_empty() && starts_with(&attribute, &value),
907
+ "$=" => !value.is_empty() && ends_with(&attribute, &value),
908
+ "*=" => !value.is_empty() && contains(&attribute, &value),
909
+ _ => false,
910
+ }
911
+ }
912
+
913
+ fn matches_backwards<D: SelectDom>(
914
+ dom: &D,
915
+ id: u32,
916
+ complex: &Complex,
917
+ index: usize,
918
+ scope: &[u32],
919
+ memo: &mut BackwardMemo,
920
+ ) -> Result<bool> {
921
+ matches_backwards_within(dom, id, complex, index, scope, None, memo)
922
+ }
923
+
924
+ /// Results of matching an element against the compounds up to an index, for
925
+ /// one complex selector, scope and allowed set. Without it, chains of
926
+ /// descendant combinators retry the same ancestors for every candidate,
927
+ /// which grows exponentially with nesting depth.
928
+ #[derive(Default)]
929
+ struct BackwardMemo(IdMap<u64, bool>);
930
+
931
+ /// Matches right to left. With `allowed`, every element matched for an
932
+ /// earlier compound must be in that set.
933
+ fn matches_backwards_within<D: SelectDom>(
934
+ dom: &D,
935
+ id: u32,
936
+ complex: &Complex,
937
+ index: usize,
938
+ scope: &[u32],
939
+ allowed: Option<&IdSet<u32>>,
940
+ memo: &mut BackwardMemo,
941
+ ) -> Result<bool> {
942
+ // One combinator cannot repeat work; the memo would only cost lookups.
943
+ let key = (complex.parts.len() > 2).then(|| (index as u64) << 32 | u64::from(id));
944
+ if let Some(known) = key.and_then(|key| memo.0.get(&key)) {
945
+ return Ok(*known);
946
+ }
947
+ let matched = matches_backwards_uncached(dom, id, complex, index, scope, allowed, memo)?;
948
+ if let Some(key) = key {
949
+ memo.0.insert(key, matched);
950
+ }
951
+ Ok(matched)
952
+ }
953
+
954
+ fn matches_backwards_uncached<D: SelectDom>(
955
+ dom: &D,
956
+ id: u32,
957
+ complex: &Complex,
958
+ index: usize,
959
+ scope: &[u32],
960
+ allowed: Option<&IdSet<u32>>,
961
+ memo: &mut BackwardMemo,
962
+ ) -> Result<bool> {
963
+ if !matches_compound(dom, id, &complex.parts[index], scope)? {
964
+ return Ok(false);
965
+ }
966
+ if index == 0 {
967
+ return Ok(true);
968
+ }
969
+ let relation = complex.combinators[index - 1];
970
+ let candidates = match relation {
971
+ Combinator::Child => dom
972
+ .parent(id)
973
+ .into_iter()
974
+ .filter(|id| tag(dom, *id))
975
+ .collect(),
976
+ Combinator::Descendant => {
977
+ let mut parents = Vec::new();
978
+ let mut parent = dom.parent(id);
979
+ while let Some(id) = parent {
980
+ if !tag(dom, id) {
981
+ break;
982
+ }
983
+ parents.push(id);
984
+ parent = dom.parent(id);
985
+ }
986
+ parents
987
+ }
988
+ Combinator::Next | Combinator::Following => {
989
+ let mut others = siblings(dom, id);
990
+ let offset = others.iter().position(|other| *other == id).unwrap_or(0);
991
+ others.truncate(offset);
992
+ if matches!(relation, Combinator::Next) {
993
+ others.into_iter().rev().take(1).collect()
994
+ } else {
995
+ others
996
+ }
997
+ }
998
+ };
999
+ for candidate in candidates {
1000
+ if allowed.is_some_and(|allowed| !allowed.contains(&candidate)) {
1001
+ continue;
1002
+ }
1003
+ if matches_backwards_within(dom, candidate, complex, index - 1, scope, allowed, memo)? {
1004
+ return Ok(true);
1005
+ }
1006
+ }
1007
+ Ok(false)
1008
+ }
1009
+
1010
+ /// Whether evaluating `complex` right to left gives the same result as
1011
+ /// expanding it left to right: no leading combinator, no `:scope`, and no
1012
+ /// positional pseudo-class, which filters each intermediate selection.
1013
+ fn is_backward_safe(complex: &Complex) -> Result<bool> {
1014
+ if complex.leading.is_some() || complex.parts.len() < 2 {
1015
+ return Ok(false);
1016
+ }
1017
+ for part in &complex.parts {
1018
+ for test in part {
1019
+ if let Test::Pseudo(name, argument) = test {
1020
+ if name == "scope"
1021
+ || position(name)
1022
+ || (matches!(name.as_str(), "not" | "is" | "where" | "matches")
1023
+ && has_position(argument)?)
1024
+ {
1025
+ return Ok(false);
1026
+ }
1027
+ }
1028
+ }
1029
+ }
1030
+ Ok(true)
1031
+ }
1032
+
1033
+ fn matches_expression<D: SelectDom>(dom: &D, id: u32, source: &str, scope: &[u32]) -> Result<bool> {
1034
+ for complex in parse(source)?.iter() {
1035
+ let mut memo = BackwardMemo::default();
1036
+ if matches_backwards(dom, id, complex, complex.parts.len() - 1, scope, &mut memo)? {
1037
+ return Ok(true);
1038
+ }
1039
+ }
1040
+ Ok(false)
1041
+ }
1042
+
1043
+ fn pseudo<D: SelectDom>(
1044
+ dom: &D,
1045
+ id: u32,
1046
+ name: &str,
1047
+ argument: &str,
1048
+ scope: &[u32],
1049
+ ) -> Result<bool> {
1050
+ if let Some(result) = dom.custom_pseudo(id, name, Some(argument)) {
1051
+ return Ok(result);
1052
+ }
1053
+ if let Some(alias) = dom.pseudo_alias(name) {
1054
+ return matches_expression(dom, id, alias, scope);
1055
+ }
1056
+ let node_name = dom.name(id).unwrap_or("");
1057
+ Ok(match name {
1058
+ "not" => !matches_expression(dom, id, argument, scope)?,
1059
+ "is" | "where" | "matches" => matches_expression(dom, id, argument, scope)?,
1060
+ "has" => !select_in(dom, argument, Some(&[id]))?.is_empty(),
1061
+ "contains" | "icontains" => {
1062
+ let value = unescape(argument.trim_matches(['\'', '"']));
1063
+ let text = dom.text(id);
1064
+ if name == "icontains" {
1065
+ contains(&text.to_lowercase(), &value.to_lowercase())
1066
+ } else {
1067
+ contains(&text, &value)
1068
+ }
1069
+ }
1070
+ "root" => dom.parent(id).is_none_or(|parent| !tag(dom, parent)),
1071
+ "scope" => scope.contains(&id),
1072
+ "empty" | "parent" => {
1073
+ let empty = !dom
1074
+ .children(id)
1075
+ .iter()
1076
+ .any(|child| tag(dom, *child) || !dom.text(*child).is_empty());
1077
+ if name == "empty" {
1078
+ empty
1079
+ } else {
1080
+ !empty
1081
+ }
1082
+ }
1083
+ "first-child" | "last-child" | "only-child" | "nth-child" | "nth-last-child"
1084
+ | "first-of-type" | "last-of-type" | "only-of-type" | "nth-of-type"
1085
+ | "nth-last-of-type" => {
1086
+ let mut children = siblings(dom, id);
1087
+ if name.ends_with("of-type") {
1088
+ children.retain(|child| dom.name(*child) == Some(node_name));
1089
+ }
1090
+ let mut argument = argument;
1091
+ if let Some((formula, of)) = argument.split_once(" of ") {
1092
+ argument = formula;
1093
+ children = filter_in(dom, of, &children)?;
1094
+ }
1095
+ let Some(index) = children.iter().position(|child| *child == id) else {
1096
+ return Ok(false);
1097
+ };
1098
+ match name {
1099
+ "first-child" | "first-of-type" => index == 0,
1100
+ "last-child" | "last-of-type" => index + 1 == children.len(),
1101
+ "only-child" | "only-of-type" => children.len() == 1,
1102
+ _ => nth(argument, index, children.len(), name.contains("nth-last")),
1103
+ }
1104
+ }
1105
+ "header" => matches!(node_name, "h1" | "h2" | "h3" | "h4" | "h5" | "h6"),
1106
+ "input" => matches!(node_name, "input" | "textarea" | "select" | "button"),
1107
+ "button" => {
1108
+ node_name == "button"
1109
+ || (node_name == "input" && attr_matches(dom, id, "type", "=", "button", None))
1110
+ }
1111
+ "text" => {
1112
+ node_name == "input"
1113
+ && dom.attr(id, "type").is_none_or(|kind| {
1114
+ kind.is_empty()
1115
+ || if dom.xml_mode() {
1116
+ kind == "text"
1117
+ } else {
1118
+ kind.eq_ignore_ascii_case("text")
1119
+ }
1120
+ })
1121
+ }
1122
+ "checkbox" | "file" | "password" | "radio" | "reset" | "image" | "submit" => {
1123
+ attr_matches(dom, id, "type", "=", name, None)
1124
+ }
1125
+ "selected" => selected(dom, id),
1126
+ "checked" => {
1127
+ (node_name == "input"
1128
+ && dom.attr(id, "checked").is_some()
1129
+ && (attr_matches(dom, id, "type", "=", "checkbox", None)
1130
+ || attr_matches(dom, id, "type", "=", "radio", None)))
1131
+ || selected(dom, id)
1132
+ }
1133
+ "disabled" => disabled(dom, id),
1134
+ "enabled" => !disabled(dom, id),
1135
+ "link" | "any-link" => {
1136
+ matches!(node_name, "a" | "area" | "link") && dom.attr(id, "href").is_some()
1137
+ }
1138
+ "visited" | "active" | "hover" | "focus" | "target" => false,
1139
+ "required" => {
1140
+ matches!(node_name, "input" | "select" | "textarea")
1141
+ && dom.attr(id, "required").is_some()
1142
+ }
1143
+ "optional" => {
1144
+ matches!(node_name, "input" | "select" | "textarea")
1145
+ && dom.attr(id, "required").is_none()
1146
+ }
1147
+ "read-only" => {
1148
+ dom.attr(id, "readonly").is_some() || !matches!(node_name, "input" | "textarea")
1149
+ }
1150
+ "read-write" => {
1151
+ matches!(node_name, "input" | "textarea")
1152
+ && dom.attr(id, "readonly").is_none()
1153
+ && !disabled(dom, id)
1154
+ }
1155
+ "lang" => {
1156
+ let language = unescape(argument.trim_matches(['\'', '"'])).to_ascii_lowercase();
1157
+ let mut current = Some(id);
1158
+ let mut matches = false;
1159
+ while let Some(id) = current {
1160
+ if let Some(value) = dom.attr(id, "lang").or_else(|| dom.attr(id, "xml:lang")) {
1161
+ let value = value.to_ascii_lowercase();
1162
+ matches = value == language || value.starts_with(&(language.clone() + "-"));
1163
+ break;
1164
+ }
1165
+ current = dom.parent(id);
1166
+ }
1167
+ matches
1168
+ }
1169
+ name if position(name) => true,
1170
+ _ => return Err(invalid(format!("Unknown pseudo-class :{name}"))),
1171
+ })
1172
+ }
1173
+
1174
+ /// The candidates of a compound that names an element type, from the tree's
1175
+ /// name index; `matches_compound` still tests each one.
1176
+ fn elements_named_by<'a, D: SelectDom>(dom: &'a D, tests: &[Test]) -> Option<&'a [u32]> {
1177
+ tests.iter().find_map(|test| match test {
1178
+ Test::Tag(name) => dom.elements_named(&name.to_ascii_lowercase()),
1179
+ _ => None,
1180
+ })
1181
+ }
1182
+
1183
+ fn matches_compound<D: SelectDom>(dom: &D, id: u32, tests: &[Test], scope: &[u32]) -> Result<bool> {
1184
+ if !tag(dom, id) {
1185
+ return Ok(false);
1186
+ }
1187
+ for test in tests {
1188
+ let matched = match test {
1189
+ Test::Tag(name) => {
1190
+ if !dom.lower_case_tags() {
1191
+ dom.name(id)
1192
+ .is_some_and(|actual| equal_strings(actual, name))
1193
+ } else {
1194
+ dom.name(id)
1195
+ .is_some_and(|actual| equal_strings(actual, &name.to_ascii_lowercase()))
1196
+ }
1197
+ }
1198
+ Test::Id(value) => dom
1199
+ .attr(id, "id")
1200
+ .is_some_and(|actual| equal_strings(actual, value)),
1201
+ Test::Class(value) => dom.attr(id, "class").is_some_and(|classes| {
1202
+ classes
1203
+ .split_ascii_whitespace()
1204
+ .any(|class| equal_strings(class, value))
1205
+ }),
1206
+ Test::Attribute {
1207
+ name,
1208
+ op,
1209
+ value,
1210
+ flag,
1211
+ } => attr_matches(dom, id, name, op, value, *flag),
1212
+ Test::Pseudo(name, argument) => {
1213
+ if matches!(name.as_str(), "not" | "is" | "where" | "matches")
1214
+ && has_position(argument)?
1215
+ {
1216
+ true
1217
+ } else {
1218
+ pseudo(dom, id, name, argument, scope)?
1219
+ }
1220
+ }
1221
+ };
1222
+ if !matched {
1223
+ return Ok(false);
1224
+ }
1225
+ }
1226
+ Ok(true)
1227
+ }
1228
+
1229
+ fn apply<D: SelectDom>(dom: &D, ids: Vec<u32>, tests: &[Test], scope: &[u32]) -> Result<Vec<u32>> {
1230
+ let mut result = Vec::new();
1231
+ for id in ids {
1232
+ if matches_compound(dom, id, tests, scope)? {
1233
+ result.push(id);
1234
+ }
1235
+ }
1236
+ for test in tests {
1237
+ if let Test::Pseudo(name, argument) = test {
1238
+ if position(name) {
1239
+ let len = result.len() as i64;
1240
+ let requested = argument.parse::<i64>().unwrap_or(0);
1241
+ let requested = if requested < 0 {
1242
+ len + requested
1243
+ } else {
1244
+ requested
1245
+ };
1246
+ result = result
1247
+ .into_iter()
1248
+ .enumerate()
1249
+ .filter_map(|(index, id)| {
1250
+ let index = index as i64;
1251
+ let include = match name.as_str() {
1252
+ "first" => index == 0,
1253
+ "last" => index == len - 1,
1254
+ "eq" | "nth" => index == requested,
1255
+ "lt" => index < requested,
1256
+ "gt" => index > requested,
1257
+ "even" => index % 2 == 0,
1258
+ "odd" => index % 2 == 1,
1259
+ _ => true,
1260
+ };
1261
+ include.then_some(id)
1262
+ })
1263
+ .collect();
1264
+ } else if matches!(name.as_str(), "not" | "is" | "where" | "matches")
1265
+ && has_position(argument)?
1266
+ {
1267
+ let wanted: IdSet<_> = filter_in(dom, argument, &result)?.into_iter().collect();
1268
+ result.retain(|id| wanted.contains(id) != (name == "not"));
1269
+ }
1270
+ }
1271
+ }
1272
+ Ok(result)
1273
+ }
1274
+
1275
+ /// Query descendants of contexts (the root document when omitted).
1276
+ /// Option-derived flags, read once per query rather than for every node tested.
1277
+ struct Flagged<'a, D> {
1278
+ dom: &'a D,
1279
+ xml: bool,
1280
+ lower_tags: bool,
1281
+ lower_attributes: bool,
1282
+ }
1283
+
1284
+ impl<'a, D: SelectDom> Flagged<'a, D> {
1285
+ fn new(dom: &'a D) -> Self {
1286
+ Self {
1287
+ dom,
1288
+ xml: dom.xml_mode(),
1289
+ lower_tags: dom.lower_case_tags(),
1290
+ lower_attributes: dom.lower_case_attribute_names(),
1291
+ }
1292
+ }
1293
+ }
1294
+
1295
+ impl<D: SelectDom> SelectDom for Flagged<'_, D> {
1296
+ fn kind(&self, id: u32) -> &str {
1297
+ self.dom.kind(id)
1298
+ }
1299
+ fn name(&self, id: u32) -> Option<&str> {
1300
+ self.dom.name(id)
1301
+ }
1302
+ fn attr(&self, id: u32, name: &str) -> Option<&str> {
1303
+ self.dom.attr(id, name)
1304
+ }
1305
+ fn parent(&self, id: u32) -> Option<u32> {
1306
+ self.dom.parent(id)
1307
+ }
1308
+ fn children(&self, id: u32) -> &[u32] {
1309
+ self.dom.children(id)
1310
+ }
1311
+ fn text(&self, id: u32) -> String {
1312
+ self.dom.text(id)
1313
+ }
1314
+ fn xml_mode(&self) -> bool {
1315
+ self.xml
1316
+ }
1317
+ fn lower_case_tags(&self) -> bool {
1318
+ self.lower_tags
1319
+ }
1320
+ fn lower_case_attribute_names(&self) -> bool {
1321
+ self.lower_attributes
1322
+ }
1323
+ fn custom_pseudo(&self, id: u32, name: &str, argument: Option<&str>) -> Option<bool> {
1324
+ self.dom.custom_pseudo(id, name, argument)
1325
+ }
1326
+ fn pseudo_alias(&self, name: &str) -> Option<&str> {
1327
+ self.dom.pseudo_alias(name)
1328
+ }
1329
+ fn elements_named(&self, lowercase_name: &str) -> Option<&[u32]> {
1330
+ self.dom.elements_named(lowercase_name)
1331
+ }
1332
+ fn is_id_order_document_order(&self) -> bool {
1333
+ self.dom.is_id_order_document_order()
1334
+ }
1335
+ }
1336
+
1337
+ pub(crate) fn select<D: SelectDom>(
1338
+ dom: &D,
1339
+ source: &str,
1340
+ contexts: Option<&[u32]>,
1341
+ ) -> Result<Vec<u32>> {
1342
+ select_in(&Flagged::new(dom), source, contexts)
1343
+ }
1344
+
1345
+ /// Filter a supplied selection, applying positional pseudos to that selection.
1346
+ pub(crate) fn filter<D: SelectDom>(dom: &D, source: &str, ids: &[u32]) -> Result<Vec<u32>> {
1347
+ filter_in(&Flagged::new(dom), source, ids)
1348
+ }
1349
+
1350
+ fn select_in<D: SelectDom>(dom: &D, source: &str, contexts: Option<&[u32]>) -> Result<Vec<u32>> {
1351
+ let scope = contexts.unwrap_or(&[0]);
1352
+ let complexes = parse(source)?;
1353
+ // A compound over one subtree already follows DOM order. Avoid walking
1354
+ // the entire document again to sort an already ordered result.
1355
+ let ordered_compound = complexes.len() == 1
1356
+ && complexes[0].parts.len() == 1
1357
+ && complexes[0].leading.is_none()
1358
+ && scope.len() == 1;
1359
+ let mut result = Vec::new();
1360
+ let mut is_ordered = complexes.len() == 1 && scope.len() == 1;
1361
+ for complex in complexes.iter() {
1362
+ validate(dom, complex)?;
1363
+ if is_backward_safe(complex)? {
1364
+ // As in Cheerio, results lie within the scope, and elements matched
1365
+ // by earlier compounds may be the scope itself but not above it.
1366
+ // Candidates are in document order, and each is tested once.
1367
+ let last = complex.parts.len() - 1;
1368
+ let mut memo = BackwardMemo::default();
1369
+ if let Some(named) = (scope == [0] && !tag(dom, 0))
1370
+ .then(|| elements_named_by(dom, &complex.parts[last]))
1371
+ .flatten()
1372
+ {
1373
+ for id in named {
1374
+ if matches_backwards_within(dom, *id, complex, last, scope, None, &mut memo)? {
1375
+ result.push(*id);
1376
+ }
1377
+ }
1378
+ continue;
1379
+ }
1380
+ if scope == [0] && !tag(dom, 0) {
1381
+ // Test each node while the walk has it in cache, without a candidate list.
1382
+ let mut failure = None;
1383
+ for_each_descendant(dom, 0, |id| {
1384
+ match matches_backwards_within(dom, id, complex, last, scope, None, &mut memo) {
1385
+ Ok(true) => result.push(id),
1386
+ Ok(false) => {}
1387
+ Err(error) => failure = Some(error),
1388
+ }
1389
+ failure.is_none()
1390
+ });
1391
+ if let Some(error) = failure {
1392
+ return Err(error);
1393
+ }
1394
+ continue;
1395
+ }
1396
+ let candidates = descendants(dom, scope);
1397
+ let allowed: Option<IdSet<u32>> = (scope != [0] || tag(dom, 0))
1398
+ .then(|| scope.iter().chain(&candidates).copied().collect());
1399
+ for id in candidates {
1400
+ if matches_backwards_within(
1401
+ dom,
1402
+ id,
1403
+ complex,
1404
+ last,
1405
+ scope,
1406
+ allowed.as_ref(),
1407
+ &mut memo,
1408
+ )? {
1409
+ result.push(id);
1410
+ }
1411
+ }
1412
+ continue;
1413
+ }
1414
+ is_ordered &= ordered_compound;
1415
+ let named = (scope == [0] && complex.parts.len() == 1 && !tag(dom, 0))
1416
+ .then(|| elements_named_by(dom, &complex.parts[0]))
1417
+ .flatten();
1418
+ let mut candidates = if let Some(leading) = complex.leading {
1419
+ expand(dom, scope, leading)
1420
+ } else if let Some(named) = named {
1421
+ named.to_vec()
1422
+ } else {
1423
+ descendants(dom, scope)
1424
+ };
1425
+ if complex.parts[0]
1426
+ .iter()
1427
+ .any(|test| matches!(test,Test::Pseudo(name,_) if name=="scope"))
1428
+ {
1429
+ candidates = unique(scope.iter().copied().chain(candidates));
1430
+ }
1431
+ let mut current = apply(dom, candidates, &complex.parts[0], scope)?;
1432
+ for (index, part) in complex.parts.iter().enumerate().skip(1) {
1433
+ current = apply(
1434
+ dom,
1435
+ expand(dom, &current, complex.combinators[index - 1]),
1436
+ part,
1437
+ scope,
1438
+ )?;
1439
+ }
1440
+ result.extend(current);
1441
+ }
1442
+ if is_ordered {
1443
+ return Ok(result);
1444
+ }
1445
+ if dom.is_id_order_document_order() {
1446
+ result.sort_unstable();
1447
+ result.dedup();
1448
+ return Ok(result);
1449
+ }
1450
+ let wanted: IdSet<u32> = result.iter().copied().collect();
1451
+ // Stable IDs are allocation IDs after mutations; obtain actual DOM order.
1452
+ let ordered = descendants(dom, &[0]);
1453
+ let mut sorted: Vec<u32> = ordered
1454
+ .into_iter()
1455
+ .filter(|id| wanted.contains(id))
1456
+ .collect();
1457
+ let attached: IdSet<u32> = sorted.iter().copied().collect();
1458
+ sorted.extend(
1459
+ unique(result)
1460
+ .into_iter()
1461
+ .filter(|id| !attached.contains(id)),
1462
+ );
1463
+ Ok(sorted)
1464
+ }
1465
+
1466
+ fn filter_in<D: SelectDom>(dom: &D, source: &str, ids: &[u32]) -> Result<Vec<u32>> {
1467
+ let mut wanted = IdSet::default();
1468
+ for complex in parse(source)?.iter() {
1469
+ validate(dom, complex)?;
1470
+ let candidates = if complex.parts.len() == 1 {
1471
+ apply(dom, ids.to_vec(), &complex.parts[0], ids)?
1472
+ } else {
1473
+ let mut result = Vec::new();
1474
+ let mut memo = BackwardMemo::default();
1475
+ for id in ids {
1476
+ if matches_backwards(dom, *id, complex, complex.parts.len() - 1, ids, &mut memo)? {
1477
+ result.push(*id);
1478
+ }
1479
+ }
1480
+ result
1481
+ };
1482
+ wanted.extend(candidates);
1483
+ }
1484
+ Ok(ids
1485
+ .iter()
1486
+ .copied()
1487
+ .filter(|id| wanted.contains(id))
1488
+ .collect())
1489
+ }
1490
+
1491
+ #[cfg(test)]
1492
+ mod tests {
1493
+ use super::*;
1494
+ use crate::arena::parse_xml;
1495
+ use serde_json::json;
1496
+
1497
+ fn fixture() -> crate::arena::DomArena {
1498
+ parse_xml("<main><ul id='list'><li class='a' data-n='A'>one</li><li class='b'>two <b>B</b></li><li class='a'>three</li><li>four</li></ul><p id='escaped:id'>end</p></main>",json!({"xmlMode":false,"_useHtmlParser2":true}))
1499
+ }
1500
+
1501
+ #[test]
1502
+ fn selectors_and_combinators() {
1503
+ let dom = fixture();
1504
+ for (source, count) in [
1505
+ ("li", 4),
1506
+ ("main > ul > li.a", 2),
1507
+ ("li.a + li", 2),
1508
+ ("li.b ~ li", 2),
1509
+ ("ul:has(b)", 1),
1510
+ ("li:contains(two)", 1),
1511
+ ("li:not(.a)", 2),
1512
+ ("li:is(.a,.b)", 3),
1513
+ ("[data-n='a' i]", 1),
1514
+ ("#escaped\\:id", 1),
1515
+ ] {
1516
+ assert_eq!(select(&dom, source, None).unwrap().len(), count, "{source}");
1517
+ }
1518
+ }
1519
+
1520
+ #[test]
1521
+ fn selectors_compare_logical_utf16_and_css_escape_values() {
1522
+ let high = crate::codec::from_units(&[0xd83d]);
1523
+ let low = crate::codec::from_units(&[0xde00]);
1524
+ let literal = crate::codec::encode_scalar('\u{e03d}');
1525
+ let dom = parse_xml(
1526
+ &format!("<main><p id='emoji' title='😀'>😀</p><p id='lone' title='{high}'>{high}</p><p id='literal' title='{literal}'>{literal}</p><p title='café'>text</p></main>"),
1527
+ json!({"xmlMode":false,"_useHtmlParser2":true,"__losslessUnicode":true}),
1528
+ );
1529
+ assert_eq!(
1530
+ select(&dom, &format!("p:contains('{high}')"), None)
1531
+ .unwrap()
1532
+ .len(),
1533
+ 2
1534
+ );
1535
+ assert_eq!(
1536
+ select(&dom, &format!("p[title^='{high}']"), None)
1537
+ .unwrap()
1538
+ .len(),
1539
+ 2
1540
+ );
1541
+ assert_eq!(
1542
+ select(&dom, &format!("p[title$='{low}']"), None)
1543
+ .unwrap()
1544
+ .len(),
1545
+ 1
1546
+ );
1547
+ assert_eq!(
1548
+ select(&dom, &format!("p[title*='{literal}']"), None)
1549
+ .unwrap()
1550
+ .len(),
1551
+ 1
1552
+ );
1553
+ assert_eq!(
1554
+ select(&dom, "p[title='\\d83d\\de00']", None).unwrap().len(),
1555
+ 1
1556
+ );
1557
+ assert_eq!(select(&dom, "p:contains('\\d83d')", None).unwrap().len(), 2);
1558
+ assert_eq!(select(&dom, "p[title=CAFÉ i]", None).unwrap().len(), 1);
1559
+ }
1560
+
1561
+ #[test]
1562
+ fn positional_and_structural() {
1563
+ let dom = fixture();
1564
+ for (source, count) in [
1565
+ ("li:first", 1),
1566
+ ("li:last", 1),
1567
+ ("li:eq(-1)", 1),
1568
+ ("li:lt(2)", 2),
1569
+ ("li:gt(1)", 2),
1570
+ ("li:even", 2),
1571
+ ("li:not(:first)", 3),
1572
+ ("li:nth-child(2n+1)", 2),
1573
+ ("li:nth-last-child(2)", 1),
1574
+ ("li:first-child", 1),
1575
+ ("li:last-child", 1),
1576
+ ("ul:only-child", 0),
1577
+ ] {
1578
+ assert_eq!(select(&dom, source, None).unwrap().len(), count, "{source}");
1579
+ }
1580
+ }
1581
+
1582
+ #[test]
1583
+ fn scoped_and_relative_selection() {
1584
+ let dom = fixture();
1585
+ let ul = select(&dom, "ul", None).unwrap();
1586
+ assert_eq!(select(&dom, "> li", Some(&ul)).unwrap().len(), 4);
1587
+ assert_eq!(select(&dom, "main li", Some(&ul)).unwrap().len(), 0);
1588
+ assert_eq!(select(&dom, ":scope > li", Some(&ul)).unwrap().len(), 4);
1589
+ let ids = select(&dom, "li", None).unwrap();
1590
+ assert_eq!(filter(&dom, ":odd", &ids).unwrap(), vec![ids[1], ids[3]]);
1591
+ assert_eq!(
1592
+ filter(&dom, "li.a + li", &ids).unwrap(),
1593
+ vec![ids[1], ids[3]]
1594
+ );
1595
+ }
1596
+ }