Debian Codegraph @

net/sf/saxon/expr/Atomizer.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.event.ReceiverOptions;
11 import net.sf.saxon.expr.instruct.Block;
12 import net.sf.saxon.expr.instruct.Choose;
13 import net.sf.saxon.expr.instruct.ValueOf;
14 import net.sf.saxon.expr.parser.*;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.ma.arrays.ArrayItemType;
17 import net.sf.saxon.ma.map.MapType;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.NameTest;
20 import net.sf.saxon.pattern.NodeKindTest;
21 import net.sf.saxon.pattern.NodeTest;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.iter.AtomizingIterator;
24 import net.sf.saxon.tree.iter.EmptyIterator;
25 import net.sf.saxon.tree.iter.UntypedAtomizingIterator;
26 import net.sf.saxon.type.*;
27 import net.sf.saxon.value.AtomicValue;
28 import net.sf.saxon.value.Cardinality;
29 import net.sf.saxon.value.EmptySequence;
30
31
32 /**
33 * An Atomizer is an expression corresponding essentially to the fn:data() function: it
34 * maps a sequence by replacing nodes with their typed values
35 */
36
37 public final class Atomizer extends UnaryExpression {
38
39 private boolean untyped = false; //set to true if it is known that the nodes being atomized will be untyped
40 private boolean singleValued = false; // set to true if all atomized nodes will atomize to a single atomic value
41 private ItemType operandItemType = null;
42 private RoleDiagnostic roleDiagnostic = null;
43
44 /**
45 * Constructor
46 *
47 * @param sequence the sequence to be atomized
48 * @param role (may be null) additional information for use in diagnostics
49 */
50
51 public Atomizer(Expression sequence, RoleDiagnostic role) {
52 super(sequence);
53 this.roleDiagnostic = role;
54 sequence.setFlattened(true);
55 }
56
57 /**
58 * Make an atomizer with a given operand
59 *
60 * @param sequence the operand
61 * @param role (may be null) additional information for diagnostics
62 * @return an Atomizer that atomizes the given operand, or another expression that returns the same result
63 */
64
65 public static Expression makeAtomizer(Expression sequence, RoleDiagnostic role) {
66 if (sequence instanceof Literal && ((Literal) sequence).getValue() instanceof AtomicSequence) {
67 return sequence;
68 } else {
69 return new Atomizer(sequence, role);
70 }
71 }
72
73 protected OperandRole getOperandRole() {
74 return OperandRole.ATOMIC_SEQUENCE;
75 }
76
77 /**
78 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
79 * This method indicates which of these methods is provided directly. The other methods will always be available
80 * indirectly, using an implementation that relies on one of the other methods.
81 *
82 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
83 * {@link #PROCESS_METHOD}
84 */
85
86 public int getImplementationMethod() {
87 return ITERATE_METHOD | WATCH_METHOD;
88 }
89
90 public ItemType getOperandItemType() {
91 if (operandItemType == null) {
92 operandItemType = getBaseExpression().getItemType();
93 }
94 return operandItemType;
95 }
96
97 /**
98 * Simplify an expression
99 *
100 */
101
102 /*@NotNull*/
103 public Expression simplify() throws XPathException {
104 //untyped = !getContainer().getPackageData().isSchemaAware();
105 untyped = !getPackageData().isSchemaAware();
106 computeSingleValued(getConfiguration().getTypeHierarchy());
107 Expression operand = getBaseExpression().simplify();
108 if (operand instanceof Literal) {
109 GroundedValue val = ((Literal) operand).getValue();
110
111 if (val instanceof AtomicValue) {
112 return operand;
113 }
114 SequenceIterator iter = val.iterate();
115 Item i;
116 while ((i = iter.next()) != null) {
117 if (i instanceof NodeInfo) {
118 return this;
119 }
120 if (i instanceof Function) {
121 if (((Function)i).isArray()) {
122 return this;
123 } else if (((Function)i).isMap()) {
124 XPathException err = new XPathException(
125 expandMessage("Cannot atomize a map (" + i.toShortString() + ")"), "FOTY0013");
126 err.setIsTypeError(true);
127 err.setLocation(getLocation());
128 throw err;
129 } else {
130 XPathException err = new XPathException(
131 expandMessage("Cannot atomize a function item"), "FOTY0013");
132 err.setIsTypeError(true);
133 err.setLocation(getLocation());
134 throw err;
135 }
136 }
137 }
138 // if all items in the sequence are atomic (they generally will be, since this is
139 // done at compile time), then return the sequence
140 return operand;
141 } else if (operand instanceof ValueOf && (((ValueOf) operand).getOptions() & ReceiverOptions.DISABLE_ESCAPING) == 0) {
142 // XSLT users tend to use ValueOf unnecessarily
143 return ((ValueOf) operand).convertToCastAsString();
144 }
145 setBaseExpression(operand);
146 return this;
147 }
148
149 /**
150 * Type-check the expression
151 */
152
153 /*@NotNull*/
154 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
155 getOperand().typeCheck(visitor, contextInfo);
156 untyped = untyped | !visitor.getStaticContext().getPackageData().isSchemaAware();
157
158 // If the configuration allows typed data, check whether the content type of these particular nodes is untyped
159 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
160 computeSingleValued(th);
161 resetLocalStaticProperties();
162 ItemType operandType = getOperandItemType();
163 if (th.isSubType(operandType, BuiltInAtomicType.ANY_ATOMIC)) {
164 return getBaseExpression();
165 }
166 if (!operandType.isAtomizable(th)) {
167 XPathException err;
168 if (operandType instanceof FunctionItemType) {
169 String thing = operandType instanceof MapType ? "map" : "function item";
170 err = new XPathException(
171 expandMessage("Cannot atomize a " + thing), "FOTY0013");
172 } else {
173 err = new XPathException(
174 expandMessage("Cannot atomize an element that is defined in the schema to have element-only content"), "FOTY0012");
175 }
176 err.setIsTypeError(true);
177 err.setLocation(getLocation());
178 throw err;
179 }
180 getBaseExpression().setFlattened(true);
181 return this;
182 }
183
184 private void computeSingleValued(TypeHierarchy th) {
185 ItemType operandType = getOperandItemType();
186 if (th.relationship(operandType, ArrayItemType.ANY_ARRAY_TYPE) != TypeHierarchy.DISJOINT) {
187 singleValued = false;
188 } else {
189 singleValued = untyped;
190 if (!singleValued) {
191 ItemType nodeType = getBaseExpression().getItemType();
192 if (nodeType instanceof NodeTest) {
193 SchemaType st = ((NodeTest) nodeType).getContentType();
194 if (st == Untyped.getInstance() || st.isAtomicType() || (st.isComplexType() && st != AnyType.getInstance())) {
195 singleValued = true;
196 }
197 if (!nodeType.getUType().overlaps(UType.ELEMENT.union(UType.ATTRIBUTE))) {
198 singleValued = true;
199 }
200 }
201 }
202 }
203 }
204
205 /**
206 * Expand an error message with information about the context in which atomization is taking place
207 * @param message the message to be expanded
208 */
209
210 private String expandMessage(String message) {
211 if (roleDiagnostic == null) {
212 return message;
213 } else {
214 return message + ". Found while atomizing the " + roleDiagnostic.getMessage();
215 }
216 }
217
218
219 /**
220 * Perform optimisation of an expression and its subexpressions.
221 * <p>This method is called after all references to functions and variables have been resolved
222 * to the declaration of the function or variable, and after all type checking has been done.</p>
223 *
224 * @param visitor an expression visitor
225 * @param contextInfo the static type of "." at the point where this expression is invoked.
226 * The parameter is set to null if it is known statically that the context item will be undefined.
227 * If the type of the context item is not known statically, the argument is set to
228 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
229 * @return the original expression, rewritten if appropriate to optimize execution
230 * @throws net.sf.saxon.trans.XPathException
231 * if an error is discovered during this phase
232 * (typically a type error)
233 */
234
235 /*@NotNull*/
236 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
237 Expression exp = super.optimize(visitor, contextInfo);
238 if (exp == this) {
239 final TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
240 Expression operand = getBaseExpression();
241 if (th.isSubType(operand.getItemType(), BuiltInAtomicType.ANY_ATOMIC)) {
242 return operand;
243 }
244 if (operand instanceof ValueOf && (((ValueOf) operand).getOptions() & ReceiverOptions.DISABLE_ESCAPING) == 0) {
245 // XSLT users tend to use ValueOf unnecessarily
246 Expression cast = ((ValueOf) operand).convertToCastAsString();
247 return cast.optimize(visitor, contextInfo);
248 }
249 if (operand instanceof LetExpression || operand instanceof ForExpression) {
250 // replace data(let $x := y return z) by (let $x := y return data(z))
251 Expression action = ((Assignation) operand).getAction();
252 ((Assignation) operand).setAction(new Atomizer(action, roleDiagnostic));
253 return operand.optimize(visitor, contextInfo);
254 }
255 if (operand instanceof Choose) {
256 // replace data(if x then y else z) by (if x then data(y) else data(z)
257 ((Choose)operand).atomizeActions();
258 return operand.optimize(visitor, contextInfo);
259 }
260 if (operand instanceof Block) {
261 // replace data((x,y,z)) by (data(x), data(y), data(z)) as some of the atomizers
262 // may prove to be redundant. (Also, it helps streaming)
263 Operand[] children = ((Block) operand).getOperanda();
264 Expression[] atomizedChildren = new Expression[children.length];
265 for (int i = 0; i < children.length; i++) {
266 atomizedChildren[i] = new Atomizer(children[i].getChildExpression(), roleDiagnostic);
267 }
268 Block newBlock = new Block(atomizedChildren);
269 return newBlock.typeCheck(visitor, contextInfo).optimize(visitor, contextInfo);
270 }
271 if (untyped && operand instanceof AxisExpression &&
272 ((AxisExpression)operand).getAxis() == AxisInfo.ATTRIBUTE &&
273 ((AxisExpression) operand).getNodeTest() instanceof NameTest &&
274 !((AxisExpression) operand).isContextPossiblyUndefined()) {
275 StructuredQName name = ((AxisExpression) operand).getNodeTest().getMatchingNodeName();
276 FingerprintedQName qName = new FingerprintedQName(name, visitor.getConfiguration().getNamePool());
277 AttributeGetter ag = new AttributeGetter(qName);
278 int checks = 0;
279 if (!(((AxisExpression) operand).getContextItemType() instanceof NodeTest)) {
280 checks = AttributeGetter.CHECK_CONTEXT_ITEM_IS_NODE;
281 }
282 ag.setRequiredChecks(checks);
283 ExpressionTool.copyLocationInfo(this, ag);
284 return ag;
285 }
286 }
287 return exp;
288 }
289
290 /**
291 * Ask whether it is known that any nodes in the input will always be untyped
292 *
293 * @return true if it is known that all nodes in the input will be untyped
294 */
295 public boolean isUntyped() {
296 return untyped;
297 }
298
299
300 /**
301 * Determine the special properties of this expression
302 *
303 * @return {@link StaticProperty#NO_NODES_NEWLY_CREATED}.
304 */
305
306 public int computeSpecialProperties() {
307 int p = super.computeSpecialProperties();
308 p &= ~StaticProperty.NODESET_PROPERTIES;
309 return p | StaticProperty.NO_NODES_NEWLY_CREATED;
310 }
311
312 /**
313 * Reset the static properties of the expression to -1, so that they have to be recomputed
314 * next time they are used.
315 */
316 @Override
317 public void resetLocalStaticProperties() {
318 super.resetLocalStaticProperties();
319 operandItemType = null;
320 }
321
322 /**
323 * Copy an expression. This makes a deep copy.
324 *
325 * @return the copy of the original expression
326 * @param rebindings
327 */
328
329 /*@NotNull*/
330 public Expression copy(RebindingMap rebindings) {
331 Atomizer copy = new Atomizer(getBaseExpression().copy(rebindings), roleDiagnostic);
332 copy.untyped = untyped;
333 copy.singleValued = singleValued;
334 ExpressionTool.copyLocationInfo(this, copy);
335 return copy;
336 }
337
338 @Override
339 public String getStreamerName() {
340 return "Atomizer";
341 }
342
343 /**
344 * Iterate over the sequence of values
345 */
346
347 /*@NotNull*/
348 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
349 try {
350 SequenceIterator base = getBaseExpression().iterate(context);
351 return getAtomizingIterator(base, untyped && operandItemType instanceof NodeTest);
352 } catch (XPathException e) {
353 if (roleDiagnostic == null || !e.getErrorCodeQName().hasURI(NamespaceConstant.ERR)) {
354 throw e;
355 } else {
356 String message = expandMessage(e.getMessage());
357 XPathException e2 = new XPathException(message, e.getErrorCodeLocalPart(), e.getLocator());
358 e2.setXPathContext(context);
359 e2.maybeSetLocation(getLocation());
360 throw e2;
361 }
362 }
363 }
364
365 /**
366 * Evaluate as an Item. This should only be called if the Atomizer has cardinality zero-or-one,
367 * which will only be the case if the underlying expression has cardinality zero-or-one.
368 */
369
370 public AtomicValue evaluateItem(XPathContext context) throws XPathException {
371 Item i = getBaseExpression().evaluateItem(context);
372 if (i == null) {
373 return null;
374 } else {
375 return i.atomize().head();
376 }
377 }
378
379 /**
380 * Determine the data type of the items returned by the expression, if possible
381 *
382 * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER. For this class, the
383 * result is always an atomic type, but it might be more specific.
384 */
385
386 /*@NotNull*/
387 public ItemType getItemType() {
388 operandItemType = getBaseExpression().getItemType();
389 TypeHierarchy th = getConfiguration().getTypeHierarchy();
390 return getAtomizedItemType(getBaseExpression(), untyped, th);
391 }
392
393 /**
394 * Compute the type that will result from atomizing the result of a given expression
395 *
396 * @param operand the given expression
397 * @param alwaysUntyped true if it is known that nodes will always be untyped
398 * @param th the type hierarchy cache
399 * @return the item type of the result of evaluating the operand expression, after atomization, or
400 * xs:error if it is known that atomization will return an error
401 */
402
403 public static ItemType getAtomizedItemType(Expression operand, boolean alwaysUntyped, TypeHierarchy th) {
404 ItemType in = operand.getItemType();
405 if (in.isPlainType()) {
406 return in;
407 } else if (in instanceof NodeTest) {
408 UType kinds = in.getUType();
409 if (alwaysUntyped) {
410 // Some node-kinds always have a typed value that's a string
411
412 if (STRING_KINDS.subsumes(kinds)) {
413 return BuiltInAtomicType.STRING;
414 }
415 // Some node-kinds are always untyped atomic; some are untypedAtomic provided that the configuration
416 // is untyped
417
418 if (UNTYPED_IF_UNTYPED_KINDS.subsumes(kinds)) {
419 return BuiltInAtomicType.UNTYPED_ATOMIC;
420 }
421 } else {
422 if (UNTYPED_KINDS.subsumes(kinds)) {
423 return BuiltInAtomicType.UNTYPED_ATOMIC;
424 }
425 }
426
427 return in.getAtomizedItemType();
428 } else if (in instanceof JavaExternalObjectType) {
429 return in.getAtomizedItemType();
430 } else if (in instanceof ArrayItemType) {
431 PlainType ait = ((ArrayItemType)in).getMemberType().getPrimaryType().getAtomizedItemType();
432 return ait == null ? ErrorType.getInstance() : ait;
433 } else if (in instanceof FunctionItemType) {
434 return ErrorType.getInstance();
435 }
436 return BuiltInAtomicType.ANY_ATOMIC;
437 }
438
439 /**
440 * Node kinds whose typed value is always a string
441 */
442 public static final UType STRING_KINDS =
443 UType.NAMESPACE.union(UType.COMMENT).union(UType.PI);
444
445 /**
446 * Node kinds whose typed value is always untypedAtomic
447 */
448
449 public static final UType UNTYPED_KINDS =
450 UType.TEXT.union(UType.DOCUMENT);
451
452 /**
453 * Node kinds whose typed value is untypedAtomic if the configuration is untyped
454 */
455
456 public static final UType UNTYPED_IF_UNTYPED_KINDS =
457 UType.TEXT.union(UType.ELEMENT).union(UType.DOCUMENT).union(UType.ATTRIBUTE);
458
459 /**
460 * Determine the static cardinality of the expression
461 */
462
463 public int computeCardinality() {
464 ItemType in = getOperandItemType();
465 Expression operand = getBaseExpression();
466 if (singleValued) {
467 return operand.getCardinality();
468 } else if (untyped && in instanceof NodeTest) {
469 return operand.getCardinality();
470 } else if (Cardinality.allowsMany(operand.getCardinality())) {
471 return StaticProperty.ALLOWS_ZERO_OR_MORE;
472 } else if (in.isPlainType()) {
473 return operand.getCardinality();
474 } else if (in instanceof NodeTest) {
475 SchemaType schemaType = ((NodeTest) in).getContentType();
476 if (schemaType.isAtomicType()) {
477 // can return at most one atomic value per node
478 return operand.getCardinality();
479 }
480 }
481 return StaticProperty.ALLOWS_ZERO_OR_MORE;
482 }
483
484
485 /**
486 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
487 * by an expression in a source tree.
488 * <p>The default implementation of this method assumes that an expression does no navigation other than
489 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
490 * same context as the containing expression. The method must be overridden for any expression
491 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
492 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
493 * functions because they create a new navigation root. Implementations also exist for PathExpression and
494 * FilterExpression because they have subexpressions that are evaluated in a different context from the
495 * calling expression.</p>
496 *
497 * @param pathMap the PathMap to which the expression should be added
498 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
499 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
500 * expression, and that represent possible results of this expression. For an expression that does
501 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
502 * expressions, it is the same as the input pathMapNode.
503 */
504
505 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
506 PathMap.PathMapNodeSet result = getBaseExpression().addToPathMap(pathMap, pathMapNodeSet);
507 if (result != null) {
508 TypeHierarchy th = getConfiguration().getTypeHierarchy();
509 ItemType operandItemType = getBaseExpression().getItemType();
510 if (th.relationship(NodeKindTest.ELEMENT, operandItemType) != TypeHierarchy.DISJOINT ||
511 th.relationship(NodeKindTest.DOCUMENT, operandItemType) != TypeHierarchy.DISJOINT) {
512 result.setAtomized();
513 }
514 }
515 return null;
516 }
517
518 /**
519 * Get an iterator that returns the result of atomizing the sequence delivered by the supplied
520 * iterator
521 *
522 * @param base the supplied iterator, the input to atomization
523 * @param oneToOne this can safely be set to true if it is known that all nodes in the base sequence will
524 * be untyped and that there will be no arrays in the base sequence; but it is always OK
525 * to set it to false.
526 * @return an iterator that returns atomic values, the result of the atomization
527 * @throws net.sf.saxon.trans.XPathException
528 * if a dynamic evaluation error occurs
529 */
530
531 public static SequenceIterator<? extends AtomicValue> getAtomizingIterator(SequenceIterator base, boolean oneToOne) throws XPathException {
532 int properties = base.getProperties();
533 if ((properties & SequenceIterator.LAST_POSITION_FINDER) != 0) {
534 int count = ((LastPositionFinder) base).getLength();
535 if (count == 0) {
536 return EmptyIterator.emptyIterator();
537 } else if (count == 1) {
538 Item first = base.next();
539 return first.atomize().iterate();
540 }
541 } else if ((properties & SequenceIterator.ATOMIZING) != 0) {
542 return new AxisAtomizingIterator((AtomizedValueIterator)base);
543 }
544 if (oneToOne) {
545 return new UntypedAtomizingIterator(base);
546 } else {
547 return new AtomizingIterator(base);
548 }
549 }
550
551 public static AtomicSequence atomize(Sequence<?> sequence) throws XPathException {
552 if (sequence instanceof AtomicSequence) {
553 return (AtomicSequence)sequence;
554 } else if (sequence instanceof EmptySequence) {
555 return EmptyAtomicSequence.getInstance();
556 } else {
557 SequenceIterator<? extends AtomicValue> iter = getAtomizingIterator(sequence.iterate(), false);
558 return new AtomicArray(iter);
559 }
560 }
561
562 /**
563 * Diagnostic print of expression structure. The abstract expression tree
564 * is written to the supplied output destination.
565 */
566
567 public String getExpressionName() {
568 return "data";
569 }
570
571 /**
572 * The toString() method for an expression attempts to give a representation of the expression
573 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
574 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
575 */
576 @Override
577 public String toString() {
578 return "data(" + getBaseExpression().toString() + ")";
579 }
580
581 @Override
582 public String toShortString() {
583 return getBaseExpression().toShortString();
584 }
585
586
587 }
588