Debian Codegraph @

net/sf/saxon/pattern/CombinedNodeTest.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.pattern;
9
10 import net.sf.saxon.expr.parser.Token;
11 import net.sf.saxon.ma.map.DictionaryMap;
12 import net.sf.saxon.om.Item;
13 import net.sf.saxon.om.NodeInfo;
14 import net.sf.saxon.om.NodeName;
15 import net.sf.saxon.om.StructuredQName;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.tiny.NodeVectorTree;
18 import net.sf.saxon.tree.util.FastStringBuffer;
19 import net.sf.saxon.type.*;
20 import net.sf.saxon.value.StringValue;
21 import net.sf.saxon.z.IntExceptPredicate;
22 import net.sf.saxon.z.IntSet;
23
24 import java.util.Optional;
25 import java.util.function.IntPredicate;
26
27 /**
28 * A CombinedNodeTest combines two node tests using one of the operators
29 * union (=or), intersect (=and), difference (= "and not"). This arises
30 * when optimizing a union (etc) of two path expressions using the same axis.
31 * A CombinedNodeTest is also used to support constructs such as element(N,T),
32 * which can be expressed as (element(N,*) AND element(*,T))
33 *
34 * @author Michael H. Kay
35 */
36
37 public class CombinedNodeTest extends NodeTest {
38
39 private NodeTest nodetest1;
40 private NodeTest nodetest2;
41 private int operator;
42
43 /**
44 * Create a NodeTest that combines two other node tests
45 *
46 * @param nt1 the first operand. Note that if the defaultPriority of the pattern
47 * is required, it will be taken from that of the first operand.
48 * @param operator one of Token.UNION, Token.INTERSECT, Token.EXCEPT
49 * @param nt2 the second operand
50 */
51
52 public CombinedNodeTest(NodeTest nt1, int operator, NodeTest nt2) {
53 nodetest1 = nt1;
54 this.operator = operator;
55 nodetest2 = nt2;
56 }
57
58 /**
59 * Get the corresponding {@link net.sf.saxon.type.UType}. A UType is a union of primitive item
60 * types.
61 *
62 * @return the smallest UType that subsumes this item type
63 */
64 public UType getUType() {
65 UType u1 = nodetest1.getUType();
66 UType u2 = nodetest2.getUType();
67 switch (operator) {
68 case Token.UNION:
69 return u1.union(u2);
70 case Token.INTERSECT:
71 return u1.intersection(u2);
72 case Token.EXCEPT:
73 return u1;
74 default:
75 throw new IllegalArgumentException("Unknown operator in Combined Node Test");
76 }
77 }
78
79 /**
80 * Test whether this node test is satisfied by a given node. This method is only
81 * fully supported for a subset of NodeTests, because it doesn't provide all the information
82 * needed to evaluate all node tests. In particular (a) it can't be used to evaluate a node
83 * test of the form element(N,T) or schema-element(E) where it is necessary to know whether the
84 * node is nilled, and (b) it can't be used to evaluate a node test of the form
85 * document-node(element(X)). This in practice means that it is used (a) to evaluate the
86 * simple node tests found in the XPath 1.0 subset used in XML Schema, and (b) to evaluate
87 * node tests where the node kind is known to be an attribute.
88 *
89 * @param nodeKind The kind of node to be matched
90 * @param name identifies the expanded name of the node to be matched.
91 * The value should be null for a node with no name.
92 * @param annotation The actual content type of the node
93 */
94 @Override
95 public boolean matches(int nodeKind, NodeName name, SchemaType annotation) {
96 switch (operator) {
97 case Token.UNION:
98 return nodetest1 == null ||
99 nodetest2 == null ||
100 nodetest1.matches(nodeKind, name, annotation) ||
101 nodetest2.matches(nodeKind, name, annotation);
102 case Token.INTERSECT:
103 return (nodetest1 == null || nodetest1.matches(nodeKind, name, annotation)) &&
104 (nodetest2 == null || nodetest2.matches(nodeKind, name, annotation));
105 case Token.EXCEPT:
106 return (nodetest1 == null || nodetest1.matches(nodeKind, name, annotation)) &&
107 !(nodetest2 == null || nodetest2.matches(nodeKind, name, annotation));
108 default:
109 throw new IllegalArgumentException("Unknown operator in Combined Node Test");
110 }
111 }
112
113 @Override
114 public IntPredicate getMatcher(NodeVectorTree tree) {
115 switch (operator) {
116 case Token.UNION:
117 return nodetest1.getMatcher(tree).or(nodetest2.getMatcher(tree));
118 case Token.INTERSECT:
119 return nodetest1.getMatcher(tree).and(nodetest2.getMatcher(tree));
120 case Token.EXCEPT:
121 return new IntExceptPredicate(nodetest1.getMatcher(tree), nodetest2.getMatcher(tree));
122 default:
123 throw new IllegalArgumentException("Unknown operator in Combined Node Test");
124 }
125 }
126
127 /**
128 * Test whether this node test is satisfied by a given node. This alternative
129 * method is used in the case of nodes where calculating the fingerprint is expensive,
130 * for example DOM or JDOM nodes.
131 *
132 * @param node the node to be matched
133 */
134
135 public boolean matchesNode(/*@NotNull*/ NodeInfo node) {
136 switch (operator) {
137 case Token.UNION:
138 return nodetest1 == null ||
139 nodetest2 == null ||
140 nodetest1.matchesNode(node) ||
141 nodetest2.matchesNode(node);
142 case Token.INTERSECT:
143 return (nodetest1 == null || nodetest1.matchesNode(node)) &&
144 (nodetest2 == null || nodetest2.matchesNode(node));
145 case Token.EXCEPT:
146 return (nodetest1 == null || nodetest1.matchesNode(node)) &&
147 !(nodetest2 == null || nodetest2.matchesNode(node));
148 default:
149 throw new IllegalArgumentException("Unknown operator in Combined Node Test");
150 }
151 }
152
153 public String toString() {
154 return makeString(false);
155 }
156
157 private String makeString(boolean forExport) {
158 if (nodetest1 instanceof NameTest && operator == Token.INTERSECT) {
159 int kind = nodetest1.getPrimitiveType();
160 String skind = kind == Type.ELEMENT ? "element(" : "attribute(";
161 String content = "";
162 if (nodetest2 instanceof ContentTypeTest) {
163 SchemaType schemaType = ((ContentTypeTest) nodetest2).getSchemaType();
164 if (forExport) {
165 schemaType = schemaType.getNearestNamedType();
166 }
167 content = ", " + schemaType.getEQName();
168 if (nodetest2.isNillable()) {
169 content += "?";
170 }
171 }
172 String name = nodetest1.getMatchingNodeName().getEQName();
173 return skind + name + content + ')';
174 } else {
175 String nt1 = nodetest1 == null ? "item()" : nodetest1.toString();
176 String nt2 = nodetest2 == null ? "item()" : nodetest2.toString();
177 return '(' + nt1 + ' ' + Token.tokens[operator] + ' ' + nt2 + ')';
178 }
179 }
180
181 /**
182 * Return a string representation of this ItemType suitable for use in stylesheet
183 * export files. This differs from the result of toString() in that it will not contain
184 * any references to anonymous types. Note that it may also use the Saxon extended syntax
185 * for union types and tuple types. The default implementation returns the result of
186 * calling {@code toString()}.
187 *
188 * @return the string representation as an instance of the XPath SequenceType construct
189 */
190 @Override
191 public String toExportString() {
192 return makeString(true);
193 }
194
195 /**
196 * Add the "parameters" of the type to a Dictionary containing the type information
197 * in structured form
198 */
199
200 public void addTypeDetails(DictionaryMap map) {
201 if (nodetest1 instanceof NameTest && operator == Token.INTERSECT) {
202 map.initialPut("n", new StringValue(nodetest1.getMatchingNodeName().getEQName()));
203 if (nodetest2 instanceof ContentTypeTest) {
204 SchemaType schemaType = ((ContentTypeTest) nodetest2).getSchemaType();
205 //if (schemaType != Untyped.getInstance() && schemaType != BuiltInAtomicType.UNTYPED_ATOMIC) {
206 map.initialPut("c", new StringValue(schemaType.getEQName() +
207 (nodetest2.isNillable() ? "?" : "")));
208
209 //}
210 }
211 }
212 }
213
214
215 /**
216 * Get the basic kind of object that this ItemType matches: for a NodeTest, this is the kind of node,
217 * or Type.Node if it matches different kinds of nodes.
218 *
219 * @return the node kind matched by this node test
220 */
221
222 public int getPrimitiveType() {
223 UType mask = getUType();
224 if (mask.equals(UType.ELEMENT)) {
225 return Type.ELEMENT;
226 }
227 if (mask.equals(UType.ATTRIBUTE)) {
228 return Type.ATTRIBUTE;
229 }
230 if (mask.equals(UType.DOCUMENT)) {
231 return Type.DOCUMENT;
232 }
233 return Type.NODE;
234 }
235
236 /**
237 * Get the set of node names allowed by this NodeTest. This is returned as a set of Integer fingerprints.
238 * IntUniversalSet indicates that all names are permitted (i.e. that there are no constraints on the node name).
239 */
240
241 /*@NotNull*/
242 public Optional<IntSet> getRequiredNodeNames() {
243 Optional<IntSet> os1 = nodetest1.getRequiredNodeNames();
244 Optional<IntSet> os2 = nodetest2.getRequiredNodeNames();
245 if (os1.isPresent() && os2.isPresent()) {
246 IntSet s1 = os1.get();
247 IntSet s2 = os2.get();
248 switch (operator) {
249 case Token.UNION: {
250 return Optional.of(s1.union(s2));
251 }
252 case Token.INTERSECT: {
253 return Optional.of(s1.intersect(s2));
254 }
255 case Token.EXCEPT: {
256 return Optional.of(s1.except(s2));
257 }
258 default:
259 throw new IllegalStateException();
260 }
261 } else {
262 return Optional.empty();
263 }
264 }
265
266 /**
267 * Get the content type allowed by this NodeTest (that is, the type annotation of the matched nodes).
268 * Return AnyType if there are no restrictions. The default implementation returns AnyType.
269 */
270
271 public SchemaType getContentType() {
272 SchemaType type1 = nodetest1.getContentType();
273 SchemaType type2 = nodetest2.getContentType();
274 if (type1.isSameType(type2)) {
275 return type1;
276 }
277 if (operator == Token.INTERSECT) {
278 if (type2 instanceof AnyType || (type2 instanceof AnySimpleType && type1.isSimpleType())) {
279 return type1;
280 }
281 if (type1 instanceof AnyType || (type1 instanceof AnySimpleType && type2.isSimpleType())) {
282 return type2;
283 }
284 }
285 return AnyType.getInstance();
286 }
287
288 /**
289 * Get the item type of the atomic values that will be produced when an item
290 * of this type is atomized (assuming that atomization succeeds)
291 */
292
293 /*@NotNull*/
294 public AtomicType getAtomizedItemType() {
295 AtomicType type1 = nodetest1.getAtomizedItemType();
296 AtomicType type2 = nodetest2.getAtomizedItemType();
297 if (type1.isSameType(type2)) {
298 return type1;
299 }
300 if (operator == Token.INTERSECT) {
301 if (type2.equals(BuiltInAtomicType.ANY_ATOMIC)) {
302 return type1;
303 }
304 if (type1.equals(BuiltInAtomicType.ANY_ATOMIC)) {
305 return type2;
306 }
307 }
308 return BuiltInAtomicType.ANY_ATOMIC;
309 }
310
311 /**
312 * Ask whether values of this type are atomizable
313 *
314 * @return true unless it is known that these items will be elements with element-only
315 * content, in which case return false
316 * @param th the type hierarchy cache
317 */
318
319 public boolean isAtomizable(TypeHierarchy th) {
320 switch (operator) {
321 case Token.UNION:
322 return nodetest1.isAtomizable(th) || nodetest2.isAtomizable(th);
323 case Token.INTERSECT:
324 return nodetest1.isAtomizable(th) && nodetest2.isAtomizable(th);
325 case Token.EXCEPT:
326 return nodetest1.isAtomizable(th);
327 default:
328 return true;
329 }
330 }
331
332 /**
333 * Get the name of the nodes matched by this nodetest, if it matches a specific name.
334 * Return -1 if the node test matches nodes of more than one name
335 */
336
337 public int getFingerprint() {
338 int fp1 = nodetest1.getFingerprint();
339 int fp2 = nodetest2.getFingerprint();
340 if (fp1 == fp2) {
341 return fp1;
342 }
343 if (fp2 == -1 && operator == Token.INTERSECT) {
344 return fp1;
345 }
346 if (fp1 == -1 && operator == Token.INTERSECT) {
347 return fp2;
348 }
349 return -1;
350 }
351
352 @Override
353 public StructuredQName getMatchingNodeName() {
354 StructuredQName n1 = nodetest1.getMatchingNodeName();
355 StructuredQName n2 = nodetest2.getMatchingNodeName();
356 if (n1 != null && n1.equals(n2)) {
357 return n1;
358 }
359 if (n1 == null && operator == Token.INTERSECT) {
360 return n2;
361 }
362 if (n2 == null && operator == Token.INTERSECT) {
363 return n1;
364 }
365 return null;
366 }
367
368 /**
369 * Determine whether the content type (if present) is nillable
370 *
371 * @return true if the content test (when present) can match nodes that are nilled
372 */
373
374 public boolean isNillable() {
375 // this should err on the safe side
376 return nodetest1.isNillable() && nodetest2.isNillable();
377 }
378
379 /**
380 * Returns a hash code value for the object.
381 */
382
383 public int hashCode() {
384 return nodetest1.hashCode() ^ nodetest2.hashCode();
385 }
386
387 /**
388 * Indicates whether some other object is "equal to" this one.
389 */
390 public boolean equals(Object other) {
391 return other instanceof CombinedNodeTest &&
392 ((CombinedNodeTest) other).nodetest1.equals(nodetest1) &&
393 ((CombinedNodeTest) other).nodetest2.equals(nodetest2) &&
394 ((CombinedNodeTest) other).operator == operator;
395 }
396
397 /**
398 * Get the default priority of this nodeTest when used as a pattern. In the case of a union, this will always
399 * be (arbitrarily) the default priority of the first operand. In other cases, again somewhat arbitrarily, it
400 * is 0.25, reflecting the common usage of an intersection to represent the pattern element(E, T).
401 */
402
403 public double getDefaultPriority() {
404 if (operator == Token.UNION) {
405 return nodetest1.getDefaultPriority();
406 } else {
407 // typically it's element(E, T)
408 return 0.25;
409 }
410 }
411
412 /**
413 * Get the two parts of the combined node test
414 *
415 * @return the two operands
416 */
417
418 /*@NotNull*/
419 public NodeTest[] getComponentNodeTests() {
420 return new NodeTest[]{nodetest1, nodetest2};
421 }
422
423 /**
424 * Get the operator used to combine the two node tests: one of {@link net.sf.saxon.expr.parser.Token#UNION},
425 * {@link net.sf.saxon.expr.parser.Token#INTERSECT}, {@link net.sf.saxon.expr.parser.Token#EXCEPT},
426 *
427 * @return the operator
428 */
429
430 public int getOperator() {
431 return operator;
432 }
433
434
435 /**
436 * Generate Javascript code to test whether an item conforms to this item type
437 *
438 * @return a Javascript instruction or sequence of instructions, which can be used as the body
439 * of a Javascript function, and which returns a boolean indication whether the value of the
440 * variable "item" is an instance of this item type.
441 * @throws XPathException if JS code cannot be generated for this item type, for example because
442 * the test is schema-aware.
443 * @param knownToBe An item type that the supplied item is known to conform to; the generated code
444 * can assume that the item is an instance of this type.
445 * @param targetVersion The version of Saxon-JS for which code is being generated. Currently either 1 or 2.
446
447 */
448 @Override
449 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) throws XPathException {
450 FastStringBuffer fsb = new FastStringBuffer(256);
451 String conjunctor = null;
452 switch (operator) {
453 case Token.UNION:
454 conjunctor = "||";
455 break;
456 case Token.INTERSECT:
457 conjunctor = "&&";
458 break;
459 case Token.EXCEPT:
460 conjunctor = "&&!";
461 break;
462 }
463 fsb.append("function a() {" + nodetest1.generateJavaScriptItemTypeTest(knownToBe, targetVersion) + "};");
464 fsb.append("function b() {" + nodetest2.generateJavaScriptItemTypeTest(knownToBe, targetVersion) + "};");
465 fsb.append("return a()" + conjunctor + "b();");
466 return fsb.toString();
467 }
468
469 /**
470 * Get extra diagnostic information about why a supplied item does not conform to this
471 * item type, if available. If extra information is returned, it should be in the form of a complete
472 * sentence, minus the closing full stop. No information should be returned for obvious cases.
473 *
474 * @param item the item that doesn't match this type
475 * @param th the type hierarchy cache
476 * @return optionally, a message explaining why the item does not match the type
477 */
478 @Override
479 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
480 Optional<String> explanation = super.explainMismatch(item, th);
481 if (explanation.isPresent()) {
482 return explanation;
483 }
484 if (operator == Token.INTERSECT) {
485 // the most common case
486 if (!nodetest1.matchesNode((NodeInfo)item)) {
487 return nodetest1.explainMismatch(item, th);
488 } else if (!nodetest2.matchesNode((NodeInfo)item)) {
489 return nodetest2.explainMismatch(item, th);
490 }
491 }
492 return Optional.empty();
493 }
494
495
496 }
497