Debian Codegraph @

net/sf/saxon/expr/instruct/ElementCreator.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.Controller;
11 import net.sf.saxon.event.*;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.lib.ParseOptions;
14 import net.sf.saxon.lib.Validation;
15 import net.sf.saxon.ma.arrays.ArrayItemType;
16 import net.sf.saxon.ma.map.MapType;
17 import net.sf.saxon.om.Item;
18 import net.sf.saxon.om.NamespaceBinding;
19 import net.sf.saxon.om.NodeInfo;
20 import net.sf.saxon.om.NodeName;
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.type.*;
26 import net.sf.saxon.value.Cardinality;
27
28
29 /**
30 * An instruction that creates an element node. There are two subtypes, FixedElement
31 * for use where the name is known statically, and Element where it is computed
32 * dynamically. To allow use in both XSLT and XQuery, the class acts both as an
33 * Instruction and as an Expression.
34 */
35
36 public abstract class ElementCreator extends ParentNodeConstructor {
37
38
39 /**
40 * The inheritNamespacesToChildren flag indicates that the namespace nodes on the element created by this instruction
41 * are to be inherited (copied) on the children of this element. That is, if this flag is false, the child
42 * elements must carry a namespace undeclaration for all the namespaces on the parent, unless they are
43 * redeclared in some way.
44 */
45
46 protected boolean inheritNamespacesToChildren = true;
47
48 /**
49 * The inheritNamespacesFromParent flag indicates that this element should inherit the namespaces of its
50 * parent element in the result tree. That is, if this flag is false, this element must carry a namespace
51 * undeclaration for all the namespaces on its parent, unless they are redeclared in some way.
52 */
53
54 protected boolean inheritNamespacesFromParent = true;
55
56 /**
57 * Construct an ElementCreator. Exists for the benefit of subclasses.
58 */
59
60 public ElementCreator() {
61 }
62
63 /**
64 * Get the item type of the value returned by this instruction
65 *
66 * @return the item type
67 */
68
69 /*@NotNull*/
70 public ItemType getItemType() {
71 return NodeKindTest.ELEMENT;
72 }
73
74 @Override
75 public int getCardinality() {
76 return StaticProperty.EXACTLY_ONE;
77 }
78
79 /**
80 * Say whether this element causes its children to inherit namespaces
81 *
82 * @param inherit true if namespaces are to be inherited by the children
83 */
84
85 public void setInheritNamespacesToChildren(boolean inherit) {
86 inheritNamespacesToChildren = inherit;
87 }
88
89 /**
90 * Ask whether the inherit namespaces flag is set
91 *
92 * @return true if namespaces constructed on this parent element are to be inherited by its children
93 */
94
95 public boolean isInheritNamespacesToChildren() {
96 return inheritNamespacesToChildren;
97 }
98
99 /**
100 * Say whether this element causes inherits namespaces from its parent. True except in XQuery where
101 * one direct element constructor forms the immediate content of another (see W3C bug 22334)
102 *
103 * @param inherit true if namespaces are to be inherited from the parent
104 */
105
106 public void setInheritNamespacesFromParent(boolean inherit) {
107 inheritNamespacesFromParent = inherit;
108 }
109
110 /**
111 * Ask whether this element inherits namespaces from its parent. True except in XQuery where
112 * one direct element constructor forms the immediate content of another (see W3C bug 22334)
113 *
114 * @return true if this child element inherits namespaces from its parent element
115 */
116
117 public boolean isInheritNamespacesFromParent() {
118 return inheritNamespacesFromParent;
119 }
120
121 /**
122 * Get the static properties of this expression (other than its type). The result is
123 * bit-signficant. These properties are used for optimizations. In general, if
124 * property bit is set, it is true, but if it is unset, the value is unknown.
125 *
126 * @return a set of flags indicating static properties of this expression
127 */
128
129 public int computeSpecialProperties() {
130 int p = super.computeSpecialProperties() |
131 StaticProperty.SINGLE_DOCUMENT_NODESET;
132 if (getValidationAction() == Validation.STRIP) {
133 p |= StaticProperty.ALL_NODES_UNTYPED;
134 }
135 return p;
136 }
137
138 /**
139 * Suppress validation on contained element constructors, on the grounds that the parent element
140 * is already performing validation. The default implementation does nothing.
141 */
142
143 public void suppressValidation(int parentValidationMode) {
144 if (getValidationAction() == parentValidationMode && getSchemaType() == null) {
145 // TODO: is this safe? e.g. if the child has validation=strict but matches a skip wildcard in the parent
146 setValidationAction(Validation.PRESERVE, null);
147 }
148 }
149
150 /**
151 * Check statically whether the content of the element creates attributes or namespaces
152 * after creating any child nodes
153 *
154 * @param env the static context
155 * @throws XPathException if the content is found to be incorrect
156 */
157
158 protected void checkContentSequence(StaticContext env) throws XPathException {
159 Operand[] components;
160 if (getContentExpression() instanceof Block) {
161 components = ((Block) getContentExpression()).getOperanda();
162 } else {
163 components = new Operand[]{contentOp};
164 }
165
166 boolean foundChild = false;
167 boolean foundPossibleChild = false;
168 for (Operand o : components) {
169 Expression component = o.getChildExpression();
170 ItemType it = component.getItemType();
171 if (it.isAtomicType()) {
172 foundChild = true;
173 } else if (it instanceof FunctionItemType && !(it instanceof ArrayItemType)) {
174 String which = it instanceof MapType ? "map" : "function";
175 XPathException de = new XPathException(
176 "Cannot add a " + which + " as a child of a constructed element");
177 de.setErrorCode(isXSLT() ? "XTDE0450" : "XQTY0105");
178 de.setLocator(component.getLocation());
179 de.setIsTypeError(true);
180 throw de;
181 } else if (it instanceof NodeTest) {
182 boolean maybeEmpty = Cardinality.allowsZero(component.getCardinality());
183 UType possibleNodeKinds = it.getUType();
184 if (possibleNodeKinds.overlaps(UType.TEXT)) {
185 // the text node might turn out to be zero-length. If that's a possibility,
186 // then we only issue a warning. Also, we need to completely ignore a known
187 // zero-length text node, which is included to prevent space-separation
188 // in an XQuery construct like <a>{@x}{@y}</b>
189 if (component instanceof ValueOf &&
190 ((ValueOf) component).getSelect() instanceof StringLiteral) {
191 String value = ((StringLiteral) ((ValueOf) component).getSelect()).getStringValue();
192 if (value.isEmpty()) {
193 // continue; // not an error
194 } else {
195 foundChild = true;
196 }
197 } else {
198 foundPossibleChild = true;
199 }
200 } else if (!possibleNodeKinds.overlaps(UType.CHILD_NODE_KINDS)) {
201 if (maybeEmpty) {
202 foundPossibleChild = true;
203 } else {
204 foundChild = true;
205 }
206 } else if (foundChild && possibleNodeKinds == UType.ATTRIBUTE && !maybeEmpty) {
207 XPathException de = new XPathException(
208 "Cannot create an attribute node after creating a child of the containing element");
209 de.setErrorCode(isXSLT() ? "XTDE0410" : "XQTY0024");
210 de.setLocator(component.getLocation());
211 throw de;
212 } else if (foundChild && possibleNodeKinds == UType.NAMESPACE && !maybeEmpty) {
213 XPathException de = new XPathException(
214 "Cannot create a namespace node after creating a child of the containing element");
215 de.setErrorCode(isXSLT() ? "XTDE0410" : "XQTY0024");
216 de.setLocator(component.getLocation());
217 throw de;
218 } else if ((foundChild || foundPossibleChild) && possibleNodeKinds == UType.ATTRIBUTE) {
219 env.issueWarning(
220 "Creating an attribute here will fail if previous instructions create any children",
221 component.getLocation());
222 } else if ((foundChild || foundPossibleChild) && possibleNodeKinds == UType.NAMESPACE) {
223 env.issueWarning(
224 "Creating a namespace node here will fail if previous instructions create any children",
225 component.getLocation());
226 }
227 }
228
229 }
230 }
231
232 /**
233 * Determine (at run-time) the name code of the element being constructed
234 *
235 * @param context the XPath dynamic evaluation context
236 * @param copiedNode for the benefit of xsl:copy, the node being copied; otherwise null
237 * @return the integer name code representing the element name
238 * @throws XPathException if a failure occurs
239 */
240
241 public abstract NodeName getElementName(XPathContext context, /*@Nullable*/ NodeInfo copiedNode) throws XPathException;
242
243 /**
244 * Get the base URI for the element being constructed
245 *
246 * @param context the XPath dynamic evaluation context
247 * @param copiedNode the node being copied (for xsl:copy), otherwise null
248 * @return the base URI of the constructed element
249 */
250
251 public abstract String getNewBaseURI(XPathContext context, NodeInfo copiedNode);
252
253 /**
254 * Callback to output namespace nodes for the new element. This method is responsible
255 * for ensuring that a namespace node is always generated for the namespace of the element
256 * name itself.
257 *
258 * @param context The execution context
259 * @param receiver the Receiver where the namespace nodes are to be written
260 * @param nameCode the name code of the element being created
261 * @param copiedNode the node being copied (for xsl:copy) or null otherwise
262 * @throws XPathException if a dynamic error occurs
263 */
264
265 public abstract void outputNamespaceNodes(
266 XPathContext context, Receiver receiver, NodeName nameCode, /*@Nullable*/ NodeInfo copiedNode)
267 throws XPathException;
268
269 /**
270 * Callback to get a list of the intrinsic namespaces that need to be generated for the element.
271 *
272 * @return the set of namespace bindings.
273 * @throws net.sf.saxon.trans.XPathException if an error occurs
274 */
275
276 public NamespaceBinding[] getActiveNamespaces() throws XPathException {
277 return null;
278 }
279
280 /**
281 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
282 * This method indicates which of these methods is prefered. For instructions this is the process() method.
283 */
284
285 public int getImplementationMethod() {
286 return Expression.PROCESS_METHOD | Expression.EVALUATE_METHOD;
287 }
288
289 /**
290 * Evaluate the instruction to produce a new element node. This method is typically used when there is
291 * a parent element or document in a result tree, to which the new element is added.
292 *
293 * @param context XPath dynamic evaluation context
294 * @return null (this instruction never returns a tail call)
295 * @throws XPathException if a dynamic error occurs
296 */
297 public TailCall processLeavingTail(XPathContext context)
298 throws XPathException {
299 return processLeavingTail(context, null);
300 }
301
302 /**
303 * Evaluate the instruction to produce a new element node. This method is typically used when there is
304 * a parent element or document in a result tree, to which the new element is added.
305 *
306 * @param context XPath dynamic evaluation context
307 * @param copiedNode null except in the case of xsl:copy, when it is the node being copied; otherwise null
308 * @return null (this instruction never returns a tail call)
309 * @throws XPathException if a dynamic error occurs
310 */
311 public final TailCall processLeavingTail(XPathContext context, /*@Nullable*/ NodeInfo copiedNode)
312 throws XPathException {
313
314 try {
315
316 NodeName elemName = getElementName(context, copiedNode);
317 SchemaType typeCode = getValidationAction() == Validation.PRESERVE ? AnyType.getInstance() : Untyped.getInstance();
318
319 Receiver out = context.getReceiver();
320 Receiver saved = out;
321 boolean pop = false;
322 Receiver elemOut = out;
323 if (!preservingTypes) {
324 ParseOptions options = new ParseOptions(getValidationOptions());
325 options.setTopLevelElement(elemName.getStructuredQName());
326 context.getConfiguration().prepareValidationReporting(context, options);
327 Receiver validator = context.getConfiguration().getElementValidator(out, options, getLocation());
328
329 if (validator != out) {
330 out = new TreeReceiver(validator);
331 context.setReceiver(out);
332 pop = true;
333 }
334 elemOut = out;
335 }
336
337 if (elemOut.getSystemId() == null) {
338 elemOut.setSystemId(getNewBaseURI(context, copiedNode));
339 }
340 int properties = inheritNamespacesToChildren ? 0 : ReceiverOptions.DISINHERIT_NAMESPACES;
341 if (!inheritNamespacesFromParent) {
342 properties |= ReceiverOptions.REFUSE_NAMESPACES;
343 }
344
345 elemOut.startElement(elemName, typeCode, getLocation(), properties);
346
347 // output the required namespace nodes via a callback
348
349 outputNamespaceNodes(context, elemOut, elemName, copiedNode);
350
351 // process subordinate instructions to generate attributes and content
352 getContentExpression().process(context);
353
354 // output the element end tag (which will fail if validation fails)
355 elemOut.endElement();
356
357 if (pop) {
358 context.setReceiver(saved);
359 }
360 return null;
361
362 } catch (XPathException e) {
363 e.maybeSetLocation(getLocation());
364 e.maybeSetContext(context);
365 throw e;
366 }
367 }
368
369 /**
370 * Evaluate the constructor, returning the constructed element node. If lazy construction
371 * mode is in effect, then an UnconstructedParent object is returned instead.
372 */
373
374 public Item evaluateItem(XPathContext context) throws XPathException {
375 return constructElement(context, null);
376 // TODO: recover from validation errors that might have occurred
377 }
378
379 /**
380 * Construct the element node as a free-standing (parentless) node in a tiny tree
381 *
382 * @param context XPath dynamic evaluation context
383 * @param copiedNode for the benefit of xsl:copy, the node being copied
384 * @return the constructed element node
385 * @throws XPathException if a dynamic error occurs
386 */
387 private NodeInfo constructElement(XPathContext context, /*@Nullable*/ NodeInfo copiedNode) throws XPathException {
388 try {
389 Controller controller = context.getController();
390 Receiver saved = context.getReceiver();
391 SequenceOutputter seq = controller.allocateSequenceOutputter(1);
392 seq.getPipelineConfiguration().setHostLanguage(getPackageData().getHostLanguage());
393
394 NodeName elemName = getElementName(context, copiedNode);
395 SchemaType typeCode = getValidationAction() == Validation.PRESERVE ? AnyType.getInstance() : Untyped.getInstance();
396
397 SequenceReceiver ini = seq;
398 if (!preservingTypes) {
399 ParseOptions options = new ParseOptions(getValidationOptions());
400 options.setTopLevelElement(elemName.getStructuredQName());
401 controller.getConfiguration().prepareValidationReporting(context, options);
402 Receiver validator = controller.getConfiguration().getElementValidator(ini, options, getLocation());
403
404 if (ini.getSystemId() == null) {
405 ini.setSystemId(getNewBaseURI(context, copiedNode));
406 }
407 if (validator == ini) {
408 context.setReceiver(ini);
409 } else {
410 TreeReceiver tr = new TreeReceiver(validator);
411 tr.setPipelineConfiguration(seq.getPipelineConfiguration());
412 context.setReceiver(tr);
413 ini = tr;
414 }
415 } else {
416 context.setReceiver(ini);
417 if (ini.getSystemId() == null) {
418 ini.setSystemId(getNewBaseURI(context, copiedNode));
419 }
420 }
421
422 ini.open();
423 int properties = inheritNamespacesToChildren ? 0 : ReceiverOptions.DISINHERIT_NAMESPACES;
424 if (!inheritNamespacesFromParent) {
425 properties |= ReceiverOptions.REFUSE_NAMESPACES;
426 }
427 ini.startElement(elemName, typeCode, getLocation(), properties);
428
429 // output the namespace nodes for the new element
430 outputNamespaceNodes(context, ini, elemName, null);
431
432 getContentExpression().process(context);
433
434 ini.endElement();
435 ini.close();
436 context.setReceiver(saved);
437
438 // the constructed element is the first and only item in the sequence
439 NodeInfo result = (NodeInfo) seq.popLastItem();
440 seq.reset();
441 return result;
442
443 } catch (XPathException err) {
444 err.maybeSetLocation(getLocation());
445 err.maybeSetContext(context);
446 throw err;
447 }
448 }
449
450 protected void exportValidationAndType(ExpressionPresenter out) {
451 if (getValidationAction() != Validation.SKIP && getValidationAction() != Validation.BY_TYPE) {
452 out.emitAttribute("validation", Validation.toString(getValidationAction()));
453 }
454 if (getValidationAction() == Validation.BY_TYPE) {
455 SchemaType type = getSchemaType();
456 if (type != null) {
457 out.emitAttribute("type", type.getStructuredQName());
458 }
459 }
460 }
461
462 protected String getInheritanceFlags() {
463 String flags = "";
464 if (!inheritNamespacesFromParent) {
465 flags += "P";
466 }
467 if (!inheritNamespacesToChildren) {
468 flags += "C";
469 }
470 return flags;
471 }
472
473 public void setInheritanceFlags(String flags) {
474 inheritNamespacesFromParent = !flags.contains("P");
475 inheritNamespacesToChildren = !flags.contains("C");
476 }
477
478 /**
479 * Get the (partial) name of a class that supports streaming of this kind of expression
480 *
481 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
482 * or null if there is no such class
483 */
484 @Override
485 public String getStreamerName() {
486 return "ElementCreator";
487 }
488 }
489