Debian Codegraph @

net/sf/saxon/expr/SingletonAtomizer.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.expr;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.parser.*;
12 import net.sf.saxon.ma.map.MapType;
13 import net.sf.saxon.om.AtomicSequence;
14 import net.sf.saxon.om.Item;
15 import net.sf.saxon.om.SequenceIterator;
16 import net.sf.saxon.pattern.NodeKindTest;
17 import net.sf.saxon.pattern.NodeTest;
18 import net.sf.saxon.trace.ExpressionPresenter;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.type.*;
21 import net.sf.saxon.value.AtomicValue;
22 import net.sf.saxon.value.Cardinality;
23
24 /**
25 * A SingletonAtomizer combines the functions of an Atomizer and a CardinalityChecker: it is used to
26 * atomize a sequence of nodes, checking that the result of the atomization contains zero or one atomic
27 * values. Note that the input may be a sequence of nodes or atomic values, even though the result must
28 * contain at most one atomic value.
29 */
30
31 public final class SingletonAtomizer extends UnaryExpression {
32
33 private boolean allowEmpty;
34 private RoleDiagnostic role;
35
36 /**
37 * Constructor
38 *
39 * @param sequence the sequence to be atomized
40 * @param role contains information about where the expression appears, for use in any error message
41 * @param allowEmpty true if the result sequence is allowed to be empty.
42 */
43
44 public SingletonAtomizer(Expression sequence, RoleDiagnostic role, boolean allowEmpty) {
45 super(sequence);
46 this.allowEmpty = allowEmpty;
47 this.role = role;
48 }
49
50 protected OperandRole getOperandRole() {
51 return OperandRole.SINGLE_ATOMIC;
52 }
53
54 /**
55 * Ask if the expression is allowed to return an empty sequence
56 * @return true if the expected cardinality is zero-or-one, false if it is exactly-one
57 */
58
59 public boolean isAllowEmpty() {
60 return allowEmpty;
61 }
62
63 /**
64 * Simplify an expression
65 *
66 */
67
68 /*@NotNull*/
69 public Expression simplify() throws XPathException {
70 Expression operand = getBaseExpression().simplify();
71 if (operand instanceof Literal && ((Literal) operand).getValue() instanceof AtomicValue) {
72 return operand;
73 }
74 setBaseExpression(operand);
75 return this;
76 }
77
78 /**
79 * Type-check the expression
80 */
81
82 /*@NotNull*/
83 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
84 getOperand().typeCheck(visitor, contextInfo);
85 Expression operand = getBaseExpression();
86 ExpressionTool.resetStaticProperties(this);
87 if (Literal.isEmptySequence(operand)) {
88 if (!allowEmpty) {
89 typeError("An empty sequence is not allowed as the " + role.getMessage(), role.getErrorCode(), null);
90 }
91 return operand;
92 }
93 ItemType operandType = operand.getItemType();
94 if (operandType.isPlainType()) {
95 return operand;
96 }
97 if (!operandType.isAtomizable(visitor.getConfiguration().getTypeHierarchy())) {
98 XPathException err;
99 if (operandType instanceof MapType) {
100 err = new XPathException("Cannot atomize a map (" + toShortString() + ")", "FOTY0013");
101 } else if (operandType instanceof FunctionItemType) {
102 err = new XPathException("Cannot atomize a function item", "FOTY0013");
103 } else {
104 err = new XPathException(
105 "Cannot atomize an element that is defined in the schema to have element-only content", "FOTY0012");
106 }
107 err.setIsTypeError(true);
108 err.setLocation(getLocation());
109 err.setFailingExpression(getParentExpression());
110 throw err;
111 }
112 return this;
113 }
114
115
116 /*@NotNull*/
117 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
118 Expression exp = super.optimize(visitor, contextInfo);
119 if (exp == this) {
120 // Since it's an error for the result to have more than one item, there's no point sorting the input
121 setBaseExpression(getBaseExpression().unordered(true, false));
122 if (getBaseExpression().getItemType().isPlainType() &&
123 !Cardinality.allowsMany(getBaseExpression().getCardinality())) {
124 return getBaseExpression();
125 }
126 return this;
127 } else {
128 return exp;
129 }
130 }
131
132 /**
133 * Determine the special properties of this expression
134 *
135 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}.
136 */
137
138 public int computeSpecialProperties() {
139 int p = super.computeSpecialProperties();
140 return p | StaticProperty.NO_NODES_NEWLY_CREATED;
141 }
142
143 /**
144 * Copy an expression. This makes a deep copy.
145 *
146 * @return the copy of the original expression
147 * @param rebindings variables that need to be re-bound
148 */
149
150 /*@NotNull*/
151 public Expression copy(RebindingMap rebindings) {
152 Expression e2 = new SingletonAtomizer(getBaseExpression().copy(rebindings), role, allowEmpty);
153 ExpressionTool.copyLocationInfo(this, e2);
154 return e2;
155 }
156
157 /**
158 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
159 * This method indicates which of these methods is provided directly. The other methods will always be available
160 * indirectly, using an implementation that relies on one of the other methods.
161 *
162 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
163 * {@link #PROCESS_METHOD}
164 */
165 @Override
166 public int getImplementationMethod() {
167 return EVALUATE_METHOD;
168 }
169
170
171 /**
172 * Get the (partial) name of a class that supports streaming of this kind of expression
173 *
174 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
175 * or null if there is no such class
176 */
177 @Override
178 public String getStreamerName() {
179 return "SingletonAtomizer";
180 }
181
182 /**
183 * Get the RoleLocator (used to construct error messages)
184 *
185 * @return the role locator
186 */
187
188 public RoleDiagnostic getRole() {
189 return role;
190 }
191
192
193 /*@Nullable*/
194 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
195 PathMap.PathMapNodeSet result = getBaseExpression().addToPathMap(pathMap, pathMapNodeSet);
196 if (result != null) {
197 TypeHierarchy th = getConfiguration().getTypeHierarchy();
198 ItemType operandItemType = getBaseExpression().getItemType();
199 if (th.relationship(NodeKindTest.ELEMENT, operandItemType) != TypeHierarchy.DISJOINT ||
200 th.relationship(NodeKindTest.DOCUMENT, operandItemType) != TypeHierarchy.DISJOINT) {
201 result.setAtomized();
202 }
203 }
204 return null;
205 }
206
207 /**
208 * Evaluate as an Item. This should only be called if a singleton or empty sequence is required;
209 * it throws a type error if the underlying sequence is multi-valued.
210 */
211
212 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
213 int found = 0;
214 AtomicValue result = null;
215 SequenceIterator iter = getBaseExpression().iterate(context);
216 Item item;
217 while ((item = iter.next()) != null) {
218 AtomicSequence seq = item.atomize();
219 found += seq.getLength();
220 if (found > 1) {
221 typeError(
222 "A sequence of more than one item is not allowed as the " +
223 role.getMessage() + CardinalityChecker.depictSequenceStart(getBaseExpression().iterate(context), 3),
224 role.getErrorCode(), context);
225 }
226 if (found == 1) {
227 result = seq.head();
228 }
229 }
230 if (found == 0 && !allowEmpty) {
231 typeError("An empty sequence is not allowed as the " +
232 role.getMessage(), role.getErrorCode(), null);
233 }
234 return result;
235 }
236
237 /**
238 * Determine the data type of the items returned by the expression, if possible
239 *
240 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER. For this class, the
241 * result is always an atomic type, but it might be more specific.
242 */
243
244 /*@NotNull*/
245 public ItemType getItemType() {
246 boolean isSchemaAware = true;
247 try {
248 isSchemaAware = getPackageData().isSchemaAware();
249 } catch (NullPointerException err) {
250 // ultra-cautious code in case expression container has not been set
251 if (!getConfiguration().isLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION)) {
252 isSchemaAware = false;
253 }
254 }
255 ItemType in = getBaseExpression().getItemType();
256 if (in.isPlainType()) {
257 return in;
258 } else if (in instanceof NodeTest) {
259 UType kinds = in.getUType();
260 if (!isSchemaAware) {
261 // Some node-kinds always have a typed value that's a string
262
263 if (Atomizer.STRING_KINDS.subsumes(kinds)) {
264 return BuiltInAtomicType.STRING;
265 }
266 // Some node-kinds are always untyped atomic; some are untypedAtomic provided that the configuration
267 // is untyped
268
269 if (Atomizer.UNTYPED_IF_UNTYPED_KINDS.subsumes(kinds)) {
270 return BuiltInAtomicType.UNTYPED_ATOMIC;
271 }
272 } else {
273 if (Atomizer.UNTYPED_KINDS.subsumes(kinds)) {
274 return BuiltInAtomicType.UNTYPED_ATOMIC;
275 }
276 }
277
278 return in.getAtomizedItemType();
279 } else if (in instanceof JavaExternalObjectType) {
280 return in.getAtomizedItemType();
281 }
282 return BuiltInAtomicType.ANY_ATOMIC;
283 }
284
285 /**
286 * Determine the static cardinality of the expression
287 */
288
289 public int computeCardinality() {
290 if (allowEmpty) {
291 return StaticProperty.ALLOWS_ZERO_OR_ONE;
292 } else {
293 return StaticProperty.EXACTLY_ONE;
294 }
295 }
296
297 /**
298 * Give a string representation of the expression name for use in diagnostics
299 *
300 * @return the expression name, as a string
301 */
302
303 public String getExpressionName() {
304 return "atomizeSingleton";
305 }
306
307 /**
308 * Diagnostic print of expression structure. The abstract expression tree
309 * is written to the supplied output destination.
310 *
311 * @param out
312 */
313 @Override
314 public void export(ExpressionPresenter out) throws XPathException {
315
316 out.startElement("atomSing", this);
317 if (allowEmpty) {
318 out.emitAttribute("card", "?");
319 }
320 out.emitAttribute("diag", getRole().save());
321 getBaseExpression().export(out);
322 out.endElement();
323 }
324
325 @Override
326 public String toShortString() {
327 return getBaseExpression().toShortString();
328 }
329
330
331 }
332