Debian Codegraph @

net/sf/saxon/expr/instruct/CopyOf.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.*;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.lib.ParseOptions;
17 import net.sf.saxon.lib.Validation;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.AnyNodeTest;
20 import net.sf.saxon.pattern.ContentTypeTest;
21 import net.sf.saxon.pattern.NodeKindTest;
22 import net.sf.saxon.pattern.NodeTest;
23 import net.sf.saxon.trace.ExpressionPresenter;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.tiny.TinyBuilder;
26 import net.sf.saxon.tree.tiny.TinyNodeImpl;
27 import net.sf.saxon.tree.util.FastStringBuffer;
28 import net.sf.saxon.tree.wrapper.VirtualCopy;
29 import net.sf.saxon.tree.wrapper.VirtualUntypedCopy;
30 import net.sf.saxon.type.*;
31 import net.sf.saxon.value.SequenceType;
32
33 import java.net.URI;
34 import java.net.URISyntaxException;
35
36
37 /**
38 * An xsl:copy-of element in the stylesheet.
39 */
40
41 public class CopyOf extends Instruction implements ValidatingInstruction {
42
43 private Operand selectOp;
44 private boolean copyNamespaces;
45 private boolean copyAccumulators;
46 private int validation;
47 private SchemaType schemaType;
48 private boolean requireDocumentOrElement = false;
49 private boolean rejectDuplicateAttributes;
50 //private boolean readOnce = false;
51 private boolean validating;
52 private boolean copyLineNumbers = false;
53 private boolean copyForUpdate = false;
54 private boolean isSchemaAware = true;
55
56 /**
57 * Create an xsl:copy-of instruction (also used in XQuery for implicit copying)
58 *
59 * @param select expression that selects the nodes to be copied
60 * @param copyNamespaces true if namespaces are to be copied
61 * @param validation validation mode for the result tree
62 * @param schemaType schema type for validating the result tree
63 * @param rejectDuplicateAttributes true if duplicate attributes are to be rejected (XQuery). False
64 * if duplicates are handled by discarding all but the first (XSLT).
65 */
66
67 public CopyOf(Expression select,
68 boolean copyNamespaces,
69 int validation,
70 SchemaType schemaType,
71 boolean rejectDuplicateAttributes) {
72 selectOp = new Operand(this, select, OperandRole.SINGLE_ATOMIC);
73 this.copyNamespaces = copyNamespaces;
74 this.validation = validation;
75 this.schemaType = schemaType;
76 validating = schemaType != null || validation != Validation.PRESERVE;
77 this.rejectDuplicateAttributes = rejectDuplicateAttributes;
78 }
79
80 public Expression getSelect() {
81 return selectOp.getChildExpression();
82 }
83
84 /**
85 * Set the select expression
86 *
87 * @param select the new select expression
88 */
89
90 public void setSelect(Expression select) {
91 selectOp.setChildExpression(select);
92 }
93
94 @Override
95 public Iterable<Operand> operands() {
96 return selectOp;
97 }
98
99 /**
100 * Get the validation mode
101 *
102 * @return the validation mode
103 */
104
105 public int getValidationAction() {
106 return validation;
107 }
108
109 /**
110 * Test if the instruction is doing validation
111 *
112 * @return true if it is
113 */
114
115 public boolean isValidating() {
116 return validating;
117 }
118
119 /**
120 * Get the schema type to be used for validation
121 *
122 * @return the schema type, or null if not validating against a type
123 */
124
125 public SchemaType getSchemaType() {
126 return schemaType;
127 }
128
129 /**
130 * Set the "is schema aware" property
131 *
132 * @param schemaAware true if schema awareness is enabled
133 */
134
135 public void setSchemaAware(boolean schemaAware) {
136 this.isSchemaAware = schemaAware;
137 }
138
139 /**
140 * Set whether line numbers are to be copied from the source to the result.
141 * Default is false.
142 *
143 * @param copy true if line numbers are to be copied
144 */
145
146 public void setCopyLineNumbers(boolean copy) {
147 copyLineNumbers = copy;
148 }
149
150 /**
151 * Determine whether this instruction creates new nodes.
152 * The result depends on the type of the select expression.
153 */
154
155 public final boolean mayCreateNewNodes() {
156 return !getSelect().getItemType().isPlainType();
157 }
158
159 /**
160 * Get the name of this instruction, for diagnostics and tracing
161 */
162
163 public int getInstructionNameCode() {
164 return StandardNames.XSL_COPY_OF;
165 }
166
167 /**
168 * For XQuery, the operand (select) must be a single element or document node.
169 *
170 * @param requireDocumentOrElement true if the argument must be a single element or document node
171 */
172 public void setRequireDocumentOrElement(boolean requireDocumentOrElement) {
173 this.requireDocumentOrElement = requireDocumentOrElement;
174 }
175
176 /**
177 * Test whether this expression requires a document or element node
178 *
179 * @return true if this expression requires the value of the argument to be a document or element node,
180 * false if there is no such requirement
181 */
182
183 public boolean isDocumentOrElementRequired() {
184 return requireDocumentOrElement;
185 }
186
187 /**
188 * Set whether this instruction is creating a copy for the purpose of updating (XQuery transform expression)
189 *
190 * @param forUpdate true if this copy is being created to support an update
191 */
192
193 public void setCopyForUpdate(boolean forUpdate) {
194 copyForUpdate = forUpdate;
195 }
196
197 /**
198 * Ask whether this instruction is creating a copy for the purpose of updating (XQuery transform expression)
199 *
200 * @return true if this copy is being created to support an update
201 */
202
203 public boolean isCopyForUpdate() {
204 return copyForUpdate;
205 }
206
207 /**
208 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
209 * This method indicates which of these methods is provided. This implementation provides both iterate() and
210 * process() methods natively.
211 */
212
213 public int getImplementationMethod() {
214 return ITERATE_METHOD | PROCESS_METHOD | WATCH_METHOD;
215 }
216
217 /**
218 * Ask whether namespaces are to be copied or not
219 *
220 * @return true if namespaces are to be copied (the default)
221 */
222
223 public boolean isCopyNamespaces() {
224 return copyNamespaces;
225 }
226
227 /**
228 * Say whether accumulator values should be copied from the source document
229 * @param copy true if values should be copied
230 */
231
232 public void setCopyAccumulators(boolean copy) {
233 copyAccumulators = copy;
234 }
235
236 /**
237 * Ask whether accumulator values should be copied from the source document
238 *
239 * @return true if values should be copied
240 */
241
242 public boolean isCopyAccumulators() {
243 return copyAccumulators;
244 }
245
246
247 /**
248 * Copy an expression. This makes a deep copy.
249 *
250 * @param rebindings information about variables whose bindings need to be replaced
251 * @return the copy of the original expression
252 */
253
254 /*@NotNull*/
255 public Expression copy(RebindingMap rebindings) {
256 CopyOf c = new CopyOf(getSelect().copy(rebindings), copyNamespaces, validation, schemaType, rejectDuplicateAttributes);
257 ExpressionTool.copyLocationInfo(this, c);
258 c.setCopyForUpdate(copyForUpdate);
259 c.setCopyLineNumbers(copyLineNumbers);
260 c.isSchemaAware = isSchemaAware;
261 c.setCopyAccumulators(copyAccumulators);
262 return c;
263 }
264
265 /*@NotNull*/
266 public ItemType getItemType() {
267 ItemType in = getSelect().getItemType();
268 if (!isSchemaAware) {
269 return in;
270 }
271 Configuration config = getConfiguration();
272 if (schemaType != null) {
273 TypeHierarchy th = config.getTypeHierarchy();
274 int e = th.relationship(in, NodeKindTest.ELEMENT);
275 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
276 return new ContentTypeTest(Type.ELEMENT, schemaType, config, false);
277 }
278 int a = th.relationship(in, NodeKindTest.ATTRIBUTE);
279 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
280 return new ContentTypeTest(Type.ATTRIBUTE, schemaType, config, false);
281 }
282 } else {
283 switch (validation) {
284 case Validation.PRESERVE:
285 return in;
286 case Validation.STRIP: {
287 TypeHierarchy th = config.getTypeHierarchy();
288 int e = th.relationship(in, NodeKindTest.ELEMENT);
289 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
290 return new ContentTypeTest(Type.ELEMENT, Untyped.getInstance(), config, false);
291 }
292 int a = th.relationship(in, NodeKindTest.ATTRIBUTE);
293 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
294 return new ContentTypeTest(Type.ATTRIBUTE, BuiltInAtomicType.UNTYPED_ATOMIC, config, false);
295 }
296 if (e != TypeHierarchy.DISJOINT || a != TypeHierarchy.DISJOINT) {
297 // it might be an element or attribute
298 return in instanceof NodeTest ? AnyNodeTest.getInstance() : AnyItemType.getInstance();
299 } else {
300 // it can't be an element or attribute, so stripping type annotations can't affect it
301 return in;
302 }
303 }
304 case Validation.STRICT:
305 case Validation.LAX:
306 if (in instanceof NodeTest) {
307 TypeHierarchy th = config.getTypeHierarchy();
308 int fp = ((NodeTest) in).getFingerprint();
309 if (fp != -1) {
310 int e = th.relationship(in, NodeKindTest.ELEMENT);
311 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
312 SchemaDeclaration elem = config.getElementDeclaration(fp);
313 if (elem != null) {
314 try {
315 return new ContentTypeTest(Type.ELEMENT, elem.getType(), config, false);
316 } catch (MissingComponentException e1) {
317 return new ContentTypeTest(Type.ELEMENT, AnyType.getInstance(), config, false);
318 }
319 } else {
320 // Although there is no element declaration now, there might be one at run-time
321 return new ContentTypeTest(Type.ELEMENT, AnyType.getInstance(), config, false);
322 }
323 }
324 int a = th.relationship(in, NodeKindTest.ATTRIBUTE);
325 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
326 SchemaDeclaration attr = config.getElementDeclaration(fp);
327 if (attr != null) {
328 try {
329 return new ContentTypeTest(Type.ATTRIBUTE, attr.getType(), config, false);
330 } catch (MissingComponentException e1) {
331 return new ContentTypeTest(Type.ATTRIBUTE, AnySimpleType.getInstance(), config, false);
332 }
333 } else {
334 // Although there is no attribute declaration now, there might be one at run-time
335 return new ContentTypeTest(Type.ATTRIBUTE, AnySimpleType.getInstance(), config, false);
336 }
337 }
338 } else {
339 int e = th.relationship(in, NodeKindTest.ELEMENT);
340 if (e == TypeHierarchy.SAME_TYPE || e == TypeHierarchy.SUBSUMED_BY) {
341 return NodeKindTest.ELEMENT;
342 }
343 int a = th.relationship(in, NodeKindTest.ATTRIBUTE);
344 if (a == TypeHierarchy.SAME_TYPE || a == TypeHierarchy.SUBSUMED_BY) {
345 return NodeKindTest.ATTRIBUTE;
346 }
347 }
348 return AnyNodeTest.getInstance();
349 } else if (in instanceof AtomicType) {
350 return in;
351 } else {
352 return AnyItemType.getInstance();
353 }
354 }
355 }
356 return getSelect().getItemType();
357 }
358
359 public int getCardinality() {
360 return getSelect().getCardinality();
361 }
362
363 public int getDependencies() {
364 return getSelect().getDependencies();
365 }
366
367 /*@NotNull*/
368 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
369 typeCheckChildren(visitor, contextInfo);
370 if (isDocumentOrElementRequired()) {
371 // this implies the expression is actually an XQuery validate{} expression, hence the error messages
372 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.TYPE_OP, "validate", 0);
373 role.setErrorCode("XQTY0030");
374 Configuration config = visitor.getConfiguration();
375 setSelect(config.getTypeChecker(false).staticTypeCheck(
376 getSelect(), SequenceType.SINGLE_NODE, role, visitor));
377
378 TypeHierarchy th = config.getTypeHierarchy();
379 ItemType t = getSelect().getItemType();
380 if (th.isSubType(t, NodeKindTest.ATTRIBUTE)) {
381 throw new XPathException("validate{} expression cannot be applied to an attribute", "XQTY0030");
382 }
383 if (th.isSubType(t, NodeKindTest.TEXT)) {
384 throw new XPathException("validate{} expression cannot be applied to a text node", "XQTY0030");
385 }
386 if (th.isSubType(t, NodeKindTest.COMMENT)) {
387 throw new XPathException("validate{} expression cannot be applied to a comment node", "XQTY0030");
388 }
389 if (th.isSubType(t, NodeKindTest.PROCESSING_INSTRUCTION)) {
390 throw new XPathException("validate{} expression cannot be applied to a processing instruction node", "XQTY0030");
391 }
392 if (th.isSubType(t, NodeKindTest.NAMESPACE)) {
393 throw new XPathException("validate{} expression cannot be applied to a namespace node", "XQTY0030");
394 }
395 }
396 return this;
397 }
398
399 /*@NotNull*/
400 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
401 selectOp.optimize(visitor, contextItemType);
402 if (Literal.isEmptySequence(getSelect())) {
403 return getSelect();
404 }
405 adoptChildExpression(getSelect());
406 if (getSelect().getItemType().isPlainType()) {
407 return getSelect();
408 }
409 return this;
410 }
411
412 /**
413 * Diagnostic print of expression structure. The abstract expression tree
414 * is written to the supplied output destination.
415 */
416
417 public void export(ExpressionPresenter out) throws XPathException {
418 out.startElement("copyOf", this);
419 if (validation != Validation.SKIP) {
420 out.emitAttribute("validation", Validation.toString(validation));
421 }
422 if (schemaType != null) {
423 out.emitAttribute("type", schemaType.getStructuredQName());
424 }
425
426 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C16);
427 if (requireDocumentOrElement) {
428 fsb.append('p');
429 }
430 if (rejectDuplicateAttributes) {
431 fsb.append('a');
432 }
433 if (validating) {
434 fsb.append('v');
435 }
436 if (copyLineNumbers) {
437 fsb.append('l');
438 }
439 if (copyForUpdate) {
440 fsb.append('u');
441 }
442 if (isSchemaAware) {
443 fsb.append('s');
444 }
445 if (copyNamespaces) {
446 fsb.append('c');
447 }
448 if (copyAccumulators) {
449 fsb.append('m');
450 }
451 if (!fsb.isEmpty()) {
452 out.emitAttribute("flags", fsb.toString());
453 }
454 getSelect().export(out);
455 out.endElement();
456 }
457
458 /**
459 * Get the (partial) name of a class that supports streaming of this kind of expression
460 *
461 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
462 * or null if there is no such class
463 */
464 @Override
465 public String getStreamerName() {
466 return "CopyOf";
467 }
468
469 /**
470 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
471 * by an expression in a source tree.
472 * <p>The default implementation of this method assumes that an expression does no navigation other than
473 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
474 * same context as the containing expression. The method must be overridden for any expression
475 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
476 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
477 * functions because they create a new navigation root. Implementations also exist for PathExpression and
478 * FilterExpression because they have subexpressions that are evaluated in a different context from the
479 * calling expression.</p>
480 *
481 * @param pathMap the PathMap to which the expression should be added
482 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
483 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
484 * expression, and that represent possible results of this expression. For an expression that does
485 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
486 * expressions, it is the same as the input pathMapNode.
487 */
488
489 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
490 PathMap.PathMapNodeSet result = super.addToPathMap(pathMap, pathMapNodeSet);
491 result.setReturnable(false);
492 TypeHierarchy th = getConfiguration().getTypeHierarchy();
493 ItemType type = getItemType();
494 if (th.relationship(type, NodeKindTest.ELEMENT) != TypeHierarchy.DISJOINT ||
495 th.relationship(type, NodeKindTest.DOCUMENT) != TypeHierarchy.DISJOINT) {
496 result.addDescendants();
497 }
498 return new PathMap.PathMapNodeSet(pathMap.makeNewRoot(this));
499 }
500
501 /**
502 * Process this xsl:copy-of instruction
503 *
504 * @param context the dynamic context for the transformation
505 * @return null - this implementation of the method never returns a TailCall
506 */
507
508 public TailCall processLeavingTail(XPathContext context) throws XPathException {
509
510 Receiver out = context.getReceiver();
511
512 if (copyAccumulators) {
513 // Try to create a virtual copy if we can. This is cheaper
514 if (mustPush()) {
515 // This typically happens with the combination copy-accumulators=yes, validation=strict
516 // Test case accumulators-070
517 // We have to create a physical copy because of the validation requirement, but this makes
518 // it difficult to copy the accumulator values.
519 getSelect().iterate(context).forEachOrFail(item -> {
520 if (item instanceof NodeInfo) {
521 TinyBuilder builder = new TinyBuilder(out.getPipelineConfiguration());
522 builder.open();
523 copyOneNode(context, new TreeReceiver(builder), (NodeInfo) item, CopyOptions.ALL_NAMESPACES);
524 builder.close();
525 TinyNodeImpl copy = (TinyNodeImpl) builder.getCurrentRoot();
526 copy.getTree().setCopiedFrom((NodeInfo) item);
527 out.append(copy);
528 } else {
529 out.append(item);
530 }
531 });
532 } else {
533 // Use the iterate() method to create a virtual copy.
534 iterate(context).forEachOrFail(out::append);
535 }
536 } else {
537
538 int copyOptions = CopyOptions.TYPE_ANNOTATIONS
539 | (copyNamespaces ? CopyOptions.ALL_NAMESPACES : 0)
540 | (copyForUpdate ? CopyOptions.FOR_UPDATE : 0);
541
542 getSelect().iterate(context).forEachOrFail(item -> {
543 if (item instanceof NodeInfo) {
544 copyOneNode(context, out, (NodeInfo) item, copyOptions);
545 } else {
546 out.append(item, getLocation(), ReceiverOptions.ALL_NAMESPACES);
547 }
548 });
549
550 }
551 return null;
552 }
553
554 private void copyOneNode(XPathContext context, Receiver out, NodeInfo item, int copyOptions) throws XPathException {
555 Controller controller = context.getController();
556 boolean copyBaseURI = out.getSystemId() == null;
557 int kind = item.getNodeKind();
558 if (requireDocumentOrElement &&
559 !(kind == Type.ELEMENT || kind == Type.DOCUMENT)) {
560 XPathException e = new XPathException("Operand of validate expression must be a document or element node");
561 e.setXPathContext(context);
562 e.setErrorCode("XQTY0030");
563 throw e;
564 }
565 final Configuration config = controller.getConfiguration();
566 switch (kind) {
567
568 case Type.ELEMENT: {
569 Receiver eval = out;
570 if (validating) {
571 ParseOptions options = new ParseOptions();
572 options.setSchemaValidationMode(validation);
573 SchemaType type = schemaType;
574 if (type == null && (validation == Validation.STRICT || validation == Validation.LAX)) {
575 // Bug 3062
576 String xsitype = item.getAttributeValue(NamespaceConstant.SCHEMA_INSTANCE, "type");
577 if (xsitype != null) {
578 StructuredQName typeName;
579 try {
580 typeName = StructuredQName.fromLexicalQName(
581 xsitype,
582 true,
583 false,
584 new InscopeNamespaceResolver(item));
585 } catch (XPathException e) {
586 throw new XPathException("Invalid QName in xsi:type attribute of element being validated: "
587 + xsitype + ". " + e.getMessage(), "XTTE1510");
588 }
589 type = config.getSchemaType(typeName);
590 if (type == null) {
591 throw new XPathException("Unknown xsi:type in element being validated: " + xsitype, "XTTE1510");
592 }
593 }
594 }
595 options.setTopLevelType(type);
596 options.setTopLevelElement(NameOfNode.makeName(item).getStructuredQName());
597 options.setErrorListener(context.getErrorListener());
598 config.prepareValidationReporting(context, options);
599 eval = config.getElementValidator(out, options, getLocation());
600 }
601 if (copyBaseURI) {
602 eval.setSystemId(computeNewBaseUri(item, getStaticBaseURIString()));
603 }
604
605 Receiver savedReceiver = null;
606 PipelineConfiguration savedPipe = null;
607 if (copyLineNumbers) {
608 savedReceiver = eval;
609 PipelineConfiguration pipe = eval.getPipelineConfiguration();
610 savedPipe = new PipelineConfiguration(pipe);
611 LocationCopier copier = new LocationCopier(false);
612 pipe.setComponent(CopyInformee.class.getName(), copier);
613 }
614 item.copy(eval, copyOptions, getLocation());
615 if (copyLineNumbers) {
616 eval = savedReceiver;
617 assert eval != null;
618 eval.setPipelineConfiguration(savedPipe);
619 }
620 break;
621 }
622 case Type.ATTRIBUTE:
623 if (schemaType != null && schemaType.isComplexType()) {
624 XPathException e = new XPathException("When copying an attribute with schema validation, the requested type must not be a complex type");
625 e.setLocation(getLocation());
626 e.setXPathContext(context);
627 e.setErrorCode("XTTE1535");
628 throw dynamicError(getLocation(), e, context);
629 }
630 try {
631 copyAttribute(item, (SimpleType) schemaType, validation, this, context, rejectDuplicateAttributes);
632 } catch (NoOpenStartTagException err) {
633 XPathException e = new XPathException(err.getMessage());
634 e.setLocation(getLocation());
635 e.setXPathContext(context);
636 e.setErrorCodeQName(err.getErrorCodeQName());
637 throw dynamicError(getLocation(), e, context);
638 }
639 break;
640 case Type.TEXT:
641 out.characters(item.getStringValueCS(), getLocation(), 0);
642 break;
643
644 case Type.PROCESSING_INSTRUCTION:
645 if (copyBaseURI) {
646 out.setSystemId(item.getBaseURI());
647 }
648 out.processingInstruction(item.getDisplayName(), item.getStringValueCS(), getLocation(), 0);
649 break;
650
651 case Type.COMMENT:
652 out.comment(item.getStringValueCS(), getLocation(), 0);
653 break;
654
655 case Type.NAMESPACE:
656 try {
657 item.copy(out, 0, getLocation());
658 } catch (NoOpenStartTagException err) {
659 XPathException e = new XPathException(err.getMessage());
660 e.setXPathContext(context);
661 e.setErrorCodeQName(err.getErrorCodeQName());
662 throw dynamicError(getLocation(), e, context);
663 }
664 break;
665
666 case Type.DOCUMENT: {
667 ParseOptions options = new ParseOptions();
668 options.setSchemaValidationMode(validation);
669 options.setSpaceStrippingRule(NoElementsSpaceStrippingRule.getInstance());
670 options.setTopLevelType(schemaType);
671 options.setErrorListener(context.getErrorListener());
672 config.prepareValidationReporting(context, options);
673 Receiver val = config.getDocumentValidator(out, item.getBaseURI(), options, getLocation());
674 //val.setPipelineConfiguration(out.getPipelineConfiguration());
675 if (copyBaseURI) {
676 val.setSystemId(item.getBaseURI());
677 }
678 Receiver savedReceiver = null;
679 PipelineConfiguration savedPipe = null;
680 if (copyLineNumbers) {
681 savedReceiver = val;
682 savedPipe = new PipelineConfiguration(val.getPipelineConfiguration());
683 LocationCopier copier = new LocationCopier(true);
684 val.getPipelineConfiguration().setComponent(CopyInformee.class.getName(), copier);
685
686 }
687 item.copy(val, copyOptions, getLocation());
688 if (copyLineNumbers) {
689 val = savedReceiver;
690 assert val != null;
691 val.setPipelineConfiguration(savedPipe);
692 }
693 // if (val != out) {
694 // See bug 2403
695 // val.close(); // needed to flush out unresolved IDREF values when validating: test copy-5021
696 // }
697 break;
698 }
699 default:
700 throw new IllegalArgumentException("Unknown node kind " + item.getNodeKind());
701 }
702 }
703
704 public static String computeNewBaseUri(NodeInfo source, String staticBaseURI) {
705 // These rules are the rules for xsl:copy-of instruction in XSLT. The same code is used to support the
706 // validate{} expression in XQuery. XQuery says nothing about the base URI of a node that results
707 // from a validate{} expression, so until it does, we might as well use the same logic.
708 String newBaseUri;
709 String xmlBase = source.getAttributeValue(NamespaceConstant.XML, "base");
710 if (xmlBase != null) {
711 try {
712 URI xmlBaseUri = new URI(xmlBase);
713 if (xmlBaseUri.isAbsolute()) {
714 newBaseUri = xmlBase;
715 } else if (staticBaseURI != null) {
716 URI sbu = new URI(staticBaseURI);
717 URI abs = sbu.resolve(xmlBaseUri);
718 newBaseUri = abs.toString();
719 } else {
720 newBaseUri = source.getBaseURI();
721 }
722 } catch (URISyntaxException err) {
723 newBaseUri = source.getBaseURI();
724 }
725 } else {
726 newBaseUri = source.getBaseURI();
727 }
728 return newBaseUri;
729 }
730
731 /**
732 * Method shared by xsl:copy and xsl:copy-of to copy an attribute node
733 *
734 * @param source the node to be copied
735 * @param schemaType the simple type against which the value is to be validated, if any
736 * @param validation one of preserve, strip, strict, lax
737 * @param instruction the calling instruction, used for diagnostics
738 * @param context the dynamic context
739 * @param rejectDuplicates true if duplicate attributes with the same name are disallowed (XQuery)
740 * @throws XPathException if a failure occurs
741 */
742
743 static void copyAttribute(NodeInfo source,
744 SimpleType schemaType,
745 int validation,
746 Instruction instruction,
747 XPathContext context,
748 boolean rejectDuplicates)
749 throws XPathException {
750 int opt = 0;
751 if (rejectDuplicates) {
752 opt |= ReceiverOptions.REJECT_DUPLICATES;
753 }
754 CharSequence value = source.getStringValueCS();
755 SimpleType annotation = validateAttribute(source, schemaType, validation, context);
756 try {
757 context.getReceiver().attribute(NameOfNode.makeName(source), annotation, value, instruction.getLocation(), opt);
758 } catch (XPathException e) {
759 e.maybeSetContext(context);
760 e.maybeSetLocation(instruction.getLocation());
761 if (instruction.getPackageData().getHostLanguage() == Configuration.XQUERY && e.getErrorCodeLocalPart().equals("XTTE0950")) {
762 e.setErrorCode("XQTY0086");
763 }
764 throw e;
765 }
766 }
767
768 /**
769 * Validate an attribute node and return the type annotation to be used
770 *
771 * @param source the node to be copied
772 * @param schemaType the simple type against which the value is to be validated, if any
773 * @param validation one of preserve, strip, strict, lax
774 * @param context the dynamic context
775 * @return the type annotation to be used for the attribute
776 * @throws XPathException if the attribute is not valid
777 */
778
779
780 public static SimpleType validateAttribute(
781 NodeInfo source, SimpleType schemaType, int validation, XPathContext context) throws XPathException {
782 CharSequence value = source.getStringValueCS();
783 SimpleType annotation = BuiltInAtomicType.UNTYPED_ATOMIC;
784 if (schemaType != null) {
785 if (schemaType.isNamespaceSensitive()) {
786 XPathException err = new XPathException("Cannot create a parentless attribute whose " +
787 "type is namespace-sensitive (such as xs:QName)");
788 err.setErrorCode("XTTE1545");
789 throw err;
790 }
791 ValidationFailure err = schemaType.validateContent(
792 value, DummyNamespaceResolver.getInstance(), context.getConfiguration().getConversionRules());
793 if (err != null) {
794 err.setMessage("Attribute being copied does not match the required type. " +
795 err.getMessage());
796 err.setErrorCode("XTTE1510");
797 throw err.makeException();
798 }
799 annotation = schemaType;
800 } else if (validation == Validation.STRICT || validation == Validation.LAX) {
801 try {
802 annotation = context.getConfiguration().validateAttribute(NameOfNode.makeName(source).getStructuredQName(), value, validation);
803 } catch (ValidationException e) {
804 XPathException err = XPathException.makeXPathException(e);
805 err.setErrorCodeQName(e.getErrorCodeQName());
806 err.setIsTypeError(true);
807 throw err;
808 }
809
810 } else if (validation == Validation.PRESERVE) {
811 annotation = (SimpleType) source.getSchemaType();
812 if (!annotation.equals(BuiltInAtomicType.UNTYPED_ATOMIC) && annotation.isNamespaceSensitive()) {
813 XPathException err = new XPathException("Cannot preserve type annotation when copying an attribute with namespace-sensitive content");
814 err.setErrorCode(context.getController().getExecutable().getHostLanguage() == Configuration.XSLT ? "XTTE0950" : "XQTY0086");
815 err.setIsTypeError(true);
816 throw err;
817 }
818 }
819 return annotation;
820 }
821
822 private boolean mustPush() {
823 return schemaType != null || validation == Validation.LAX || validation == Validation.STRICT ||
824 /*!copyNamespaces ||*/ copyForUpdate;
825 }
826
827 /*@NotNull*/
828 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
829 final Controller controller = context.getController();
830 assert controller != null;
831 if (schemaType == null /*&& copyNamespaces*/ && !copyForUpdate) {
832 if (validation == Validation.PRESERVE) {
833 // create a virtual copy of the underlying nodes
834 ItemMappingFunction<Item<?>, Item<?>> copier = item -> {
835 if (item instanceof NodeInfo) {
836 if (((NodeInfo) item).getTreeInfo().isTyped()) {
837 if (!copyNamespaces && ((NodeInfo) item).getNodeKind() == Type.ELEMENT) {
838 // A lot of extra work here just to check for error XTTE0950, but the conditions are rare
839 Sink sink = new Sink(controller.makePipelineConfiguration());
840 ((NodeInfo) item).copy(sink, CopyOptions.TYPE_ANNOTATIONS, getLocation());
841 }
842 if (((NodeInfo) item).getNodeKind() == Type.ATTRIBUTE &&
843 ((SimpleType) ((NodeInfo) item).getSchemaType()).isNamespaceSensitive()) {
844 throw new XPathException("Cannot copy an attribute with namespace-sensitive content except as part of its containing element", "XTTE0950");
845 }
846 }
847 VirtualCopy vc = VirtualCopy.makeVirtualCopy((NodeInfo) item);
848 vc.setDropNamespaces(!copyNamespaces);
849 vc.getTreeInfo().setCopyAccumulators(copyAccumulators);
850 if (((NodeInfo) item).getNodeKind() == Type.ELEMENT) {
851 vc.setSystemId(computeNewBaseUri((NodeInfo) item, getStaticBaseURIString()));
852 }
853 return vc;
854 } else {
855 return item;
856 }
857 };
858 return new ItemMappingIterator<>(getSelect().iterate(context), copier, true);
859 } else if (validation == Validation.STRIP) {
860 // create a virtual copy of the underlying nodes
861 ItemMappingFunction<Item<?>, Item<?>> copier = item -> {
862 if (!(item instanceof NodeInfo)) {
863 return item;
864 }
865 VirtualCopy vc = VirtualUntypedCopy.makeVirtualUntypedTree((NodeInfo) item, (NodeInfo) item);
866 vc.getTreeInfo().setCopyAccumulators(copyAccumulators);
867 vc.setDropNamespaces(!copyNamespaces);
868 if (((NodeInfo) item).getNodeKind() == Type.ELEMENT) {
869 vc.setSystemId(computeNewBaseUri((NodeInfo) item, getStaticBaseURIString()));
870 }
871 return vc;
872 };
873 return new ItemMappingIterator<>(getSelect().iterate(context), copier, true);
874 }
875 }
876 Receiver saved = context.getReceiver();
877 PipelineConfiguration pipe = controller.makePipelineConfiguration();
878 pipe.setXPathContext(context);
879 SequenceOutputter out = new SequenceOutputter(pipe);
880 if (copyForUpdate) {
881 out.setTreeModel(TreeModel.LINKED_TREE);
882 }
883 pipe.setHostLanguage(getPackageData().getHostLanguage());
884 context.setReceiver(out);
885 try {
886 process(context);
887 } catch (XPathException err) {
888 err.maybeSetLocation(getLocation());
889 err.maybeSetContext(context);
890 throw err;
891 }
892 context.setReceiver(saved);
893 return out.getSequence().iterate();
894 }
895
896
897 }
898