Debian Codegraph @

net/sf/saxon/functions/DeepEqual.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.XPathContext;
12 import net.sf.saxon.expr.sort.AtomicComparer;
13 import net.sf.saxon.expr.sort.GenericAtomicComparer;
14 import net.sf.saxon.lib.UnfailingErrorListener;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.pattern.SameNameTest;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.tree.iter.AtomicIterator;
19 import net.sf.saxon.tree.iter.AxisIterator;
20 import net.sf.saxon.tree.tiny.WhitespaceTextImpl;
21 import net.sf.saxon.tree.util.FastStringBuffer;
22 import net.sf.saxon.tree.util.Navigator;
23 import net.sf.saxon.tree.util.Orphan;
24 import net.sf.saxon.type.ComplexType;
25 import net.sf.saxon.type.SchemaType;
26 import net.sf.saxon.type.Type;
27 import net.sf.saxon.value.*;
28
29 import java.util.ArrayList;
30 import java.util.HashSet;
31 import java.util.List;
32
33 /**
34 * XSLT 2.0 deep-equal() function, where the collation is already known.
35 * Supports deep comparison of two sequences (of nodes and/or atomic values)
36 * optionally using a collation
37 */
38
39 public class DeepEqual extends CollatingFunctionFixed {
40
41 /**
42 * Flag indicating that two elements should only be considered equal if they have the same
43 * in-scope namespaces
44 */
45 public static final int INCLUDE_NAMESPACES = 1;
46
47 /**
48 * Flag indicating that two element or attribute nodes are considered equal only if their
49 * names use the same namespace prefix
50 */
51 public static final int INCLUDE_PREFIXES = 1 << 1;
52
53 /**
54 * Flag indicating that comment children are taken into account when comparing element or document nodes
55 */
56 public static final int INCLUDE_COMMENTS = 1 << 2;
57
58 /**
59 * Flag indicating that processing instruction nodes are taken into account when comparing element or document nodes
60 */
61 public static final int INCLUDE_PROCESSING_INSTRUCTIONS = 1 << 3;
62
63 /**
64 * Flag indicating that whitespace text nodes are ignored when comparing element nodes
65 */
66 public static final int EXCLUDE_WHITESPACE_TEXT_NODES = 1 << 4;
67
68 /**
69 * Flag indicating that elements and attributes should always be compared according to their string
70 * value, not their typed value
71 */
72 public static final int COMPARE_STRING_VALUES = 1 << 5;
73
74 /**
75 * Flag indicating that elements and attributes must have the same type annotation to be considered
76 * deep-equal
77 */
78 public static final int COMPARE_ANNOTATIONS = 1 << 6;
79
80 /**
81 * Flag indicating that a warning message explaining the reason why the sequences were deemed non-equal
82 * should be sent to the ErrorListener
83 */
84 public static final int WARNING_IF_FALSE = 1 << 7;
85
86 /**
87 * Flag indicating that adjacent text nodes in the top-level sequence are to be merged
88 */
89
90 public static final int JOIN_ADJACENT_TEXT_NODES = 1 << 8;
91
92 /**
93 * Flag indicating that the is-id and is-idref flags are to be compared
94 */
95
96 public static final int COMPARE_ID_FLAGS = 1 << 9;
97
98 /**
99 * Flag indicating that the variety of the type of a node is to be ignored (for example, a mixed content
100 * node can compare equal to an element-only content node
101 */
102
103 public static final int EXCLUDE_VARIETY = 1 << 10;
104
105
106 /**
107 * Determine when two sequences are deep-equal
108 *
109 * @param op1 the first sequence
110 * @param op2 the second sequence
111 * @param comparer the comparer to be used
112 * @param context the XPathContext item
113 * @param flags bit-significant integer giving comparison options. Always zero for standard
114 * F+O deep-equals comparison.
115 * @return true if the sequences are deep-equal
116 * @throws XPathException if either sequence contains a function item
117 */
118
119 public static boolean deepEqual(SequenceIterator op1, SequenceIterator op2,
120 AtomicComparer comparer, XPathContext context, int flags)
121 throws XPathException {
122 boolean result = true;
123 String reason = null;
124 UnfailingErrorListener listener = context.getErrorListener();
125 try {
126
127 if ((flags & JOIN_ADJACENT_TEXT_NODES) != 0) {
128 op1 = mergeAdjacentTextNodes(op1);
129 op2 = mergeAdjacentTextNodes(op2);
130 }
131 int pos1 = 0;
132 int pos2 = 0;
133 while (true) {
134 Item item1 = op1.next();
135 Item item2 = op2.next();
136
137 if (item1 == null && item2 == null) {
138 break;
139 }
140
141 pos1++;
142 pos2++;
143
144 if (item1 == null || item2 == null) {
145 result = false;
146 if (item1 == null) {
147 reason = "Second sequence is longer (first sequence length = " + pos2 + ")";
148 } else {
149 reason = "First sequence is longer (second sequence length = " + pos1 + ")";
150 }
151 if (item1 instanceof WhitespaceTextImpl || item2 instanceof WhitespaceTextImpl) {
152 reason += " (the first extra node is whitespace text)";
153 }
154 break;
155 }
156
157 if (item1 instanceof Function || item2 instanceof Function) {
158 if (!(item1 instanceof Function && item2 instanceof Function)) {
159 reason = "if one item is a function then both must be functions (position " + pos1 + ")";
160 return false;
161 }
162 // two maps or arrays can be deep-equal
163 boolean fe = ((Function) item1).deepEquals((Function) item2, context, comparer, flags);
164 if (!fe) {
165 result = false;
166 reason = "functions at position " + pos1 + " differ";
167 break;
168 }
169 continue;
170 }
171
172 if (item1 instanceof ObjectValue || item2 instanceof ObjectValue) {
173 if (!item1.equals(item2)) {
174 return false;
175 };
176 continue;
177 }
178
179 if (item1 instanceof NodeInfo) {
180 if (item2 instanceof NodeInfo) {
181 if (!deepEquals((NodeInfo) item1, (NodeInfo) item2, comparer, context.getConfiguration(), listener, flags)) {
182 result = false;
183 reason = "nodes at position " + pos1 + " differ";
184 break;
185 }
186 } else {
187 result = false;
188 reason = "comparing a node to an atomic value at position " + pos1;
189 break;
190 }
191 } else {
192 if (item2 instanceof NodeInfo) {
193 result = false;
194 reason = "comparing an atomic value to a node at position " + pos1;
195 break;
196 } else {
197 AtomicValue av1 = (AtomicValue) item1;
198 AtomicValue av2 = (AtomicValue) item2;
199 if (av1.isNaN() && av2.isNaN()) {
200 // treat as equal, no action
201 } else if (!comparer.comparesEqual(av1, av2)) {
202 result = false;
203 reason = "atomic values at position " + pos1 + " differ";
204 break;
205 }
206 }
207 }
208 } // end while
209
210 } catch (ClassCastException err) {
211 // this will happen if the sequences contain non-comparable values
212 // comparison errors are masked
213 //err.printStackTrace();
214 result = false;
215 reason = "sequences contain non-comparable values";
216 }
217
218 if (!result) {
219 explain(listener, reason, flags, null, null);
220 // config.getErrorListener().warning(
221 // new XPathException("deep-equal(): " + reason)
222 // );
223 }
224
225 return result;
226 }
227
228 /*
229 * Determine whether two nodes are deep-equal
230 */
231
232 public static boolean deepEquals(NodeInfo n1, NodeInfo n2,
233 AtomicComparer comparer, Configuration config, UnfailingErrorListener listener, int flags)
234 throws XPathException {
235 // shortcut: a node is always deep-equal to itself
236 if (n1.equals(n2)) {
237 return true;
238 }
239
240 if (n1.getNodeKind() != n2.getNodeKind()) {
241 explain(listener, "node kinds differ: comparing " + showKind(n1) + " to " + showKind(n2), flags, n1, n2);
242 return false;
243 }
244
245 switch (n1.getNodeKind()) {
246 case Type.ELEMENT:
247 if (!Navigator.haveSameName(n1, n2)) {
248 explain(listener, "element names differ: " + NameOfNode.makeName(n1).getStructuredQName().getEQName() +
249 " != " + NameOfNode.makeName(n2).getStructuredQName().getEQName(), flags, n1, n2);
250 return false;
251 }
252 if (((flags & INCLUDE_PREFIXES) != 0) && !n1.getPrefix().equals(n2.getPrefix())) {
253 explain(listener, "element prefixes differ: " + n1.getPrefix() +
254 " != " + n2.getPrefix(), flags, n1, n2);
255 return false;
256 }
257 AxisIterator a1 = n1.iterateAxis(AxisInfo.ATTRIBUTE);
258 AxisIterator a2 = n2.iterateAxis(AxisInfo.ATTRIBUTE);
259 if (!SequenceTool.sameLength(a1, a2)) {
260 explain(listener, "elements have different number of attributes", flags, n1, n2);
261 return false;
262 }
263 NodeInfo att1;
264 a1 = n1.iterateAxis(AxisInfo.ATTRIBUTE);
265 while ((att1 = a1.next()) != null) {
266 AxisIterator a2iter = n2.iterateAxis(AxisInfo.ATTRIBUTE,
267 new SameNameTest(att1));
268 NodeInfo att2 = a2iter.next();
269
270 if (att2 == null) {
271 explain(listener, "one element has an attribute " +
272 NameOfNode.makeName(att1).getStructuredQName().getEQName() +
273 ", the other does not", flags, n1, n2);
274 return false;
275 }
276 if (!deepEquals(att1, att2, comparer, config, listener, flags)) {
277 deepEquals(att1, att2, comparer, config, listener, flags);
278 explain(listener, "elements have different values for the attribute " +
279 NameOfNode.makeName(att1).getStructuredQName().getEQName(), flags, n1, n2);
280 return false;
281 }
282 }
283 if ((flags & INCLUDE_NAMESPACES) != 0) {
284 HashSet<NamespaceBinding> ns1 = new HashSet<>(10);
285 HashSet<NamespaceBinding> ns2 = new HashSet<>(10);
286 AxisIterator it1 = n1.iterateAxis(AxisInfo.NAMESPACE);
287 NodeInfo nn1;
288 while ((nn1 = it1.next()) != null) {
289 NamespaceBinding nscode1 = new NamespaceBinding(nn1.getLocalPart(), nn1.getStringValue());
290 ns1.add(nscode1);
291 }
292 AxisIterator it2 = n2.iterateAxis(AxisInfo.NAMESPACE);
293 NodeInfo nn2;
294 while ((nn2 = it2.next()) != null) {
295 NamespaceBinding nscode2 = new NamespaceBinding(nn2.getLocalPart(), nn2.getStringValue());
296 ns2.add(nscode2);
297 }
298 if (!ns1.equals(ns2)) {
299 explain(listener, "elements have different in-scope namespaces: " +
300 showNamespaces(ns1) + " versus " + showNamespaces(ns2), flags, n1, n2);
301 return false;
302 }
303 }
304
305 if ((flags & COMPARE_ANNOTATIONS) != 0) {
306 if (!n1.getSchemaType().equals(n2.getSchemaType())) {
307 explain(listener, "elements have different type annotation", flags, n1, n2);
308 return false;
309 }
310 }
311
312 if ((flags & EXCLUDE_VARIETY) == 0) {
313 if (n1.getSchemaType().isComplexType() != n2.getSchemaType().isComplexType()) {
314 explain(listener, "one element has complex type, the other simple", flags, n1, n2);
315 return false;
316 }
317
318 if (n1.getSchemaType().isComplexType()) {
319 int variety1 = ((ComplexType) n1.getSchemaType()).getVariety();
320 int variety2 = ((ComplexType) n2.getSchemaType()).getVariety();
321 if (variety1 != variety2) {
322 explain(listener, "both elements have complex type, but a different variety", flags, n1, n2);
323 return false;
324 }
325 }
326 }
327
328 if ((flags & COMPARE_STRING_VALUES) == 0) {
329 final SchemaType type1 = n1.getSchemaType();
330 final SchemaType type2 = n2.getSchemaType();
331 final boolean isSimple1 = type1.isSimpleType() || ((ComplexType) type1).isSimpleContent();
332 final boolean isSimple2 = type2.isSimpleType() || ((ComplexType) type2).isSimpleContent();
333 if (isSimple1 != isSimple2) {
334 explain(listener, "one element has a simple type, the other does not", flags, n1, n2);
335 return false;
336 }
337 if (isSimple1) {
338 assert isSimple2;
339 final AtomicIterator v1 = n1.atomize().iterate();
340 final AtomicIterator v2 = n2.atomize().iterate();
341 return deepEqual(v1, v2, comparer, config.getConversionContext(), flags);
342 }
343 }
344
345 if ((flags & COMPARE_ID_FLAGS) != 0) {
346 if (n1.isId() != n2.isId()) {
347 explain(listener, "one element is an ID, the other is not", flags, n1, n2);
348 return false;
349 }
350 if (n1.isIdref() != n2.isIdref()) {
351 explain(listener, "one element is an IDREF, the other is not", flags, n1, n2);
352 return false;
353 }
354 }
355 // fall through
356 case Type.DOCUMENT:
357 AxisIterator c1 = n1.iterateAxis(AxisInfo.CHILD);
358 AxisIterator c2 = n2.iterateAxis(AxisInfo.CHILD);
359 while (true) {
360 NodeInfo d1 = c1.next();
361 while (d1 != null && isIgnorable(d1, flags)) {
362 d1 = c1.next();
363 }
364 NodeInfo d2 = c2.next();
365 while (d2 != null && isIgnorable(d2, flags)) {
366 d2 = c2.next();
367 }
368 if (d1 == null || d2 == null) {
369 boolean r = d1 == d2;
370 if (!r) {
371 String message = "the first operand contains a node with " +
372 (d1 == null ? "fewer" : "more") +
373 " children than the second";
374 if (d1 instanceof WhitespaceTextImpl || d2 instanceof WhitespaceTextImpl) {
375 message += " (the first extra child is whitespace text)";
376 }
377 explain(listener, message, flags, n1, n2);
378 }
379 return r;
380 }
381 if (!deepEquals(d1, d2, comparer, config, listener, flags)) {
382 return false;
383 }
384 }
385
386 case Type.ATTRIBUTE:
387 if (!Navigator.haveSameName(n1, n2)) {
388 explain(listener, "attribute names differ: " +
389 NameOfNode.makeName(n1).getStructuredQName().getEQName() +
390 " != " + NameOfNode.makeName(n1).getStructuredQName().getEQName(), flags, n1, n2);
391 return false;
392 }
393 if (((flags & INCLUDE_PREFIXES) != 0) && !n1.getPrefix().equals(n2.getPrefix())) {
394 explain(listener, "attribute prefixes differ: " + n1.getPrefix() +
395 " != " + n2.getPrefix(), flags, n1, n2);
396 return false;
397 }
398 if ((flags & COMPARE_ANNOTATIONS) != 0) {
399 if (!n1.getSchemaType().equals(n2.getSchemaType())) {
400 explain(listener, "attributes have different type annotations", flags, n1, n2);
401 return false;
402 }
403 }
404 boolean ar;
405 if ((flags & COMPARE_STRING_VALUES) == 0) {
406 ar = deepEqual(n1.atomize().iterate(), n2.atomize().iterate(), comparer, config.getConversionContext(), 0);
407 } else {
408 ar = comparer.comparesEqual(
409 new StringValue(n1.getStringValueCS()),
410 new StringValue(n2.getStringValueCS()));
411 }
412 if (!ar) {
413 explain(listener, "attribute values differ", flags, n1, n2);
414 return false;
415 }
416 if ((flags & COMPARE_ID_FLAGS) != 0) {
417 if (n1.isId() != n2.isId()) {
418 explain(listener, "one attribute is an ID, the other is not", flags, n1, n2);
419 return false;
420 }
421 if (n1.isIdref() != n2.isIdref()) {
422 explain(listener, "one attribute is an IDREF, the other is not", flags, n1, n2);
423 return false;
424 }
425 }
426 return true;
427
428
429 case Type.PROCESSING_INSTRUCTION:
430 case Type.NAMESPACE:
431 if (!n1.getLocalPart().equals(n2.getLocalPart())) {
432 explain(listener, Type.displayTypeName(n1) + " names differ", flags, n1, n2);
433 return false;
434 }
435 // drop through
436 case Type.TEXT:
437 case Type.COMMENT:
438 boolean vr = comparer.comparesEqual((AtomicValue) n1.atomize(), (AtomicValue) n2.atomize());
439 if (!vr && ((flags & WARNING_IF_FALSE) != 0)) {
440 String v1 = n1.atomize().getStringValue();
441 String v2 = n2.atomize().getStringValue();
442 String message = "";
443 if (v1.length() != v2.length()) {
444 message = "lengths (" + v1.length() + "," + v2.length() + ")";
445 }
446 if (v1.length() < 10 && v2.length() < 10) {
447 message = " (\"" + v1 + "\" vs \"" + v2 + "\")";
448 } else {
449 int min = Math.min(v1.length(), v2.length());
450
451 if (v1.substring(0, min).equals(v2.substring(0, min))) {
452 message += " different at char " + min + "(\"" +
453 StringValue.diagnosticDisplay((v1.length() > v2.length() ? v1 : v2).substring(min)) + "\")";
454 } else if (v1.charAt(0) != v2.charAt(0)) {
455 message += " different at start " + "(\"" +
456 v1.substring(0, Math.min(v1.length(), 10)) + "\", \"" +
457 v2.substring(0, Math.min(v2.length(), 10)) + "\")";
458 } else {
459 for (int i = 1; i < min; i++) {
460 if (!v1.substring(0, i).equals(v2.substring(0, i))) {
461 message += " different at char " + (i - 1) + "(\"" +
462 v1.substring(i - 1, Math.min(v1.length(), i + 10)) + "\", \"" +
463 v2.substring(i - 1, Math.min(v2.length(), i + 10)) + "\")";
464 break;
465 }
466 }
467 }
468 }
469 explain(listener, Type.displayTypeName(n1) + " values differ (" +
470 Navigator.getPath(n1) + ", " + Navigator.getPath(n2) + "): " +
471 message, flags, n1, n2);
472 }
473 return vr;
474
475 default:
476 throw new IllegalArgumentException("Unknown node type");
477 }
478 }
479
480 private static boolean isIgnorable(NodeInfo node, int flags) {
481 final int kind = node.getNodeKind();
482 if (kind == Type.COMMENT) {
483 return (flags & INCLUDE_COMMENTS) == 0;
484 } else if (kind == Type.PROCESSING_INSTRUCTION) {
485 return (flags & INCLUDE_PROCESSING_INSTRUCTIONS) == 0;
486 } else if (kind == Type.TEXT) {
487 return ((flags & EXCLUDE_WHITESPACE_TEXT_NODES) != 0) &&
488 Whitespace.isWhite(node.getStringValueCS());
489 }
490 return false;
491 }
492
493 private static void explain(UnfailingErrorListener listener, String message, int flags, NodeInfo n1, NodeInfo n2) {
494 if ((flags & WARNING_IF_FALSE) != 0) {
495 listener.warning(new XPathException("deep-equal() " +
496 (n1 != null && n2 != null ?
497 "comparing " + Navigator.getPath(n1) + " to " + Navigator.getPath(n2) + ": " :
498 ": ") +
499 message));
500 }
501 }
502
503 private static String showKind(Item item) {
504 if (item instanceof NodeInfo && ((NodeInfo) item).getNodeKind() == Type.TEXT &&
505 Whitespace.isWhite(item.getStringValueCS())) {
506 return "whitespace text() node";
507 } else {
508 return Type.displayTypeName(item);
509 }
510 }
511
512 private static String showNamespaces(HashSet<NamespaceBinding> bindings) {
513 FastStringBuffer sb = new FastStringBuffer(256);
514 for (NamespaceBinding binding : bindings) {
515 sb.append(binding.getPrefix());
516 sb.append("=");
517 sb.append(binding.getURI());
518 sb.append(" ");
519 }
520 sb.setLength(sb.length()-1);
521 return sb.toString();
522 }
523
524 private static SequenceIterator mergeAdjacentTextNodes(SequenceIterator in) throws XPathException {
525 List<Item> items = new ArrayList<>(20);
526 boolean prevIsText = false;
527 FastStringBuffer textBuffer = new FastStringBuffer(FastStringBuffer.C64);
528 while (true) {
529 Item next = in.next();
530 if (next == null) {
531 break;
532 }
533 if (next instanceof NodeInfo && ((NodeInfo) next).getNodeKind() == Type.TEXT) {
534 textBuffer.append(next.getStringValueCS());
535 prevIsText = true;
536 } else {
537 if (prevIsText) {
538 Orphan textNode = new Orphan(null);
539 textNode.setNodeKind(Type.TEXT);
540 textNode.setStringValue(textBuffer.toString()); // must copy the buffer before reusing it
541 items.add(textNode);
542 textBuffer.setLength(0);
543 }
544 prevIsText = false;
545 items.add(next);
546 }
547 }
548 if (prevIsText) {
549 Orphan textNode = new Orphan(null);
550 textNode.setNodeKind(Type.TEXT);
551 textNode.setStringValue(textBuffer.toString()); // must copy the buffer before reusing it
552 items.add(textNode);
553 }
554 SequenceExtent extent = new SequenceExtent<>(items);
555 return extent.iterate();
556 }
557
558 /**
559 * Execute a dynamic call to the function
560 *
561 * @param context the dynamic evaluation context
562 * @param arguments the values of the arguments, supplied as Sequences.
563 * @return the result of the evaluation, in the form of a Sequence. It is the responsibility
564 * of the callee to ensure that the type of result conforms to the expected result type.
565 * @throws XPathException (should not happen)
566 */
567
568 public BooleanValue call(XPathContext context, Sequence[] arguments) throws XPathException {
569 GenericAtomicComparer comparer = new GenericAtomicComparer(getStringCollator(), context);
570 boolean b = deepEqual(arguments[0].iterate(), arguments[1].iterate(), comparer, context, 0);
571 return BooleanValue.get(b);
572 }
573
574 public String getStreamerName() {
575 return "DeepEqual";
576 }
577
578 }
579