Debian Codegraph @

net/sf/saxon/pattern/NodeTest.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.StaticProperty;
11 import net.sf.saxon.om.*;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.tiny.NodeVectorTree;
14 import net.sf.saxon.type.*;
15 import net.sf.saxon.value.SequenceType;
16 import net.sf.saxon.z.IntSet;
17 import net.sf.saxon.z.IntUniversalSet;
18
19 import java.util.Iterator;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.function.IntPredicate;
23
24 /**
25 * A NodeTest is a simple kind of pattern that enables a context-free test of whether
26 * a node matches a given node kind and name. There are several kinds of node test: a full name test, a prefix test, and an
27 * "any node of a given type" test, an "any node of any type" test, a "no nodes"
28 * test (used, e.g. for "@comment()").
29 * <p>As well as being used to support XSLT pattern matching, NodeTests act as predicates in
30 * axis steps, and also act as item types for type matching.</p>
31 * <p>For use in user-written application calling {@link NodeInfo#iterateAxis(byte, NodeTest)},
32 * it is possible to write a user-defined subclass of <code>NodeTest</code> that implements
33 * a single method, {@link #matches(int, NodeName, SchemaType)}</p>
34 *
35 * @author Michael H. Kay
36 */
37
38 public abstract class NodeTest implements ItemType.WithSequenceTypeCache {
39
40 private SequenceType _one;
41 private SequenceType _oneOrMore;
42 private SequenceType _zeroOrOne;
43 private SequenceType _zeroOrMore;
44
45 /**
46 * Determine the Genre (top-level classification) of this type
47 *
48 * @return the Genre to which this type belongs, specifically {@link Genre#NODE}
49 */
50 @Override
51 public Genre getGenre() {
52 return Genre.NODE;
53 }
54
55 /**
56 * Determine the default priority to use if this node-test appears as a match pattern
57 * for a template with no explicit priority attribute.
58 *
59 * @return the default priority for the pattern
60 */
61
62 public abstract double getDefaultPriority();
63
64
65 public boolean matches(Item item, TypeHierarchy th) {
66 return item instanceof NodeInfo && matchesNode((NodeInfo) item);
67 }
68
69 /**
70 * Get the primitive item type corresponding to this item type. For item(),
71 * this is Type.ITEM. For node(), it is Type.NODE. For specific node kinds,
72 * it is the value representing the node kind, for example Type.ELEMENT.
73 * For anyAtomicValue it is Type.ATOMIC_VALUE. For numeric it is Type.NUMBER.
74 * For other atomic types it is the primitive type as defined in XML Schema,
75 * except that INTEGER is considered to be a primitive type.
76 */
77
78 /*@NotNull*/
79 public ItemType getPrimitiveItemType() {
80 int p = getPrimitiveType();
81 if (p == Type.NODE) {
82 return AnyNodeTest.getInstance();
83 } else {
84 return NodeKindTest.makeNodeKindTest(p);
85 }
86 }
87
88 /**
89 * Get the basic kind of object that this ItemType matches: for a NodeTest, this is the kind of node,
90 * or Type.Node if it matches different kinds of nodes.
91 *
92 * @return the node kind matched by this node test
93 */
94
95 public int getPrimitiveType() {
96 return Type.NODE;
97 }
98
99 /**
100 * Get the name of the nodes matched by this nodetest, if it matches a specific name.
101 * Return -1 if the node test matches nodes of more than one name
102 */
103
104 public int getFingerprint() {
105 return -1;
106 }
107
108 /**
109 * Get the name of the nodes matched by this nodetest, if it matches a specific name.
110 * Return null if the node test matches nodes of more than one name
111 */
112
113 public StructuredQName getMatchingNodeName() {
114 return null;
115 }
116
117 /**
118 * Get an alphabetic code representing the type, or at any rate, the nearest built-in type
119 * from which this type is derived. The codes are designed so that for any two built-in types
120 * A and B, alphaCode(A) is a prefix of alphaCode(B) if and only if A is a supertype of B.
121 *
122 * @return the alphacode for the nearest containing built-in type
123 */
124 @Override
125 public String getAlphaCode() {
126 switch (getPrimitiveType()) {
127 case Type.NODE:
128 return "N";
129 case Type.ELEMENT:
130 return "NE";
131 case Type.ATTRIBUTE:
132 return "NA";
133 case Type.TEXT:
134 return "NT";
135 case Type.COMMENT:
136 return "NC";
137 case Type.PROCESSING_INSTRUCTION:
138 return "NP";
139 case Type.DOCUMENT:
140 return "ND";
141 case Type.NAMESPACE:
142 return "NN";
143 default:
144 return "*";
145 }
146 }
147
148 /**
149 * Determine whether this item type is an atomic type
150 *
151 * @return true if this is ANY_ATOMIC_TYPE or a subtype thereof
152 */
153 public boolean isAtomicType() {
154 return false;
155 }
156
157 /**
158 * Determine whether this item type is atomic (that is, whether it can ONLY match
159 * atomic values)
160 *
161 * @return false: this is not ANY_ATOMIC_TYPE or a subtype thereof
162 */
163
164 public boolean isPlainType() {
165 return false;
166 }
167
168 /**
169 * Get the item type of the atomic values that will be produced when an item
170 * of this type is atomized (assuming that atomization succeeds)
171 */
172
173 /*@NotNull*/
174 public AtomicType getAtomizedItemType() {
175 // This is overridden for a ContentTypeTest
176 return BuiltInAtomicType.ANY_ATOMIC;
177 }
178
179 /**
180 * Ask whether values of this type are atomizable
181 *
182 * @return true unless it is known that these items will be elements with element-only
183 * content, in which case return false
184 * @param th The type hierarchy cache
185 */
186
187 public boolean isAtomizable(TypeHierarchy th) {
188 // This is overridden for a ContentTypeTest
189 return true;
190 }
191
192 /**
193 * Get a matching function that can be used to test whether numbered nodes in a TinyTree
194 * or DominoTree satisfy the node test. (Calling this matcher must give the same result
195 * as calling <code>matchesNode(tree.getNode(nodeNr))</code>, but it may well be faster).
196 * @param tree the tree against which the returned function will operate
197 * @return an IntPredicate; the matches() method of this predicate takes a node number
198 * as input, and returns true if and only if the node identified by this node number
199 * matches the node test.
200 */
201
202 public IntPredicate getMatcher(final NodeVectorTree tree) {
203 return nodeNr -> matchesNode(tree.getNode(nodeNr));
204 }
205
206 /**
207 * Test whether this node test is satisfied by a given node. This method is only
208 * fully supported for a subset of NodeTests, because it doesn't provide all the information
209 * needed to evaluate all node tests. In particular (a) it can't be used to evaluate a node
210 * test of the form element(N,T) or schema-element(E) where it is necessary to know whether the
211 * node is nilled, and (b) it can't be used to evaluate a node test of the form
212 * document-node(element(X)). This in practice means that it is used (a) to evaluate the
213 * simple node tests found in the XPath 1.0 subset used in XML Schema, and (b) to evaluate
214 * node tests where the node kind is known to be an attribute.
215 *
216 * @param nodeKind The kind of node to be matched
217 * @param name identifies the expanded name of the node to be matched.
218 * The value should be null for a node with no name.
219 * @param annotation The actual content type of the node. Null means no constraint.
220 * @return true if the node matches this node test
221 */
222
223 public abstract boolean matches(int nodeKind, NodeName name, SchemaType annotation);
224
225 /**
226 * Test whether this node test is satisfied by a given node. This alternative
227 * method is used in the case of nodes where calculating the fingerprint is expensive,
228 * for example DOM or JDOM nodes. The default implementation calls the method
229 * {@link #matches(int, NodeName, SchemaType)}
230 *
231 * @param node the node to be matched
232 * @return true if the node test is satisfied by the supplied node, false otherwise
233 */
234
235 public boolean matchesNode(/*@NotNull*/ NodeInfo node) {
236 return matches(node.getNodeKind(), NameOfNode.makeName(node), node.getSchemaType());
237 }
238
239 /**
240 * Get the content type allowed by this NodeTest (that is, the type annotation of the matched nodes).
241 * Return AnyType if there are no restrictions. The default implementation returns AnyType.
242 *
243 * @return the type annotation that all nodes matching this NodeTest must satisfy
244 */
245
246 public SchemaType getContentType() {
247 Set<PrimitiveUType> m = getUType().decompose();
248 Iterator<PrimitiveUType> it = m.iterator();
249 if (m.size() == 1 && it.hasNext()) {
250 PrimitiveUType p = it.next();
251 switch (p) {
252 case DOCUMENT:
253 return AnyType.getInstance();
254 case ELEMENT:
255 return AnyType.getInstance();
256 case ATTRIBUTE:
257 return AnySimpleType.getInstance();
258 case COMMENT:
259 return BuiltInAtomicType.STRING;
260 case TEXT:
261 return BuiltInAtomicType.UNTYPED_ATOMIC;
262 case PI:
263 return BuiltInAtomicType.STRING;
264 case NAMESPACE:
265 return BuiltInAtomicType.STRING;
266 }
267 }
268 return AnyType.getInstance();
269 }
270
271 /**
272 * Get the set of node names allowed by this NodeTest. This is returned as a set of Integer fingerprints.
273 * If all names are permitted (i.e. there are no constraints on the node name), returns IntUniversalSet.getInstance().
274 * The default implementation returns the universal set.
275 *
276 * @return the set of integer fingerprints of the node names that this node test can match; or absent
277 * if the set of names cannot be represented (for example, with the name tests *:xxx or xxx:*)
278 */
279
280 /*@NotNull*/
281 public Optional<IntSet> getRequiredNodeNames() {
282 return Optional.of(IntUniversalSet.getInstance());
283 }
284
285 /**
286 * Determine whether the content type (if present) is nillable
287 *
288 * @return true if the content test (when present) can match nodes that are nilled
289 */
290
291 public boolean isNillable() {
292 return true;
293 }
294
295 /**
296 * Copy a NodeTest.
297 * Since they are never written to except in their constructors, returns the same.
298 *
299 * @return the original nodeTest
300 */
301
302 /*@NotNull*/
303 public NodeTest copy() {
304 return this;
305 }
306
307 /**
308 * Generate Javascript code to convert a supplied Javascript value to this item type,
309 * if conversion is possible, or throw an error otherwise.
310 *
311 * @param errorCode the error to be thrown if conversion is not possible
312 * @param targetVersion the version of Saxon-JS being targeted
313 * @return a Javascript instruction or sequence of instructions, which can be used as the body
314 * of a Javascript function, and which returns the result of conversion to this type, or throws
315 * an error if conversion is not possible. The variable "val" will hold the supplied Javascript
316 * value.
317 */
318 public String generateJavaScriptItemTypeAcceptor(String errorCode, int targetVersion) throws XPathException {
319 return "function test(item) {" + generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion) + "};" +
320 "if (test(val)) {return val;} else {throw SaxonJS.XError('Conversion failed', '" + errorCode + "');}";
321 }
322
323 /**
324 * Get a sequence type representing exactly one instance of this atomic type
325 *
326 * @return a sequence type representing exactly one instance of this atomic type
327 * @since 9.8.0.2
328 */
329
330 public SequenceType one() {
331 if (_one == null) {
332 _one = new SequenceType(this, StaticProperty.EXACTLY_ONE);
333 }
334 return _one;
335 }
336
337 /**
338 * Get a sequence type representing zero or one instances of this atomic type
339 *
340 * @return a sequence type representing zero or one instances of this atomic type
341 * @since 9.8.0.2
342 */
343
344 public SequenceType zeroOrOne() {
345 if (_zeroOrOne == null) {
346 _zeroOrOne = new SequenceType(this, StaticProperty.ALLOWS_ZERO_OR_ONE);
347 }
348 return _zeroOrOne;
349 }
350
351 /**
352 * Get a sequence type representing one or more instances of this atomic type
353 *
354 * @return a sequence type representing one or more instances of this atomic type
355 * @since 9.8.0.2
356 */
357
358 public SequenceType oneOrMore() {
359 if (_oneOrMore == null) {
360 _oneOrMore = new SequenceType(this, StaticProperty.ALLOWS_ONE_OR_MORE);
361 }
362 return _oneOrMore;
363 }
364
365 /**
366 * Get a sequence type representing one or more instances of this atomic type
367 *
368 * @return a sequence type representing one or more instances of this atomic type
369 * @since 9.8.0.2
370 */
371
372 public SequenceType zeroOrMore() {
373 if (_zeroOrMore == null) {
374 _zeroOrMore = new SequenceType(this, StaticProperty.ALLOWS_ZERO_OR_MORE);
375 }
376 return _zeroOrMore;
377 }
378
379 /**
380 * Get extra diagnostic information about why a supplied item does not conform to this
381 * item type, if available. If extra information is returned, it should be in the form of a complete
382 * sentence, minus the closing full stop. No information should be returned for obvious cases.
383 *
384 * @param item the item that doesn't match this type
385 * @param th the type hierarchy cache
386 * @return optionally, a message explaining why the item does not match the type
387 */
388 @Override
389 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
390 if (item instanceof NodeInfo) {
391 UType actualKind = UType.getUType(item);
392 if (!getUType().overlaps(actualKind)) {
393 return Optional.of("The supplied value is " + actualKind.toStringWithIndefiniteArticle());
394 }
395 return Optional.empty();
396 } else {
397 return Optional.of("The supplied value is " + item.getGenre().getDescription());
398 }
399 }
400
401 public String toShortString() {
402 return toString();
403 }
404
405
406 }
407