Debian Codegraph @

net/sf/saxon/pattern/ContentTypeTest.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.Configuration;
11 import net.sf.saxon.functions.Nilled_1;
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.trans.SaxonErrorCode;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.tiny.NodeVectorTree;
18 import net.sf.saxon.tree.tiny.TinyTree;
19 import net.sf.saxon.type.*;
20
21 import java.util.Optional;
22 import java.util.function.IntPredicate;
23
24 /**
25 * NodeTest is an interface that enables a test of whether a node matches particular
26 * conditions. ContentTypeTest tests for an element or attribute node with a particular
27 * type annotation.
28 *
29 * @author Michael H. Kay
30 */
31
32 public class ContentTypeTest extends NodeTest {
33
34 private int kind; // element or attribute
35 private SchemaType schemaType;
36 private Configuration config;
37 private boolean nillable = false;
38
39 /**
40 * Create a ContentTypeTest
41 *
42 * @param nodeKind the kind of nodes to be matched: always elements or attributes
43 * @param schemaType the required type annotation, as a simple or complex schema type
44 * @param config the Configuration, supplied because this KindTest needs access to schema information
45 * @param nillable indicates whether an element with xsi:nil=true satisifies the test
46 */
47
48 public ContentTypeTest(int nodeKind, SchemaType schemaType, Configuration config, boolean nillable) {
49 this.kind = nodeKind;
50 this.schemaType = schemaType;
51 this.config = config;
52 this.nillable = nillable;
53 }
54
55 /**
56 * Get the corresponding {@link net.sf.saxon.type.UType}. A UType is a union of primitive item
57 * types.
58 *
59 * @return the smallest UType that subsumes this item type
60 */
61 public UType getUType() {
62 return kind == Type.ELEMENT ? UType.ELEMENT : UType.ATTRIBUTE;
63 }
64
65 /**
66 * Indicate whether nilled elements should be matched (the default is false)
67 *
68 * @param nillable true if nilled elements should be matched
69 */
70 public void setNillable(boolean nillable) {
71 this.nillable = nillable;
72 }
73
74 /**
75 * The test is nillable if a question mark was specified as the occurrence indicator
76 *
77 * @return true if the test is nillable
78 */
79
80 public boolean isNillable() {
81 return nillable;
82 }
83
84 public SchemaType getSchemaType() {
85 return schemaType;
86 }
87
88 public int getNodeKind() {
89 return kind;
90 }
91
92 /**
93 * Test whether this node test is satisfied by a given node. This method is only
94 * fully supported for a subset of NodeTests, because it doesn't provide all the information
95 * needed to evaluate all node tests. In particular (a) it can't be used to evaluate a node
96 * test of the form element(N,T) or schema-element(E) where it is necessary to know whether the
97 * node is nilled, and (b) it can't be used to evaluate a node test of the form
98 * document-node(element(X)). This in practice means that it is used (a) to evaluate the
99 * simple node tests found in the XPath 1.0 subset used in XML Schema, and (b) to evaluate
100 * node tests where the node kind is known to be an attribute.
101 *
102 * @param nodeKind The kind of node to be matched
103 * @param name identifies the expanded name of the node to be matched.
104 * The value should be null for a node with no name.
105 * @param annotation The actual content type of the node
106 */
107 @Override
108 public boolean matches(int nodeKind, NodeName name, SchemaType annotation) {
109 return kind == nodeKind && matchesAnnotation(annotation);
110 }
111
112 @Override
113 public IntPredicate getMatcher(final NodeVectorTree tree) {
114 final byte[] nodeKindArray = tree.getNodeKindArray();
115 return nodeNr -> (nodeKindArray[nodeNr]&0x0f) == kind &&
116 matchesAnnotation(((TinyTree) tree).getSchemaType(nodeNr)) &&
117 (nillable || !((TinyTree) tree).isNilled(nodeNr));
118 }
119
120 /**
121 * Test whether this node test is satisfied by a given node. This alternative
122 * method is used in the case of nodes where calculating the fingerprint is expensive,
123 * for example DOM or JDOM nodes.
124 *
125 * @param node the node to be matched
126 */
127
128 public boolean matchesNode(/*@NotNull*/ NodeInfo node) {
129 return node.getNodeKind() == kind &&
130 matchesAnnotation(node.getSchemaType())
131 && (nillable || !Nilled_1.isNilled(node));
132 }
133
134 private boolean matchesAnnotation(SchemaType annotation) {
135 if (annotation == null) {
136 return false;
137 }
138 if (schemaType == AnyType.getInstance()) {
139 return true;
140 }
141
142 if (annotation.equals(schemaType)) {
143 return true;
144 }
145
146 // see if the type annotation is a subtype of the required type
147 int r = config.getTypeHierarchy().schemaTypeRelationship(annotation, schemaType);
148 return r == TypeHierarchy.SAME_TYPE || r == TypeHierarchy.SUBSUMED_BY;
149 }
150
151 /**
152 * Determine the default priority of this node test when used on its own as a Pattern
153 */
154
155 public final double getDefaultPriority() {
156 return 0;
157 }
158
159 /**
160 * Determine the types of nodes to which this pattern applies. Used for optimisation.
161 *
162 * @return the type of node matched by this pattern. e.g. Type.ELEMENT or Type.TEXT
163 */
164
165 public int getPrimitiveType() {
166 return kind;
167 }
168
169 /**
170 * Get the content type allowed by this NodeTest (that is, the type annotation of the matched nodes).
171 * Return AnyType if there are no restrictions. The default implementation returns AnyType.
172 */
173
174 public SchemaType getContentType() {
175 return schemaType;
176 }
177
178 /**
179 * Get the item type of the atomic values that will be produced when an item
180 * of this type is atomized (assuming that atomization succeeds)
181 */
182
183 /*@NotNull*/
184 public AtomicType getAtomizedItemType() {
185 SchemaType type = schemaType;
186 try {
187 if (type.isAtomicType()) {
188 return (AtomicType) type;
189 } else if (type instanceof ListType) {
190 SimpleType mem = ((ListType) type).getItemType();
191 if (mem.isAtomicType()) {
192 return (AtomicType) mem;
193 }
194 } else if (type instanceof ComplexType && ((ComplexType) type).isSimpleContent()) {
195 SimpleType ctype = ((ComplexType) type).getSimpleContentType();
196 assert ctype != null;
197 if (ctype.isAtomicType()) {
198 return (AtomicType) ctype;
199 } else if (ctype instanceof ListType) {
200 SimpleType mem = ((ListType) ctype).getItemType();
201 if (mem.isAtomicType()) {
202 return (AtomicType) mem;
203 }
204 }
205 }
206 } catch (MissingComponentException e) {
207 return BuiltInAtomicType.ANY_ATOMIC;
208 }
209 return BuiltInAtomicType.ANY_ATOMIC;
210 }
211
212 /**
213 * Ask whether values of this type are atomizable
214 *
215 * @return true unless it is known that these items will be elements with element-only
216 * content, in which case return false
217 * @param th The type hierarchy cache
218 */
219
220 public boolean isAtomizable(TypeHierarchy th) {
221 return !(schemaType.isComplexType() &&
222 ((ComplexType) schemaType).getVariety() == ComplexType.VARIETY_ELEMENT_ONLY);
223 }
224
225 public String toString() {
226 return (kind == Type.ELEMENT ? "element(*, " : "attribute(*, ") +
227 schemaType.getEQName() + ')';
228 }
229
230 /**
231 * Return a string representation of this ItemType suitable for use in stylesheet
232 * export files. This differs from the result of toString() in that it will not contain
233 * any references to anonymous types. Note that it may also use the Saxon extended syntax
234 * for union types and tuple types. The default implementation returns the result of
235 * calling {@code toString()}.
236 *
237 * @return the string representation as an instance of the XPath SequenceType construct
238 */
239 @Override
240 public String toExportString() {
241 return (kind == Type.ELEMENT ? "element(*, " : "attribute(*, ") +
242 schemaType.getNearestNamedType().getEQName() + ')';
243 }
244
245 /**
246 * Returns a hash code value for the object.
247 */
248
249 public int hashCode() {
250 return kind << 20 ^ schemaType.hashCode();
251 }
252
253 /**
254 * Indicates whether some other object is "equal to" this one.
255 */
256 public boolean equals(Object other) {
257 return other instanceof ContentTypeTest &&
258 ((ContentTypeTest) other).kind == kind &&
259 ((ContentTypeTest) other).schemaType == schemaType &&
260 ((ContentTypeTest) other).nillable == nillable;
261 }
262
263 /**
264 * Generate Javascript code to test whether an item conforms to this item type
265 *
266 * @return a Javascript instruction or sequence of instructions, which can be used as the body
267 * of a Javascript function, and which returns a boolean indication whether the value of the
268 * variable "item" is an instance of this item type.
269 * @throws XPathException if JS code cannot be generated for this item type, for example because
270 * the test is schema-aware.
271 * @param knownToBe An item type that the supplied item is known to conform to; the generated code
272 * can assume that the item is an instance of this type.
273 * @param targetVersion The version of Saxon-JS for which code is being generated. Currently either 1 or 2.
274
275 */
276 @Override
277 public String generateJavaScriptItemTypeTest(ItemType knownToBe, int targetVersion) throws XPathException {
278 if (kind == Type.ELEMENT) {
279 if (schemaType == Untyped.getInstance() || schemaType == AnyType.getInstance()) {
280 return NodeKindTest.makeNodeKindTest(getNodeKind()).generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion);
281 } else if (schemaType == BuiltInAtomicType.UNTYPED_ATOMIC || schemaType == BuiltInAtomicType.ANY_ATOMIC) {
282 return "return false;";
283 }
284 } else if (kind == Type.ATTRIBUTE) {
285 if (schemaType == Untyped.getInstance() || schemaType == AnyType.getInstance()
286 || schemaType == BuiltInAtomicType.UNTYPED_ATOMIC || schemaType == BuiltInAtomicType.ANY_ATOMIC) {
287 return NodeKindTest.makeNodeKindTest(getNodeKind()).generateJavaScriptItemTypeTest(AnyItemType.getInstance(), targetVersion);
288 }
289 }
290 throw new XPathException("Cannot generate JS code to test type annotations", SaxonErrorCode.SXJS0001);
291 }
292
293 /**
294 * Get extra diagnostic information about why a supplied item does not conform to this
295 * item type, if available. If extra information is returned, it should be in the form of a complete
296 * sentence, minus the closing full stop. No information should be returned for obvious cases.
297 *
298 * @param item the item that doesn't match this type
299 * @param th the type hierarchy cache
300 * @return optionally, a message explaining why the item does not match the type
301 */
302 @Override
303 public Optional<String> explainMismatch(Item item, TypeHierarchy th) {
304 Optional<String> explanation = super.explainMismatch(item, th);
305 if (explanation.isPresent()) {
306 return explanation;
307 }
308 NodeInfo node = (NodeInfo) item;
309 if (!matchesAnnotation(((NodeInfo)item).getSchemaType())) {
310 if (node.getSchemaType() == Untyped.getInstance()) {
311 return Optional.of("The supplied node has not been schema-validated");
312 }
313 if (node.getSchemaType() == BuiltInAtomicType.UNTYPED_ATOMIC) {
314 return Optional.of("The supplied node has not been schema-validated");
315 }
316 return Optional.of("The supplied node has the wrong type annotation (" + node.getSchemaType().getDescription() + ")");
317 }
318 if (Nilled_1.isNilled(node) && !nillable) {
319 return Optional.of("The supplied node has xsi:nil='true', which the required type does not allow");
320 }
321 return Optional.empty();
322 }
323
324 }
325