1/*
2 * Copyright (C) 2005 Frerich Raabe <raabe@kde.org>
3 * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "config.h"
29#include "XPathStep.h"
30
31#include "Attr.h"
32#include "Document.h"
33#include "HTMLElement.h"
34#include "NodeTraversal.h"
35#include "XMLNSNames.h"
36#include "XPathParser.h"
37#include "XPathUtil.h"
38
39namespace WebCore {
40namespace XPath {
41
42Step::Step(Axis axis, NodeTest nodeTest)
43 : m_axis(axis)
44 , m_nodeTest(WTFMove(nodeTest))
45{
46}
47
48Step::Step(Axis axis, NodeTest nodeTest, Vector<std::unique_ptr<Expression>> predicates)
49 : m_axis(axis)
50 , m_nodeTest(WTFMove(nodeTest))
51 , m_predicates(WTFMove(predicates))
52{
53}
54
55Step::~Step() = default;
56
57void Step::optimize()
58{
59 // Evaluate predicates as part of node test if possible to avoid building unnecessary NodeSets.
60 // E.g., there is no need to build a set of all "foo" nodes to evaluate "foo[@bar]", we can check the predicate while enumerating.
61 // This optimization can be applied to predicates that are not context node list sensitive, or to first predicate that is only context position sensitive, e.g. foo[position() mod 2 = 0].
62 Vector<std::unique_ptr<Expression>> remainingPredicates;
63 for (auto& predicate : m_predicates) {
64 if ((!predicateIsContextPositionSensitive(*predicate) || m_nodeTest.m_mergedPredicates.isEmpty()) && !predicate->isContextSizeSensitive() && remainingPredicates.isEmpty())
65 m_nodeTest.m_mergedPredicates.append(WTFMove(predicate));
66 else
67 remainingPredicates.append(WTFMove(predicate));
68 }
69 m_predicates = WTFMove(remainingPredicates);
70}
71
72void optimizeStepPair(Step& first, Step& second, bool& dropSecondStep)
73{
74 dropSecondStep = false;
75
76 if (first.m_axis != Step::DescendantOrSelfAxis)
77 return;
78
79 if (first.m_nodeTest.m_kind != Step::NodeTest::AnyNodeTest)
80 return;
81
82 if (!first.m_predicates.isEmpty())
83 return;
84
85 if (!first.m_nodeTest.m_mergedPredicates.isEmpty())
86 return;
87
88 ASSERT(first.m_nodeTest.m_data.isEmpty());
89 ASSERT(first.m_nodeTest.m_namespaceURI.isEmpty());
90
91 // Optimize the common case of "//" AKA /descendant-or-self::node()/child::NodeTest to /descendant::NodeTest.
92 if (second.m_axis != Step::ChildAxis)
93 return;
94
95 if (!second.predicatesAreContextListInsensitive())
96 return;
97
98 first.m_axis = Step::DescendantAxis;
99 first.m_nodeTest = WTFMove(second.m_nodeTest);
100 first.m_predicates = WTFMove(second.m_predicates);
101 first.optimize();
102 dropSecondStep = true;
103}
104
105bool Step::predicatesAreContextListInsensitive() const
106{
107 for (auto& predicate : m_predicates) {
108 if (predicateIsContextPositionSensitive(*predicate) || predicate->isContextSizeSensitive())
109 return false;
110 }
111
112 for (auto& predicate : m_nodeTest.m_mergedPredicates) {
113 if (predicateIsContextPositionSensitive(*predicate) || predicate->isContextSizeSensitive())
114 return false;
115 }
116
117 return true;
118}
119
120void Step::evaluate(Node& context, NodeSet& nodes) const
121{
122 EvaluationContext& evaluationContext = Expression::evaluationContext();
123 evaluationContext.position = 0;
124
125 nodesInAxis(context, nodes);
126
127 // Check predicates that couldn't be merged into node test.
128 for (auto& predicate : m_predicates) {
129 NodeSet newNodes;
130 if (!nodes.isSorted())
131 newNodes.markSorted(false);
132
133 for (unsigned j = 0; j < nodes.size(); j++) {
134 Node* node = nodes[j];
135
136 evaluationContext.node = node;
137 evaluationContext.size = nodes.size();
138 evaluationContext.position = j + 1;
139 if (evaluatePredicate(*predicate))
140 newNodes.append(node);
141 }
142
143 nodes = WTFMove(newNodes);
144 }
145}
146
147#if !ASSERT_DISABLED
148static inline Node::NodeType primaryNodeType(Step::Axis axis)
149{
150 switch (axis) {
151 case Step::AttributeAxis:
152 return Node::ATTRIBUTE_NODE;
153 default:
154 return Node::ELEMENT_NODE;
155 }
156}
157#endif
158
159// Evaluate NodeTest without considering merged predicates.
160inline bool nodeMatchesBasicTest(Node& node, Step::Axis axis, const Step::NodeTest& nodeTest)
161{
162 switch (nodeTest.m_kind) {
163 case Step::NodeTest::TextNodeTest:
164 return node.nodeType() == Node::TEXT_NODE || node.nodeType() == Node::CDATA_SECTION_NODE;
165 case Step::NodeTest::CommentNodeTest:
166 return node.nodeType() == Node::COMMENT_NODE;
167 case Step::NodeTest::ProcessingInstructionNodeTest: {
168 const AtomicString& name = nodeTest.m_data;
169 return node.nodeType() == Node::PROCESSING_INSTRUCTION_NODE && (name.isEmpty() || node.nodeName() == name);
170 }
171 case Step::NodeTest::AnyNodeTest:
172 return true;
173 case Step::NodeTest::NameTest: {
174 const AtomicString& name = nodeTest.m_data;
175 const AtomicString& namespaceURI = nodeTest.m_namespaceURI;
176
177 if (axis == Step::AttributeAxis) {
178 ASSERT(node.isAttributeNode());
179
180 // In XPath land, namespace nodes are not accessible on the attribute axis.
181 if (node.namespaceURI() == XMLNSNames::xmlnsNamespaceURI)
182 return false;
183
184 if (name == starAtom())
185 return namespaceURI.isEmpty() || node.namespaceURI() == namespaceURI;
186
187 return node.localName() == name && node.namespaceURI() == namespaceURI;
188 }
189
190 // Node test on the namespace axis is not implemented yet, the caller has a check for it.
191 ASSERT(axis != Step::NamespaceAxis);
192
193 // For other axes, the principal node type is element.
194 ASSERT(primaryNodeType(axis) == Node::ELEMENT_NODE);
195 if (!is<Element>(node))
196 return false;
197
198 if (name == starAtom())
199 return namespaceURI.isEmpty() || namespaceURI == node.namespaceURI();
200
201 if (node.document().isHTMLDocument()) {
202 if (is<HTMLElement>(node)) {
203 // Paths without namespaces should match HTML elements in HTML documents despite those having an XHTML namespace. Names are compared case-insensitively.
204 return equalIgnoringASCIICase(downcast<HTMLElement>(node).localName(), name) && (namespaceURI.isNull() || namespaceURI == node.namespaceURI());
205 }
206 // An expression without any prefix shouldn't match no-namespace nodes (because HTML5 says so).
207 return downcast<Element>(node).hasLocalName(name) && namespaceURI == node.namespaceURI() && !namespaceURI.isNull();
208 }
209 return downcast<Element>(node).hasLocalName(name) && namespaceURI == node.namespaceURI();
210 }
211 }
212 ASSERT_NOT_REACHED();
213 return false;
214}
215
216inline bool nodeMatches(Node& node, Step::Axis axis, const Step::NodeTest& nodeTest)
217{
218 if (!nodeMatchesBasicTest(node, axis, nodeTest))
219 return false;
220
221 EvaluationContext& evaluationContext = Expression::evaluationContext();
222
223 // Only the first merged predicate may depend on position.
224 ++evaluationContext.position;
225
226 for (auto& predicate : nodeTest.m_mergedPredicates) {
227 // No need to set context size - we only get here when evaluating predicates that do not depend on it.
228 evaluationContext.node = &node;
229 if (!evaluatePredicate(*predicate))
230 return false;
231 }
232
233 return true;
234}
235
236// Result nodes are ordered in axis order. Node test (including merged predicates) is applied.
237void Step::nodesInAxis(Node& context, NodeSet& nodes) const
238{
239 ASSERT(nodes.isEmpty());
240 switch (m_axis) {
241 case ChildAxis:
242 if (context.isAttributeNode()) // In XPath model, attribute nodes do not have children.
243 return;
244 for (Node* node = context.firstChild(); node; node = node->nextSibling()) {
245 if (nodeMatches(*node, ChildAxis, m_nodeTest))
246 nodes.append(node);
247 }
248 return;
249 case DescendantAxis:
250 if (context.isAttributeNode()) // In XPath model, attribute nodes do not have children.
251 return;
252 for (Node* node = context.firstChild(); node; node = NodeTraversal::next(*node, &context)) {
253 if (nodeMatches(*node, DescendantAxis, m_nodeTest))
254 nodes.append(node);
255 }
256 return;
257 case ParentAxis:
258 if (context.isAttributeNode()) {
259 Element* node = static_cast<Attr&>(context).ownerElement();
260 if (nodeMatches(*node, ParentAxis, m_nodeTest))
261 nodes.append(node);
262 } else {
263 ContainerNode* node = context.parentNode();
264 if (node && nodeMatches(*node, ParentAxis, m_nodeTest))
265 nodes.append(node);
266 }
267 return;
268 case AncestorAxis: {
269 Node* node = &context;
270 if (context.isAttributeNode()) {
271 node = static_cast<Attr&>(context).ownerElement();
272 if (nodeMatches(*node, AncestorAxis, m_nodeTest))
273 nodes.append(node);
274 }
275 for (node = node->parentNode(); node; node = node->parentNode()) {
276 if (nodeMatches(*node, AncestorAxis, m_nodeTest))
277 nodes.append(node);
278 }
279 nodes.markSorted(false);
280 return;
281 }
282 case FollowingSiblingAxis:
283 if (context.isAttributeNode())
284 return;
285 for (Node* node = context.nextSibling(); node; node = node->nextSibling()) {
286 if (nodeMatches(*node, FollowingSiblingAxis, m_nodeTest))
287 nodes.append(node);
288 }
289 return;
290 case PrecedingSiblingAxis:
291 if (context.isAttributeNode())
292 return;
293 for (Node* node = context.previousSibling(); node; node = node->previousSibling()) {
294 if (nodeMatches(*node, PrecedingSiblingAxis, m_nodeTest))
295 nodes.append(node);
296 }
297 nodes.markSorted(false);
298 return;
299 case FollowingAxis:
300 if (context.isAttributeNode()) {
301 Node* node = static_cast<Attr&>(context).ownerElement();
302 while ((node = NodeTraversal::next(*node))) {
303 if (nodeMatches(*node, FollowingAxis, m_nodeTest))
304 nodes.append(node);
305 }
306 } else {
307 for (Node* parent = &context; !isRootDomNode(parent); parent = parent->parentNode()) {
308 for (Node* node = parent->nextSibling(); node; node = node->nextSibling()) {
309 if (nodeMatches(*node, FollowingAxis, m_nodeTest))
310 nodes.append(node);
311 for (Node* child = node->firstChild(); child; child = NodeTraversal::next(*child, node)) {
312 if (nodeMatches(*child, FollowingAxis, m_nodeTest))
313 nodes.append(child);
314 }
315 }
316 }
317 }
318 return;
319 case PrecedingAxis: {
320 Node* node;
321 if (context.isAttributeNode())
322 node = static_cast<Attr&>(context).ownerElement();
323 else
324 node = &context;
325 while (ContainerNode* parent = node->parentNode()) {
326 for (node = NodeTraversal::previous(*node); node != parent; node = NodeTraversal::previous(*node)) {
327 if (nodeMatches(*node, PrecedingAxis, m_nodeTest))
328 nodes.append(node);
329 }
330 node = parent;
331 }
332 nodes.markSorted(false);
333 return;
334 }
335 case AttributeAxis: {
336 if (!is<Element>(context))
337 return;
338
339 Element& contextElement = downcast<Element>(context);
340
341 // Avoid lazily creating attribute nodes for attributes that we do not need anyway.
342 if (m_nodeTest.m_kind == NodeTest::NameTest && m_nodeTest.m_data != starAtom()) {
343 auto attr = contextElement.getAttributeNodeNS(m_nodeTest.m_namespaceURI, m_nodeTest.m_data);
344 if (attr && attr->namespaceURI() != XMLNSNames::xmlnsNamespaceURI) { // In XPath land, namespace nodes are not accessible on the attribute axis.
345 if (nodeMatches(*attr, AttributeAxis, m_nodeTest)) // Still need to check merged predicates.
346 nodes.append(WTFMove(attr));
347 }
348 return;
349 }
350
351 if (!contextElement.hasAttributes())
352 return;
353
354 for (const Attribute& attribute : contextElement.attributesIterator()) {
355 auto attr = contextElement.ensureAttr(attribute.name());
356 if (nodeMatches(attr.get(), AttributeAxis, m_nodeTest))
357 nodes.append(WTFMove(attr));
358 }
359 return;
360 }
361 case NamespaceAxis:
362 // XPath namespace nodes are not implemented yet.
363 return;
364 case SelfAxis:
365 if (nodeMatches(context, SelfAxis, m_nodeTest))
366 nodes.append(&context);
367 return;
368 case DescendantOrSelfAxis:
369 if (nodeMatches(context, DescendantOrSelfAxis, m_nodeTest))
370 nodes.append(&context);
371 if (context.isAttributeNode()) // In XPath model, attribute nodes do not have children.
372 return;
373 for (Node* node = context.firstChild(); node; node = NodeTraversal::next(*node, &context)) {
374 if (nodeMatches(*node, DescendantOrSelfAxis, m_nodeTest))
375 nodes.append(node);
376 }
377 return;
378 case AncestorOrSelfAxis: {
379 if (nodeMatches(context, AncestorOrSelfAxis, m_nodeTest))
380 nodes.append(&context);
381 Node* node = &context;
382 if (context.isAttributeNode()) {
383 node = static_cast<Attr&>(context).ownerElement();
384 if (nodeMatches(*node, AncestorOrSelfAxis, m_nodeTest))
385 nodes.append(node);
386 }
387 for (node = node->parentNode(); node; node = node->parentNode()) {
388 if (nodeMatches(*node, AncestorOrSelfAxis, m_nodeTest))
389 nodes.append(node);
390 }
391 nodes.markSorted(false);
392 return;
393 }
394 }
395 ASSERT_NOT_REACHED();
396}
397
398}
399}
400