script/dom/
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::rust::HandleObject;
9
10use crate::dom::bindings::codegen::Bindings::XPathResultBinding::{
11    XPathResultConstants, XPathResultMethods,
12};
13use crate::dom::bindings::error::{Error, Fallible};
14use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
15use crate::dom::bindings::root::{Dom, DomRoot};
16use crate::dom::bindings::str::DOMString;
17use crate::dom::node::Node;
18use crate::dom::window::Window;
19use crate::script_runtime::CanGc;
20use crate::xpath::{NodesetHelpers, Value};
21
22#[repr(u16)]
23#[derive(Clone, Copy, Debug, Eq, JSTraceable, MallocSizeOf, Ord, PartialEq, PartialOrd)]
24pub(crate) enum XPathResultType {
25    Any = XPathResultConstants::ANY_TYPE,
26    Number = XPathResultConstants::NUMBER_TYPE,
27    String = XPathResultConstants::STRING_TYPE,
28    Boolean = XPathResultConstants::BOOLEAN_TYPE,
29    UnorderedNodeIterator = XPathResultConstants::UNORDERED_NODE_ITERATOR_TYPE,
30    OrderedNodeIterator = XPathResultConstants::ORDERED_NODE_ITERATOR_TYPE,
31    UnorderedNodeSnapshot = XPathResultConstants::UNORDERED_NODE_SNAPSHOT_TYPE,
32    OrderedNodeSnapshot = XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE,
33    AnyUnorderedNode = XPathResultConstants::ANY_UNORDERED_NODE_TYPE,
34    FirstOrderedNode = XPathResultConstants::FIRST_ORDERED_NODE_TYPE,
35}
36
37impl TryFrom<u16> for XPathResultType {
38    type Error = ();
39
40    fn try_from(value: u16) -> Result<Self, Self::Error> {
41        match value {
42            XPathResultConstants::ANY_TYPE => Ok(Self::Any),
43            XPathResultConstants::NUMBER_TYPE => Ok(Self::Number),
44            XPathResultConstants::STRING_TYPE => Ok(Self::String),
45            XPathResultConstants::BOOLEAN_TYPE => Ok(Self::Boolean),
46            XPathResultConstants::UNORDERED_NODE_ITERATOR_TYPE => Ok(Self::UnorderedNodeIterator),
47            XPathResultConstants::ORDERED_NODE_ITERATOR_TYPE => Ok(Self::OrderedNodeIterator),
48            XPathResultConstants::UNORDERED_NODE_SNAPSHOT_TYPE => Ok(Self::UnorderedNodeSnapshot),
49            XPathResultConstants::ORDERED_NODE_SNAPSHOT_TYPE => Ok(Self::OrderedNodeSnapshot),
50            XPathResultConstants::ANY_UNORDERED_NODE_TYPE => Ok(Self::AnyUnorderedNode),
51            XPathResultConstants::FIRST_ORDERED_NODE_TYPE => Ok(Self::FirstOrderedNode),
52            _ => Err(()),
53        }
54    }
55}
56
57#[derive(Debug, JSTraceable, MallocSizeOf)]
58pub(crate) enum XPathResultValue {
59    Boolean(bool),
60    /// A IEEE-754 double-precision floating point number
61    Number(f64),
62    String(DOMString),
63    /// A collection of unique nodes
64    Nodeset(Vec<DomRoot<Node>>),
65}
66
67impl From<Value> for XPathResultValue {
68    fn from(value: Value) -> Self {
69        match value {
70            Value::Boolean(b) => XPathResultValue::Boolean(b),
71            Value::Number(n) => XPathResultValue::Number(n),
72            Value::String(s) => XPathResultValue::String(s.into()),
73            Value::Nodeset(nodes) => {
74                // Put the evaluation result into (unique) document order. This also re-roots them
75                // so that we are sure we can hold them for the lifetime of this XPathResult.
76                let rooted_nodes = nodes.document_order_unique();
77                XPathResultValue::Nodeset(rooted_nodes)
78            },
79        }
80    }
81}
82
83#[dom_struct]
84pub(crate) struct XPathResult {
85    reflector_: Reflector,
86    window: Dom<Window>,
87    result_type: XPathResultType,
88    value: XPathResultValue,
89    iterator_invalid: Cell<bool>,
90    iterator_pos: Cell<usize>,
91}
92
93impl XPathResult {
94    fn new_inherited(
95        window: &Window,
96        result_type: XPathResultType,
97        value: XPathResultValue,
98    ) -> XPathResult {
99        // TODO(vlindhol): if the wanted result type is AnyUnorderedNode | FirstOrderedNode,
100        // we could drop all nodes except one to save memory.
101        let inferred_result_type = if result_type == XPathResultType::Any {
102            match value {
103                XPathResultValue::Boolean(_) => XPathResultType::Boolean,
104                XPathResultValue::Number(_) => XPathResultType::Number,
105                XPathResultValue::String(_) => XPathResultType::String,
106                XPathResultValue::Nodeset(_) => XPathResultType::UnorderedNodeIterator,
107            }
108        } else {
109            result_type
110        };
111
112        XPathResult {
113            reflector_: Reflector::new(),
114            window: Dom::from_ref(window),
115            result_type: inferred_result_type,
116            iterator_invalid: Cell::new(false),
117            iterator_pos: Cell::new(0),
118            value,
119        }
120    }
121
122    /// NB: Blindly trusts `result_type` and constructs an object regardless of the contents
123    /// of `value`. The exception is `XPathResultType::Any`, for which we look at the value
124    /// to determine the type.
125    pub(crate) fn new(
126        window: &Window,
127        proto: Option<HandleObject>,
128        can_gc: CanGc,
129        result_type: XPathResultType,
130        value: XPathResultValue,
131    ) -> DomRoot<XPathResult> {
132        reflect_dom_object_with_proto(
133            Box::new(XPathResult::new_inherited(window, result_type, value)),
134            window,
135            proto,
136            can_gc,
137        )
138    }
139}
140
141impl XPathResultMethods<crate::DomTypeHolder> for XPathResult {
142    /// <https://dom.spec.whatwg.org/#dom-xpathresult-resulttype>
143    fn ResultType(&self) -> u16 {
144        self.result_type as u16
145    }
146
147    /// <https://dom.spec.whatwg.org/#dom-xpathresult-numbervalue>
148    fn GetNumberValue(&self) -> Fallible<f64> {
149        match (&self.value, self.result_type) {
150            (XPathResultValue::Number(n), XPathResultType::Number) => Ok(*n),
151            _ => Err(Error::Type(
152                "Can't get number value for non-number XPathResult".to_string(),
153            )),
154        }
155    }
156
157    /// <https://dom.spec.whatwg.org/#dom-xpathresult-stringvalue>
158    fn GetStringValue(&self) -> Fallible<DOMString> {
159        match (&self.value, self.result_type) {
160            (XPathResultValue::String(s), XPathResultType::String) => Ok(s.clone()),
161            _ => Err(Error::Type(
162                "Can't get string value for non-string XPathResult".to_string(),
163            )),
164        }
165    }
166
167    /// <https://dom.spec.whatwg.org/#dom-xpathresult-booleanvalue>
168    fn GetBooleanValue(&self) -> Fallible<bool> {
169        match (&self.value, self.result_type) {
170            (XPathResultValue::Boolean(b), XPathResultType::Boolean) => Ok(*b),
171            _ => Err(Error::Type(
172                "Can't get boolean value for non-boolean XPathResult".to_string(),
173            )),
174        }
175    }
176
177    /// <https://dom.spec.whatwg.org/#dom-xpathresult-iteratenext>
178    fn IterateNext(&self) -> Fallible<Option<DomRoot<Node>>> {
179        // TODO(vlindhol): actually set `iterator_invalid` somewhere
180        if self.iterator_invalid.get() {
181            return Err(Error::Range(
182                "Invalidated iterator for XPathResult, the DOM has mutated.".to_string(),
183            ));
184        }
185
186        match (&self.value, self.result_type) {
187            (
188                XPathResultValue::Nodeset(nodes),
189                XPathResultType::OrderedNodeIterator | XPathResultType::UnorderedNodeIterator,
190            ) => {
191                let pos = self.iterator_pos.get();
192                if pos >= nodes.len() {
193                    Ok(None)
194                } else {
195                    let node = nodes[pos].clone();
196                    self.iterator_pos.set(pos + 1);
197                    Ok(Some(node))
198                }
199            },
200            _ => Err(Error::Type(
201                "Can't iterate on XPathResult that is not a node-set".to_string(),
202            )),
203        }
204    }
205
206    /// <https://dom.spec.whatwg.org/#dom-xpathresult-invaliditeratorstate>
207    fn GetInvalidIteratorState(&self) -> Fallible<bool> {
208        let is_iterator_invalid = self.iterator_invalid.get();
209        if is_iterator_invalid ||
210            matches!(
211                self.result_type,
212                XPathResultType::OrderedNodeIterator | XPathResultType::UnorderedNodeIterator
213            )
214        {
215            Ok(is_iterator_invalid)
216        } else {
217            Err(Error::Type(
218                "Can't iterate on XPathResult that is not a node-set".to_string(),
219            ))
220        }
221    }
222
223    /// <https://dom.spec.whatwg.org/#dom-xpathresult-snapshotlength>
224    fn GetSnapshotLength(&self) -> Fallible<u32> {
225        match (&self.value, self.result_type) {
226            (
227                XPathResultValue::Nodeset(nodes),
228                XPathResultType::OrderedNodeSnapshot | XPathResultType::UnorderedNodeSnapshot,
229            ) => Ok(nodes.len() as u32),
230            _ => Err(Error::Type(
231                "Can't get snapshot length of XPathResult that is not a snapshot".to_string(),
232            )),
233        }
234    }
235
236    /// <https://dom.spec.whatwg.org/#dom-xpathresult-snapshotitem>
237    fn SnapshotItem(&self, index: u32) -> Fallible<Option<DomRoot<Node>>> {
238        match (&self.value, self.result_type) {
239            (
240                XPathResultValue::Nodeset(nodes),
241                XPathResultType::OrderedNodeSnapshot | XPathResultType::UnorderedNodeSnapshot,
242            ) => Ok(nodes.get(index as usize).cloned()),
243            _ => Err(Error::Type(
244                "Can't get snapshot item of XPathResult that is not a snapshot".to_string(),
245            )),
246        }
247    }
248
249    /// <https://dom.spec.whatwg.org/#dom-xpathresult-singlenodevalue>
250    fn GetSingleNodeValue(&self) -> Fallible<Option<DomRoot<Node>>> {
251        match (&self.value, self.result_type) {
252            (
253                XPathResultValue::Nodeset(nodes),
254                XPathResultType::AnyUnorderedNode | XPathResultType::FirstOrderedNode,
255            ) => Ok(nodes.first().cloned()),
256            _ => Err(Error::Type(
257                "Getting single value requires result type 'any unordered node' or 'first ordered node'".to_string(),
258            )),
259        }
260    }
261}