Skip to main content

script/dom/xpath/
xpathresult.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6
7use dom_struct::dom_struct;
8use js::context::{JSContext, NoGC};
9use script_bindings::cell::DomRefCell;
10use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
11use script_bindings::reflector::{Reflector, reflect_dom_object};
12
13use crate::dom::bindings::codegen::Bindings::XPathResultBinding::{
14    XPathResultConstants, XPathResultMethods,
15};
16use crate::dom::bindings::error::{Error, Fallible};
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::bindings::root::{Dom, DomRoot};
19use crate::dom::bindings::str::DOMString;
20use crate::dom::node::Node;
21use crate::dom::window::Window;
22use crate::xpath::Value;
23
24#[repr(u16)]
25#[derive(Clone, Copy, Debug, Eq, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
26pub(crate) enum XPathResultType {
27    Any = XPathResultConstants::ANY_TYPE,
28    Number = XPathResultConstants::NUMBER_TYPE,
29    String = XPathResultConstants::STRING_TYPE,
30    Boolean = XPathResultConstants::BOOLEAN_TYPE,
31    UnorderedNodeIterator = XPathResultConstants::UNORDERED_NODE_ITERATOR_TYPE,
32    OrderedNodeIterator = XPathResultConstants::ORDERED_NODE_ITERATOR_TYPE,
33    UnorderedNodeSnapshot = XPathResultConstants::UNORDERED_NODE_SNAPSHOT_TYPE,
34    OrderedNodeSnapshot = XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE,
35    AnyUnorderedNode = XPathResultConstants::ANY_UNORDERED_NODE_TYPE,
36    FirstOrderedNode = XPathResultConstants::FIRST_ORDERED_NODE_TYPE,
37}
38
39impl TryFrom<u16> for XPathResultType {
40    type Error = ();
41
42    fn try_from(value: u16) -> Result<Self, Self::Error> {
43        match value {
44            XPathResultConstants::ANY_TYPE => Ok(Self::Any),
45            XPathResultConstants::NUMBER_TYPE => Ok(Self::Number),
46            XPathResultConstants::STRING_TYPE => Ok(Self::String),
47            XPathResultConstants::BOOLEAN_TYPE => Ok(Self::Boolean),
48            XPathResultConstants::UNORDERED_NODE_ITERATOR_TYPE => Ok(Self::UnorderedNodeIterator),
49            XPathResultConstants::ORDERED_NODE_ITERATOR_TYPE => Ok(Self::OrderedNodeIterator),
50            XPathResultConstants::UNORDERED_NODE_SNAPSHOT_TYPE => Ok(Self::UnorderedNodeSnapshot),
51            XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE => Ok(Self::OrderedNodeSnapshot),
52            XPathResultConstants::ANY_UNORDERED_NODE_TYPE => Ok(Self::AnyUnorderedNode),
53            XPathResultConstants::FIRST_ORDERED_NODE_TYPE => Ok(Self::FirstOrderedNode),
54            _ => Err(()),
55        }
56    }
57}
58
59#[derive(Debug, JSTraceable, MallocSizeOf)]
60#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
61enum XPathResultValue {
62    Boolean(bool),
63    /// A IEEE-754 double-precision floating point number
64    Number(f64),
65    String(DOMString),
66    /// A collection of unique nodes
67    Nodeset(Vec<Dom<Node>>),
68}
69
70impl From<Value> for XPathResultValue {
71    fn from(value: Value) -> Self {
72        match value {
73            Value::Boolean(b) => XPathResultValue::Boolean(b),
74            Value::Number(n) => XPathResultValue::Number(n),
75            Value::String(s) => XPathResultValue::String(s.into()),
76            Value::NodeSet(nodes) => XPathResultValue::Nodeset(
77                nodes
78                    .into_iter()
79                    .map(|xpath_node| xpath_node.0.as_traced())
80                    .collect(),
81            ),
82        }
83    }
84}
85
86#[dom_struct]
87pub(crate) struct XPathResult {
88    reflector_: Reflector,
89    window: Dom<Window>,
90    /// The revision of the owner document when this result was created. When iterating over the
91    /// values in the result, this is used to invalidate the iterator when the document is modified.
92    version: Cell<u64>,
93    result_type: Cell<XPathResultType>,
94    value: DomRefCell<XPathResultValue>,
95    iterator_pos: Cell<usize>,
96}
97
98impl XPathResult {
99    fn new_inherited(window: &Window, result_type: XPathResultType, value: Value) -> XPathResult {
100        XPathResult {
101            reflector_: Reflector::new(),
102            window: Dom::from_ref(window),
103            version: Cell::new(
104                window
105                    .Document()
106                    .upcast::<Node>()
107                    .inclusive_descendants_version(),
108            ),
109            result_type: Cell::new(result_type),
110            iterator_pos: Cell::new(0),
111            value: DomRefCell::new(value.into()),
112        }
113    }
114
115    fn document_changed_since_creation(&self) -> bool {
116        let current_document_version = self
117            .window
118            .Document()
119            .upcast::<Node>()
120            .inclusive_descendants_version();
121        current_document_version != self.version.get()
122    }
123
124    /// NB: Blindly trusts `result_type` and constructs an object regardless of the contents
125    /// of `value`. The exception is `XPathResultType::Any`, for which we look at the value
126    /// to determine the type.
127    pub(crate) fn new(
128        cx: &mut JSContext,
129        window: &Window,
130        result_type: XPathResultType,
131        value: Value,
132    ) -> DomRoot<XPathResult> {
133        reflect_dom_object(
134            cx,
135            Box::new(XPathResult::new_inherited(window, result_type, value)),
136            window,
137        )
138    }
139
140    pub(crate) fn reinitialize_with(
141        &self,
142        no_gc: &NoGC,
143        result_type: XPathResultType,
144        value: Value,
145    ) {
146        self.result_type.set(result_type);
147        *self.value.safe_borrow_mut(no_gc) = value.into();
148        self.version.set(
149            self.window
150                .Document()
151                .upcast::<Node>()
152                .inclusive_descendants_version(),
153        );
154        self.iterator_pos.set(0);
155    }
156}
157
158impl XPathResultMethods<crate::DomTypeHolder> for XPathResult {
159    /// <https://dom.spec.whatwg.org/#dom-xpathresult-resulttype>
160    fn ResultType(&self) -> u16 {
161        self.result_type.get() as u16
162    }
163
164    /// <https://dom.spec.whatwg.org/#dom-xpathresult-numbervalue>
165    fn GetNumberValue(&self) -> Fallible<f64> {
166        match (&*self.value.borrow(), self.result_type.get()) {
167            (XPathResultValue::Number(n), XPathResultType::Number) => Ok(*n),
168            _ => Err(Error::Type(
169                c"Can't get number value for non-number XPathResult".to_owned(),
170            )),
171        }
172    }
173
174    /// <https://dom.spec.whatwg.org/#dom-xpathresult-stringvalue>
175    fn GetStringValue(&self) -> Fallible<DOMString> {
176        match (&*self.value.borrow(), self.result_type.get()) {
177            (XPathResultValue::String(s), XPathResultType::String) => Ok(s.clone()),
178            _ => Err(Error::Type(
179                c"Can't get string value for non-string XPathResult".to_owned(),
180            )),
181        }
182    }
183
184    /// <https://dom.spec.whatwg.org/#dom-xpathresult-booleanvalue>
185    fn GetBooleanValue(&self) -> Fallible<bool> {
186        match (&*self.value.borrow(), self.result_type.get()) {
187            (XPathResultValue::Boolean(b), XPathResultType::Boolean) => Ok(*b),
188            _ => Err(Error::Type(
189                c"Can't get boolean value for non-boolean XPathResult".to_owned(),
190            )),
191        }
192    }
193
194    /// <https://dom.spec.whatwg.org/#dom-xpathresult-iteratenext>
195    fn IterateNext(&self) -> Fallible<Option<DomRoot<Node>>> {
196        if !matches!(
197            self.result_type.get(),
198            XPathResultType::OrderedNodeIterator | XPathResultType::UnorderedNodeIterator
199        ) {
200            return Err(Error::Type(c"Result is not an iterator".into()));
201        }
202
203        if self.document_changed_since_creation() {
204            return Err(Error::InvalidState(None));
205        }
206
207        let XPathResultValue::Nodeset(nodes) = &*self.value.borrow() else {
208            return Err(Error::Type(
209                c"Can't iterate on XPathResult that is not a node-set".to_owned(),
210            ));
211        };
212
213        let position = self.iterator_pos.get();
214        if position >= nodes.len() {
215            Ok(None)
216        } else {
217            let node = nodes[position].as_rooted();
218            self.iterator_pos.set(position + 1);
219            Ok(Some(node))
220        }
221    }
222
223    /// <https://dom.spec.whatwg.org/#dom-xpathresult-invaliditeratorstate>
224    fn InvalidIteratorState(&self) -> bool {
225        let is_iterable = matches!(
226            self.result_type.get(),
227            XPathResultType::OrderedNodeIterator | XPathResultType::UnorderedNodeIterator
228        );
229
230        is_iterable && self.document_changed_since_creation()
231    }
232
233    /// <https://dom.spec.whatwg.org/#dom-xpathresult-snapshotlength>
234    fn GetSnapshotLength(&self) -> Fallible<u32> {
235        match (&*self.value.borrow(), self.result_type.get()) {
236            (
237                XPathResultValue::Nodeset(nodes),
238                XPathResultType::OrderedNodeSnapshot | XPathResultType::UnorderedNodeSnapshot,
239            ) => Ok(nodes.len() as u32),
240            _ => Err(Error::Type(
241                c"Can't get snapshot length of XPathResult that is not a snapshot".to_owned(),
242            )),
243        }
244    }
245
246    /// <https://dom.spec.whatwg.org/#dom-xpathresult-snapshotitem>
247    fn SnapshotItem(&self, index: u32) -> Fallible<Option<DomRoot<Node>>> {
248        match (&*self.value.borrow(), self.result_type.get()) {
249            (
250                XPathResultValue::Nodeset(nodes),
251                XPathResultType::OrderedNodeSnapshot | XPathResultType::UnorderedNodeSnapshot,
252            ) => Ok(nodes.get(index as usize).map(|node| node.as_rooted())),
253            _ => Err(Error::Type(
254                c"Can't get snapshot item of XPathResult that is not a snapshot".to_owned(),
255            )),
256        }
257    }
258
259    /// <https://dom.spec.whatwg.org/#dom-xpathresult-singlenodevalue>
260    fn GetSingleNodeValue(&self) -> Fallible<Option<DomRoot<Node>>> {
261        match (&*self.value.borrow(), self.result_type.get()) {
262            (
263                XPathResultValue::Nodeset(nodes),
264                XPathResultType::AnyUnorderedNode | XPathResultType::FirstOrderedNode,
265            ) => Ok(nodes.first().map(|node| node.as_rooted())),
266            _ => Err(Error::Type(
267                c"Getting single value requires result type 'any unordered node' or 'first ordered node'".to_owned(),
268            )),
269        }
270    }
271}