Debian Codegraph @

net/sf/saxon/expr/instruct/Copy.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.instruct;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.*;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
15 import net.sf.saxon.expr.parser.ExpressionTool;
16 import net.sf.saxon.expr.parser.ExpressionVisitor;
17 import net.sf.saxon.expr.parser.RebindingMap;
18 import net.sf.saxon.lib.ParseOptions;
19 import net.sf.saxon.lib.Validation;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.pattern.*;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.tree.util.NamespaceIterator;
25 import net.sf.saxon.type.*;
26 import net.sf.saxon.value.BooleanValue;
27 import net.sf.saxon.value.SequenceType;
28
29 import java.util.Iterator;
30
31
32 /**
33 * Handler for xsl:copy elements in stylesheet. This only handles copying of the context item. An xsl:copy
34 * with a select attribute is handled by wrapping the instruction in an xsl:for-each.
35 */
36
37 public class Copy extends ElementCreator {
38
39 private boolean copyNamespaces;
40 private ItemType selectItemType = AnyItemType.getInstance();
41 private ItemType resultItemType;
42
43 /**
44 * Create a shallow copy instruction
45 *
46 * param select selects the node (or other item) to be copied. Never null.
47 * param selectSpecified true if the select attribute of xsl:copy was specified explicitly (in which
48 * case the context for evaluating the body will change)
49 * @param copyNamespaces true if namespace nodes are to be copied when copying an element
50 * @param inheritNamespaces true if child elements are to inherit the namespace nodes of their parent
51 * @param schemaType the Schema type against which the content is to be validated
52 * @param validation the schema validation mode
53 */
54
55 public Copy(boolean copyNamespaces,
56 boolean inheritNamespaces,
57 SchemaType schemaType,
58 int validation) {
59 this.copyNamespaces = copyNamespaces;
60 this.inheritNamespacesToChildren = inheritNamespaces;
61 setValidationAction(validation, schemaType);
62 preservingTypes = schemaType == null && validation == Validation.PRESERVE;
63 }
64
65 /**
66 * Say whether namespace nodes are to be copied (in the case of an element)
67 * @param copy set to true if namespace nodes are to be copied
68 */
69
70 public void setCopyNamespaces(boolean copy) {
71 copyNamespaces = copy;
72 }
73
74 /**
75 * Ask whether namespace nodes are to be copied (in the case of an element)
76 *
77 * @return true if all in-scope namespaces are to be copied
78 */
79
80 public boolean isCopyNamespaces() {
81 return copyNamespaces;
82 }
83
84 /**
85 * Simplify an expression. This performs any static optimization (by rewriting the expression
86 * as a different expression). The default implementation does nothing.
87 *
88 *
89 *
90 * @throws net.sf.saxon.trans.XPathException
91 * if an error is discovered during expression rewriting
92 */
93
94 /*@NotNull*/
95 public Expression simplify() throws XPathException {
96 preservingTypes |= !getPackageData().isSchemaAware();
97 return super.simplify();
98 }
99
100
101 /*@NotNull*/
102 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
103
104 typeCheckChildren(visitor, contextInfo);
105
106 selectItemType = contextInfo.getItemType();
107
108 ItemType selectItemType = contextInfo.getItemType(); //select.getItemType();
109 if (selectItemType == ErrorType.getInstance()) {
110 XPathException err = new XPathException("No context item supplied for xsl:copy", "XTTE0945");
111 err.setIsTypeError(true);
112 err.setLocation(getLocation());
113 throw err;
114 }
115
116 if (selectItemType instanceof NodeTest) {
117 switch (selectItemType.getPrimitiveType()) {
118 // For elements and attributes, assume the type annotation will change
119 case Type.ELEMENT:
120 this.resultItemType = NodeKindTest.ELEMENT;
121 break;
122 case Type.DOCUMENT:
123 this.resultItemType = NodeKindTest.DOCUMENT;
124 break;
125 case Type.ATTRIBUTE:
126 case Type.TEXT:
127 case Type.COMMENT:
128 case Type.PROCESSING_INSTRUCTION:
129 case Type.NAMESPACE:
130 ContextItemExpression dot = new ContextItemExpression();
131 ExpressionTool.copyLocationInfo(this, dot);
132 CopyOf c = new CopyOf(dot, copyNamespaces, getValidationAction(), getSchemaType(), false);
133 ExpressionTool.copyLocationInfo(this, c);
134 return c.typeCheck(visitor, contextInfo);
135 default:
136 this.resultItemType = selectItemType;
137 }
138 } else {
139 this.resultItemType = selectItemType;
140 }
141
142 checkContentSequence(visitor.getStaticContext());
143 return this;
144 }
145
146 /**
147 * Copy an expression. This makes a deep copy.
148 *
149 * @return the copy of the original expression
150 * @param rebindings
151 */
152
153 /*@NotNull*/
154 public Expression copy(RebindingMap rebindings) {
155 Copy copy = new Copy(
156 copyNamespaces, inheritNamespacesToChildren, getSchemaType(), getValidationAction());
157 ExpressionTool.copyLocationInfo(this, copy);
158 copy.setContentExpression(getContentExpression().copy(rebindings));
159 copy.resultItemType = resultItemType;
160 return copy;
161 }
162
163 /**
164 * Determine which aspects of the context the expression depends on. The result is
165 * a bitwise-or'ed value composed from constants such as XPathContext.VARIABLES and
166 * XPathContext.CURRENT_NODE. The default implementation combines the intrinsic
167 * dependencies of this expression with the dependencies of the subexpressions,
168 * computed recursively. This is overridden for expressions such as FilterExpression
169 * where a subexpression's dependencies are not necessarily inherited by the parent
170 * expression.
171 *
172 * @return a set of bit-significant flags identifying the dependencies of
173 * the expression
174 */
175
176 public int getIntrinsicDependencies() {
177 return StaticProperty.DEPENDS_ON_CONTEXT_ITEM;
178 }
179
180 /**
181 * Get the name of this instruction for diagnostic and tracing purposes
182 */
183
184 public int getInstructionNameCode() {
185 return StandardNames.XSL_COPY;
186 }
187
188 /**
189 * Get the immediate sub-expressions of this expression, with information about the relationship
190 * of each expression to its parent expression. Default implementation
191 * returns a zero-length array, appropriate for an expression that has no
192 * sub-expressions.
193 *
194 * @return an iterator containing the sub-expressions of this expression
195 */
196 @Override
197 public Iterable<Operand> operands() {
198 return contentOp;
199 }
200
201
202 /**
203 * Get the item type of the result of this instruction.
204 *
205 * @return The context item type.
206 */
207
208 /*@NotNull*/
209 public ItemType getItemType() {
210 if (resultItemType != null) {
211 return resultItemType;
212 } else {
213 TypeHierarchy th = getConfiguration().getTypeHierarchy();
214 resultItemType = computeItemType(th);
215 return resultItemType;
216 }
217 }
218
219 private ItemType computeItemType(TypeHierarchy th) {
220 ItemType selectItemType = this.selectItemType; //select.getItemType();
221 if (!getPackageData().isSchemaAware()) {
222 return selectItemType;
223 }
224 if (selectItemType.getUType().overlaps(UType.ANY_ATOMIC.union(UType.FUNCTION))) {
225 return selectItemType;
226 }
227 // The rest of the code handles the complications of schema-awareness
228 Configuration config = th.getConfiguration();
229 if (getSchemaType() != null) {
230 int e = th.relationship(selectItemType, NodeKindTest.ELEMENT);
231 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
232 return new ContentTypeTest(Type.ELEMENT, getSchemaType(), config, false);
233 }
234 int a = th.relationship(selectItemType, NodeKindTest.ATTRIBUTE);
235 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
236 return new ContentTypeTest(Type.ATTRIBUTE, getSchemaType(), config, false);
237 }
238 return AnyNodeTest.getInstance();
239 } else {
240 switch (getValidationAction()) {
241 case Validation.PRESERVE:
242 return selectItemType;
243 case Validation.STRIP: {
244 int e = th.relationship(selectItemType, NodeKindTest.ELEMENT);
245 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
246 return new ContentTypeTest(Type.ELEMENT, Untyped.getInstance(), config, false);
247 }
248 int a = th.relationship(selectItemType, NodeKindTest.ATTRIBUTE);
249 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
250 return new ContentTypeTest(Type.ATTRIBUTE, BuiltInAtomicType.UNTYPED_ATOMIC, config, false);
251 }
252 if (e != TypeHierarchy.DISJOINT || a != TypeHierarchy.DISJOINT) {
253 // it might be an element or attribute
254 return AnyNodeTest.getInstance();
255 } else {
256 // it can't be an element or attribute, so stripping type annotations can't affect it
257 return selectItemType;
258 }
259 }
260 case Validation.STRICT:
261 case Validation.LAX:
262 if (selectItemType instanceof NodeTest) {
263 int fp = ((NodeTest) selectItemType).getFingerprint();
264 if (fp != -1) {
265 int e = th.relationship(selectItemType, NodeKindTest.ELEMENT);
266 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
267 SchemaDeclaration elem = config.getElementDeclaration(fp);
268 if (elem != null) {
269 try {
270 return new ContentTypeTest(Type.ELEMENT, elem.getType(), config, false);
271 } catch (MissingComponentException e1) {
272 return new ContentTypeTest(Type.ELEMENT, AnyType.getInstance(), config, false);
273 }
274 } else {
275 // No element declaration now, but there might be one at run-time
276 return new ContentTypeTest(Type.ELEMENT, AnyType.getInstance(), config, false);
277 }
278 }
279 int a = th.relationship(selectItemType, NodeKindTest.ATTRIBUTE);
280 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
281 SchemaDeclaration attr = config.getElementDeclaration(fp);
282 if (attr != null) {
283 try {
284 return new ContentTypeTest(Type.ATTRIBUTE, attr.getType(), config, false);
285 } catch (MissingComponentException e1) {
286 return new ContentTypeTest(Type.ATTRIBUTE, AnySimpleType.getInstance(), config, false);
287 }
288 } else {
289 // No attribute declaration now, but there might be one at run-time
290 return new ContentTypeTest(Type.ATTRIBUTE, AnySimpleType.getInstance(), config, false);
291 }
292 }
293 } else {
294 int e = th.relationship(selectItemType, NodeKindTest.ELEMENT);
295 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
296 return NodeKindTest.ELEMENT;
297 }
298 int a = th.relationship(selectItemType, NodeKindTest.ATTRIBUTE);
299 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
300 return NodeKindTest.ATTRIBUTE;
301 }
302 }
303 return AnyNodeTest.getInstance();
304 } else if (selectItemType instanceof AtomicType) {
305 return selectItemType;
306 } else {
307 return AnyItemType.getInstance();
308 }
309 default:
310 throw new IllegalStateException();
311 }
312 }
313 }
314
315 /*@NotNull*/
316 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
317 Expression exp = super.optimize(visitor, contextItemType);
318 if (exp == this) {
319 if (resultItemType == null) {
320 resultItemType = computeItemType(visitor.getConfiguration().getTypeHierarchy());
321 }
322 if (visitor.isOptimizeForStreaming()) {
323 UType type = contextItemType.getItemType().getUType();
324 if (!type.intersection(MultipleNodeKindTest.LEAF.getUType()).equals(UType.VOID)) {
325 Expression copyOf = new CopyOf(
326 new ContextItemExpression(), false, getValidationAction(), getSchemaType(), false);
327 NodeTest leafTest = new MultipleNodeKindTest(type.intersection(MultipleNodeKindTest.LEAF.getUType()));
328 Expression[] conditions = new Expression[]{
329 new InstanceOfExpression(
330 new ContextItemExpression(),
331 SequenceType.makeSequenceType(leafTest, StaticProperty.EXACTLY_ONE)),
332 Literal.makeLiteral(BooleanValue.TRUE, this)};
333 Expression[] actions = new Expression[]{copyOf, this};
334 Choose choose = new Choose(conditions, actions);
335 ExpressionTool.copyLocationInfo(this, choose);
336 return choose;
337 }
338 }
339 }
340 return exp;
341 }
342
343 /**
344 * Callback from ElementCreator when constructing an element
345 *
346 * @param context XPath dynamic evaluation context
347 * @param copiedNode the node being copied
348 * @return the namecode of the element to be constructed
349 * @throws XPathException
350 */
351
352 public NodeName getElementName(XPathContext context, NodeInfo copiedNode) throws XPathException {
353 return NameOfNode.makeName(copiedNode);
354 }
355
356 /**
357 * Get the base URI of a copied element node (the base URI is retained in the new copy)
358 *
359 * @param context XPath dynamic evaluation context
360 * @param copiedNode the node being copied (for xsl:copy), otherwise null
361 * @return the base URI
362 */
363
364 public String getNewBaseURI(XPathContext context, NodeInfo copiedNode) {
365 return copiedNode.getBaseURI();
366 }
367
368 /**
369 * Callback to output namespace nodes for the new element.
370 *
371 * @param context The execution context
372 * @param receiver the Receiver where the namespace nodes are to be written
373 * @param nodeName the element name
374 * @param copiedNode the node being copied (for xsl:copy), otherwise null
375 * @throws XPathException
376 */
377
378 public void outputNamespaceNodes(XPathContext context, Receiver receiver, NodeName nodeName, NodeInfo copiedNode)
379 throws XPathException {
380 if (copyNamespaces) {
381 NamespaceIterator.sendNamespaces(copiedNode, receiver);
382 } else {
383 // Always output the namespace of the element name itself
384 receiver.namespace(nodeName.getNamespaceBinding(), 0);
385 }
386 }
387
388 /**
389 * Callback to get a list of the intrinsic namespaces that need to be generated for the element.
390 * The result is an array of namespace codes, the codes either occupy the whole array or are
391 * terminated by a -1 entry. A result of null is equivalent to a zero-length array.
392 */
393
394 public NamespaceBinding[] getActiveNamespaces() throws XPathException {
395 if (copyNamespaces) {
396 // we should have disabled lazy construction, so this shouldn't be called.
397 throw new UnsupportedOperationException();
398 } else {
399 return null;
400 }
401 }
402
403
404 public TailCall processLeavingTail(XPathContext context) throws XPathException {
405 Controller controller = context.getController();
406 Receiver out = context.getReceiver();
407 Item item = context.getContextItem();//select.evaluateItem(context);
408 if (item == null) {
409 return null;
410 }
411
412 if (!(item instanceof NodeInfo)) {
413 out.append(item, getLocation(), ReceiverOptions.ALL_NAMESPACES);
414 return null;
415 }
416 NodeInfo source = (NodeInfo) item;
417 //out.getPipelineConfiguration().setBaseURI(source.getBaseURI());
418
419 // Processing depends on the node kind.
420
421 switch (source.getNodeKind()) {
422
423 case Type.ELEMENT:
424 // use the generic code for creating new elements
425 return super.processLeavingTail(context, (NodeInfo) item);
426
427 case Type.ATTRIBUTE:
428 if (getSchemaType() instanceof ComplexType) {
429 dynamicError("Cannot copy an attribute when the type requested for validation is a complex type", "XTTE1535", context);
430 }
431 try {
432 CopyOf.copyAttribute(source, (SimpleType) getSchemaType(), getValidationAction(), this, context, false);
433 } catch (NoOpenStartTagException err) {
434 err.setXPathContext(context);
435 throw dynamicError(getLocation(), err, context);
436 }
437 break;
438
439 case Type.TEXT:
440 CharSequence tval = source.getStringValueCS();
441 out.characters(tval, getLocation(), 0);
442 break;
443
444 case Type.PROCESSING_INSTRUCTION:
445 CharSequence pval = source.getStringValueCS();
446 out.processingInstruction(source.getDisplayName(), pval, getLocation(), 0);
447 break;
448
449 case Type.COMMENT:
450 CharSequence cval = source.getStringValueCS();
451 out.comment(cval, getLocation(), 0);
452 break;
453
454 case Type.NAMESPACE:
455 try {
456 source.copy(out, 0, getLocation());
457 } catch (NoOpenStartTagException err) {
458 XPathException e = new XPathException(err.getMessage());
459 e.setXPathContext(context);
460 e.setErrorCodeQName(err.getErrorCodeQName());
461 throw dynamicError(getLocation(), e, context);
462 }
463 break;
464
465 case Type.DOCUMENT:
466 Receiver saved = out;
467 boolean pop = false;
468 if (!preservingTypes) {
469 ParseOptions options = new ParseOptions(getValidationOptions());
470 options.setSpaceStrippingRule(NoElementsSpaceStrippingRule.getInstance());
471 controller.getConfiguration().prepareValidationReporting(context, options);
472 Receiver val = controller.getConfiguration().
473 getDocumentValidator(out, source.getBaseURI(), options, getLocation());
474 if (val != out) {
475 SequenceReceiver sr = new TreeReceiver(val);
476 sr.setPipelineConfiguration(out.getPipelineConfiguration());
477 context.setReceiver(sr);
478 pop = true;
479 out = sr;
480 }
481 }
482 if (out.getSystemId() == null) {
483 out.setSystemId(source.getBaseURI());
484 }
485 out.startDocument(0);
486 copyUnparsedEntities(source, out);
487 getContentExpression().process(context);
488 out.endDocument();
489 if (pop) {
490 context.setReceiver(saved);
491 }
492 break;
493
494 default:
495 throw new IllegalArgumentException("Unknown node kind " + source.getNodeKind());
496
497 }
498 return null;
499 }
500
501 public static void copyUnparsedEntities(NodeInfo source, Receiver out) throws XPathException {
502 Iterator<String> unparsedEntities = source.getTreeInfo().getUnparsedEntityNames();
503 while (unparsedEntities.hasNext()) {
504 String n = unparsedEntities.next();
505 String[] details = source.getTreeInfo().getUnparsedEntity(n);
506 out.setUnparsedEntity(n, details[0], details[1]);
507 }
508 }
509
510 /**
511 * Evaluate as an expression. We rely on the fact that when these instructions
512 * are generated by XQuery, there will always be a valueExpression to evaluate
513 * the content
514 */
515
516 public Item evaluateItem(XPathContext context) throws XPathException {
517 Controller controller = context.getController();
518 Receiver saved = context.getReceiver();
519 SequenceOutputter seq = controller.allocateSequenceOutputter(1);
520 seq.getPipelineConfiguration().setHostLanguage(getPackageData().getHostLanguage());
521 context.setReceiver(seq);
522 process(context);
523 seq.close();
524 context.setReceiver(saved);
525 Item item = seq.getFirstItem();
526 seq.reset();
527 return item;
528 }
529
530 /**
531 * Get the (partial) name of a class that supports streaming of this kind of expression
532 *
533 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
534 * or null if there is no such class
535 */
536 @Override
537 public String getStreamerName() {
538 return "Copy";
539 }
540
541 /**
542 * Diagnostic print of expression structure. The abstract expression tree
543 * is written to the supplied output destination.
544 */
545
546 public void export(ExpressionPresenter out) throws XPathException {
547 out.startElement("copy", this);
548 exportValidationAndType(out);
549 String flags = "";
550 if (copyNamespaces) {
551 flags = "c";
552 }
553 if (inheritNamespacesToChildren) {
554 flags += "i";
555 }
556 if (inheritNamespacesFromParent) {
557 flags += "n";
558 }
559 if (isLocal()) {
560 flags += "l";
561 }
562 out.emitAttribute("flags", flags);
563 out.setChildRole("content");
564 getContentExpression().export(out);
565 out.endElement();
566 }
567
568
569 }
570