Debian Codegraph @

net/sf/saxon/pattern/NameTest.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.om.*;
11 import net.sf.saxon.trace.ExpressionPresenter;
12 import net.sf.saxon.tree.tiny.NodeVectorTree;
13 import net.sf.saxon.type.*;
14 import net.sf.saxon.z.IntSet;
15 import net.sf.saxon.z.IntSingletonSet;
16
17 import java.util.Optional;
18 import java.util.function.IntPredicate;
19
20 /**
21 * NodeTest is an interface that enables a test of whether a node has a particular
22 * name and type. A NameTest matches the node kind and the namespace URI and the local
23 * name. Note that unlike the XPath production called NameTest, this is a test for a specific
24 * name, and does not include wildcard matches.
25 *
26 * @author Michael H. Kay
27 */
28
29 public class NameTest extends NodeTest implements QNameTest {
30
31 private int nodeKind;
32 private int fingerprint;
33 private UType uType;
34 private NamePool namePool;
35 /*@Nullable*/ private String uri = null; // the URI corresponding to the fingerprint - computed lazily
36 /*@Nullable*/ private String localName = null; //the local name corresponding to the fingerprint - computed lazily
37
38 /**
39 * Create a NameTest to match nodes by name
40 *
41 * @param nodeKind the kind of node, for example {@link Type#ELEMENT}
42 * @param uri the namespace URI of the required nodes. Supply "" to match nodes that are in
43 * no namespace
44 * @param localName the local name of the required nodes. Supply "" to match unnamed nodes
45 * @param namePool the namePool holding the name codes
46 * @since 9.0
47 */
48
49 public NameTest(int nodeKind, String uri, String localName, NamePool namePool) {
50 this.uri = uri;
51 this.localName = localName;
52 this.nodeKind = nodeKind;
53 this.fingerprint = namePool.allocateFingerprint(uri, localName) & NamePool.FP_MASK;
54 this.namePool = namePool;
55 this.uType = UType.fromTypeCode(nodeKind);
56 }
57
58 /**
59 * Create a NameTest to match nodes by their nameCode allocated from the NamePool
60 *
61 * @param nodeKind the kind of node, for example {@link Type#ELEMENT}
62 * @param nameCode the nameCode representing the name of the node
63 * @param namePool the namePool holding the name codes
64 * @since 8.4
65 */
66
67 public NameTest(int nodeKind, int nameCode, NamePool namePool) {
68 this.nodeKind = nodeKind;
69 this.fingerprint = nameCode & NamePool.FP_MASK;
70 this.namePool = namePool;
71 this.uType = UType.fromTypeCode(nodeKind);
72 }
73
74 /**
75 * Create a NameTest to match nodes by name
76 *
77 * @param nodeKind the kind of node, for example {@link Type#ELEMENT}
78 * @param name the name of the nodes that this NameTest will match
79 * @param pool the namePool holding the name codes
80 * @since 9.4
81 */
82
83 public NameTest(int nodeKind, NodeName name, NamePool pool) {
84 this.uri = name.getURI();
85 this.localName = name.getLocalPart();
86 this.nodeKind = nodeKind;
87 this.fingerprint = name.obtainFingerprint(pool);
88 this.namePool = pool;
89 this.uType = UType.fromTypeCode(nodeKind);
90 }
91
92 /**
93 * Get the NamePool associated with this NameTest
94 *
95 * @return the NamePool
96 */
97
98 public NamePool getNamePool() {
99 return namePool;
100 }
101
102 /**
103 * Get the node kind that this name test matches
104 *
105 * @return the matching node kind
106 */
107
108 public int getNodeKind() {
109 return nodeKind;
110 }
111
112 /**
113 * Get the corresponding {@link net.sf.saxon.type.UType}. A UType is a union of primitive item
114 * types.
115 *
116 * @return the smallest UType that subsumes this item type
117 */
118 public UType getUType() {
119 return uType;
120 }
121
122 /**
123 * Test whether this node test is satisfied by a given node. This method is only
124 * fully supported for a subset of NodeTests, because it doesn't provide all the information
125 * needed to evaluate all node tests. In particular (a) it can't be used to evaluate a node
126 * test of the form element(N,T) or schema-element(E) where it is necessary to know whether the
127 * node is nilled, and (b) it can't be used to evaluate a node test of the form
128 * document-node(element(X)). This in practice means that it is used (a) to evaluate the
129 * simple node tests found in the XPath 1.0 subset used in XML Schema, and (b) to evaluate
130 * node tests where the node kind is known to be an attribute.
131 *
132 * @param nodeKind The kind of node to be matched
133 * @param name identifies the expanded name of the node to be matched.
134 * The value should be null for a node with no name.
135 * @param annotation The actual content type of the node
136 */
137 @Override
138 public boolean matches(int nodeKind, NodeName name, SchemaType annotation) {
139 if (nodeKind != this.nodeKind) {
140 return false;
141 }
142 if (name.hasFingerprint()) {
143 return name.getFingerprint() == this.fingerprint;
144 } else {
145 computeUriAndLocal();
146 return name.hasURI(uri) && name.getLocalPart().equals(localName);
147 }
148 }
149
150 public IntPredicate getMatcher(final NodeVectorTree tree) {
151 final byte[] nodeKindArray = tree.getNodeKindArray();
152 final int[] nameCodeArray = tree.getNameCodeArray();
153 return nodeNr -> (nameCodeArray[nodeNr] & 0xfffff) == fingerprint &&
154 (nodeKindArray[nodeNr] & 0x0f) == nodeKind;
155 }
156
157 /**
158 * Test whether this node test is satisfied by a given node. This alternative
159 * method is used in the case of nodes where calculating the fingerprint is expensive,
160 * for example DOM or JDOM nodes.
161 *
162 * @param node the node to be matched
163 */
164
165 public boolean matchesNode(NodeInfo node) {
166 if (node.getNodeKind() != nodeKind) {
167 return false;
168 }
169
170 // Two different algorithms are used for name matching. If the fingerprint of the node is readily
171 // available, we use it to do an integer comparison. Otherwise, we do string comparisons on the URI
172 // and local name. In practice, Saxon's native node implementations use fingerprint matching, while
173 // DOM and JDOM nodes use string comparison of names
174
175 if (node.hasFingerprint()) {
176 return node.getFingerprint() == fingerprint;
177 } else {
178 computeUriAndLocal();
179 return localName.equals(node.getLocalPart()) && uri.equals(node.getURI());
180 }
181 }
182
183 private void computeUriAndLocal() {
184 if (uri == null || localName == null) {
185 StructuredQName name = namePool.getUnprefixedQName(fingerprint);
186 uri = name.getURI();
187 localName = name.getLocalPart();
188 }
189 }
190
191 /**
192 * Test whether the NameTest matches a given QName
193 *
194 * @param qname the QName to be matched
195 * @return true if the name matches
196 */
197
198 public boolean matches(StructuredQName qname) {
199 computeUriAndLocal();
200 return qname.getLocalPart().equals(localName) && qname.hasURI(uri);
201 }
202
203 /**
204 * Determine the default priority of this node test when used on its own as a Pattern
205 */
206
207 public final double getDefaultPriority() {
208 return 0.0;
209 }
210
211 /**
212 * Get the fingerprint required
213 */
214
215 public int getFingerprint() {
216 return fingerprint;
217 }
218
219 /**
220 * Get the name of the nodes matched by this nodetest, if it matches a specific name.
221 * Return null if the node test matches nodes of more than one name
222 */
223 @Override
224 public StructuredQName getMatchingNodeName() {
225 computeUriAndLocal();
226 return new StructuredQName("", uri, localName);
227 }
228
229 /**
230 * Determine the types of nodes to which this pattern applies. Used for optimisation.
231 * For patterns that match nodes of several types, return Type.NODE
232 *
233 * @return the type of node matched by this pattern. e.g. Type.ELEMENT or Type.TEXT
234 */
235
236 public int getPrimitiveType() {
237 return nodeKind;
238 }
239
240 /**
241 * Get the set of node names allowed by this NodeTest. This is returned as a set of Integer fingerprints.
242 * A null value indicates that all names are permitted (i.e. that there are no constraints on the node name.
243 * The default implementation returns null.
244 */
245
246 /*@NotNull*/
247 public Optional<IntSet> getRequiredNodeNames() {
248 return Optional.of(new IntSingletonSet(fingerprint));
249 }
250
251 /**
252 * Get the namespace URI matched by this nametest
253 *
254 * @return the namespace URI (using "" for the "null namepace")
255 */
256
257 public String getNamespaceURI() {
258 computeUriAndLocal();
259 return uri;
260 }
261
262 /**
263 * Get the local name matched by this nametest
264 *
265 * @return the local name
266 */
267
268 public String getLocalPart() {
269 computeUriAndLocal();
270 return localName;
271 }
272
273 public String toString() {
274 switch (nodeKind) {
275 case Type.ELEMENT:
276 return "element(" + namePool.getEQName(fingerprint) + ")";
277 case Type.ATTRIBUTE:
278 return "attribute(" + namePool.getEQName(fingerprint) + ")";
279 case Type.PROCESSING_INSTRUCTION:
280 return "processing-instruction(" + namePool.getLocalName(fingerprint) + ')';
281 case Type.NAMESPACE:
282 return "namespace-node(" + namePool.getLocalName(fingerprint) + ')';
283 }
284 return namePool.getEQName(fingerprint);
285 }
286
287 /**
288 * Returns a hash code value for the object.
289 */
290
291 public int hashCode() {
292 return nodeKind << 20 ^ fingerprint;
293 }
294
295 /**
296 * Determines whether two NameTests are equal
297 */
298
299 public boolean equals(Object other) {
300 return other instanceof NameTest &&
301 ((NameTest) other).namePool == namePool &&
302 ((NameTest) other).nodeKind == nodeKind &&
303 ((NameTest) other).fingerprint == fingerprint;
304 }
305
306 /**
307 * Generate Javascript code to test if a name matches the test.
308 *
309 * @return JS code as a string. The generated code will be used
310 * as the body of a JS function in which the argument name "q" is an
311 * XdmQName object holding the name. The XdmQName object has properties
312 * uri and local.
313 * @param targetVersion the version of Saxon-JS being targeted
314 */
315 public String generateJavaScriptNameTest(int targetVersion) {
316 computeUriAndLocal();
317 return "q.uri==='" + ExpressionPresenter.jsEscape(uri) + "'&&q.local==='" + localName + "'";
318 }
319
320 /**
321 * Generate Javascript code to test whether an item conforms to this item type
322 * @param knownToBe NodeTest that the item is known to conform to (no run-time test needed)
323 * @param targetVersion the version of Saxon-JS being targeted
324 * @return a Javascript instruction or sequence of instructions, which can be used as the body
325 * of a Javascript function, and which returns a boolean indication whether the value of the
326 * variable "item" is an instance of this item type.
327 *
328 */
329 @Override
330 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) {
331
332 boolean knownKind = knownToBe.getUType() == this.getUType();
333 if (nodeKind == Type.ATTRIBUTE && getNamespaceURI().equals("")) {
334 // Optimization
335 String nt = "item.name==='" + getLocalPart() + "'";
336 return "return " + (knownKind ? nt : "SaxonJS.U.isAttr(item) && " + nt);
337 }
338 String instNode = "";
339 if (!knownKind) {
340 if (knownToBe instanceof NodeTest) {
341 instNode = "item.nodeType===" + nodeKind + " && ";
342 } else if (nodeKind == Type.ATTRIBUTE) {
343 instNode = "SaxonJS.U.isAttr(item) && ";
344 } else if (nodeKind == Type.NAMESPACE) {
345 instNode = "SaxonJS.U.isNamespaceNode(item) && ";
346 } else {
347 instNode = "SaxonJS.U.isNode(item) && item.nodeType===" + nodeKind + " && ";
348 }
349 }
350 if (targetVersion == 1) {
351 return "var q=SaxonJS.U.nameOfNode(item); return " + instNode + generateJavaScriptNameTest(targetVersion) + ";";
352 } else {
353 computeUriAndLocal();
354 return "return " + instNode +
355 "SaxonJS.U.hasLocalName(item,'" + localName + "')&&SaxonJS.U.hasURI(item,'" +
356 ExpressionPresenter.jsEscape(uri) + "')";
357 }
358 }
359
360 /**
361 * Get extra diagnostic information about why a supplied item does not conform to this
362 * item type, if available. If extra information is returned, it should be in the form of a complete
363 * sentence, minus the closing full stop. No information should be returned for obvious cases.
364 *
365 * @param item the item that doesn't match this type
366 * @param th the type hierarchy cache
367 * @return optionally, a message explaining why the item does not match the type
368 */
369 @Override
370 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
371 Optional<String> explanation = super.explainMismatch(item, th);
372 if (explanation.isPresent()) {
373 return explanation;
374 }
375 return Optional.of("The node has the wrong name");
376 }
377
378 public String toShortString() {
379 switch (nodeKind) {
380 case Type.ELEMENT:
381 return getNamespaceURI().isEmpty() ? namePool.getLocalName(getFingerprint()) : toString();
382 case Type.ATTRIBUTE:
383 return "@" + (getNamespaceURI().isEmpty() ? namePool.getLocalName(getFingerprint()) : toString());
384 default:
385 return toString();
386 }
387 }
388
389 }
390