Debian Codegraph @

net/sf/saxon/expr/instruct/FixedElement.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.event.Receiver;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.lib.Validation;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.pattern.CombinedNodeTest;
17 import net.sf.saxon.pattern.ContentTypeTest;
18 import net.sf.saxon.pattern.NameTest;
19 import net.sf.saxon.pattern.NodeKindTest;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.tree.util.FastStringBuffer;
23 import net.sf.saxon.type.*;
24
25
26 /**
27 * An instruction that creates an element node whose name is known statically.
28 * Used for literal results elements in XSLT, for direct element constructors
29 * in XQuery, and for xsl:element in cases where the name and namespace are
30 * known statically.
31 */
32
33 public class FixedElement extends ElementCreator {
34
35 private NodeName elementName;
36 /*@NotNull*/ protected NamespaceBinding[] namespaceBindings;
37 private ItemType itemType;
38
39 /**
40 * Create an instruction that creates a new element node
41 *
42 * @param elementName Represents the name of the element node
43 * @param namespaceBindings List of namespaces to be added to the element node.
44 * Supply an empty array if none are required.
45 * @param inheritNamespacesToChildren true if the children of this element inherit its namespaces
46 * @param inheritNamespacesFromParent true if this element inherits namespaces from its parent
47 * @param schemaType Type annotation for the new element node
48 * @param validation Validation mode to be applied, for example STRICT, LAX, SKIP
49 */
50 public FixedElement(NodeName elementName,
51 NamespaceBinding[] namespaceBindings,
52 boolean inheritNamespacesToChildren,
53 boolean inheritNamespacesFromParent,
54 SchemaType schemaType,
55 int validation) {
56 this.elementName = elementName;
57 this.namespaceBindings = namespaceBindings;
58 this.inheritNamespacesToChildren = inheritNamespacesToChildren;
59 this.inheritNamespacesFromParent = inheritNamespacesFromParent;
60 setValidationAction(validation, schemaType);
61 preservingTypes = schemaType == null && validation == Validation.PRESERVE;
62 }
63
64 @Override
65 public Iterable<Operand> operands() {
66 return contentOp;
67 }
68
69 /**
70 * Simplify an expression. This performs any context-independent rewriting
71 *
72 *
73 *
74 * @throws net.sf.saxon.trans.XPathException
75 * if an error is discovered during expression rewriting
76 */
77
78 /*@NotNull*/
79 public Expression simplify() throws XPathException {
80 final Configuration config = getConfiguration();
81 preservingTypes |= !getPackageData().isSchemaAware();
82 return super.simplify();
83 }
84
85 /**
86 * Check statically whether the content of the element creates attributes or namespaces
87 * after creating any child nodes
88 *
89 * @param env the static context
90 * @throws net.sf.saxon.trans.XPathException if the content sequence is invalid
91 *
92 */
93
94 protected void checkContentSequence(StaticContext env) throws XPathException {
95 super.checkContentSequence(env);
96 itemType = computeFixedElementItemType(this, env,
97 getValidationAction(), getSchemaType(), elementName, getContentExpression());
98 }
99
100 /*@NotNull*/
101 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
102 Expression e = super.optimize(visitor, contextItemType);
103 if (e != this) {
104 return e;
105 }
106 // Remove any unnecessary creation of namespace nodes by child literal result elements.
107 // Specifically, if this instruction creates a namespace node, then a child literal result element
108 // doesn't need to create the same namespace if all the following conditions are true:
109 // (a) the child element is in the same namespace as its parent, and
110 // (b) this element doesn't specify xsl:inherit-namespaces="no"
111 // (c) the child element is incapable of creating attributes in a non-null namespace
112
113 if (!inheritNamespacesToChildren) {
114 return this;
115 }
116 if (namespaceBindings.length == 0) {
117 return this;
118 }
119 if (getContentExpression() instanceof FixedElement) {
120 FixedElement fixedContent = (FixedElement) getContentExpression();
121 if (elementName.isInSameNamespace(fixedContent.getElementName())) {
122 fixedContent.removeRedundantNamespaces(visitor, namespaceBindings);
123 }
124 return this;
125 }
126 if (getContentExpression() instanceof Block) {
127 for (Operand o : getContentExpression().operands()) {
128 Expression exp = o.getChildExpression();
129 if (exp instanceof FixedElement && elementName.isInSameNamespace(((FixedElement) exp).getElementName())) {
130 ((FixedElement) exp).removeRedundantNamespaces(visitor, namespaceBindings);
131 }
132 }
133 }
134 return this;
135 }
136
137 /**
138 * Remove namespaces that are not required for this element because they are output on
139 * the parent element
140 *
141 * @param visitor the expression visitor
142 * @param parentNamespaces the namespaces that are output by the parent element
143 */
144
145 private void removeRedundantNamespaces(ExpressionVisitor visitor, NamespaceBinding[] parentNamespaces) {
146 // It's only safe to remove any namespaces if the element is incapable of creating any attribute nodes
147 // in a non-null namespace
148 // This is because namespaces created on this element take precedence over namespaces created by namespace
149 // fixup based on the prefix used in the attribute name (see atrs24)
150 if (namespaceBindings.length == 0) {
151 return;
152 }
153 TypeHierarchy th = visitor.getConfiguration().getTypeHierarchy();
154 ItemType contentType = getContentExpression().getItemType();
155 boolean ok = th.relationship(contentType, NodeKindTest.ATTRIBUTE) == TypeHierarchy.DISJOINT;
156 if (!ok) {
157 // if the content might include attributes, discount any that are known to be in the null namespace
158 if (getContentExpression() instanceof Block) {
159 ok = true;
160 for (Operand o : getContentExpression().operands()) {
161 Expression exp = o.getChildExpression();
162 if (exp instanceof FixedAttribute) {
163 if (!((FixedAttribute)exp).getAttributeName().hasURI("")) {
164 ok = false;
165 break;
166 }
167 } else {
168 ItemType childType = exp.getItemType();
169 if (th.relationship(childType, NodeKindTest.ATTRIBUTE) != TypeHierarchy.DISJOINT) {
170 ok = false;
171 break;
172 }
173 }
174 }
175 }
176 }
177 if (ok) {
178 int removed = 0;
179 for (int i = 0; i < namespaceBindings.length; i++) {
180 for (NamespaceBinding parentNamespace : parentNamespaces) {
181 if (namespaceBindings[i] == parentNamespace) {
182 namespaceBindings[i] = null;
183 removed++;
184 break;
185 }
186 }
187 }
188 if (removed > 0) {
189 if (removed == namespaceBindings.length) {
190 namespaceBindings = NamespaceBinding.EMPTY_ARRAY;
191 } else {
192 NamespaceBinding[] ns2 = new NamespaceBinding[namespaceBindings.length - removed];
193 int j = 0;
194 for (NamespaceBinding namespaceBinding : namespaceBindings) {
195 if (namespaceBinding != null) {
196 ns2[j++] = namespaceBinding;
197 }
198 }
199 namespaceBindings = ns2;
200 }
201 }
202 }
203 }
204
205 /**
206 * Copy an expression. This makes a deep copy.
207 *
208 * @return the copy of the original expression
209 * @param rebindings a mutable list of (old binding, new binding) pairs
210 * that is used to update the bindings held in any
211 * local variable references that are copied.
212 */
213
214 /*@NotNull*/
215 public Expression copy(RebindingMap rebindings) {
216 NamespaceBinding[] ns2 = namespaceBindings;
217 if (namespaceBindings.length != 0) {
218 ns2 = new NamespaceBinding[namespaceBindings.length];
219 System.arraycopy(namespaceBindings, 0, ns2, 0, ns2.length);
220 }
221 FixedElement fe = new FixedElement(elementName, ns2, inheritNamespacesToChildren,
222 inheritNamespacesFromParent, getSchemaType(), getValidationAction());
223 fe.setContentExpression(getContentExpression().copy(rebindings));
224 ExpressionTool.copyLocationInfo(this, fe);
225 return fe;
226 }
227
228 /**
229 * Determine the item type of an element being constructed
230 *
231 * @param instr the FixedElement instruction
232 * @param env the static context
233 * @param validation the schema validation mode
234 * @param schemaType the schema type for validation
235 * @param elementName the name of the element
236 * @param content the expression that computes the content of the element
237 * @return the item type
238 * @throws XPathException if a static error is detected
239 */
240
241 private ItemType computeFixedElementItemType(FixedElement instr, StaticContext env,
242 int validation, SchemaType schemaType,
243 NodeName elementName, Expression content) throws XPathException {
244 final Configuration config = env.getConfiguration();
245 ItemType itemType;
246 int fp = elementName.obtainFingerprint(config.getNamePool()); // Bug #2563 - namespaced alias in unoptimized export
247 if (schemaType == null) {
248 if (validation == Validation.STRICT) {
249 SchemaDeclaration decl = config.getElementDeclaration(fp);
250 if (decl == null) {
251 XPathException err = new XPathException("There is no global element declaration for " +
252 elementName.getStructuredQName().getEQName() +
253 ", so strict validation will fail");
254 err.setErrorCode(instr.isXSLT() ? "XTTE1512" : "XQDY0084");
255 err.setIsTypeError(true); // technically this is a type error in XSLT but not in XQuery
256 err.setLocation(instr.getLocation());
257 throw err;
258 }
259 if (decl.isAbstract()) {
260 XPathException err = new XPathException("The element declaration for " +
261 elementName.getStructuredQName().getEQName() +
262 " is abstract, so strict validation will fail");
263 err.setErrorCode(instr.isXSLT() ? "XTTE1512" : "XQDY0027");
264 err.setIsTypeError(true); // technically this is a type error in XSLT but not in XQuery
265 err.setLocation(instr.getLocation());
266 throw err;
267 }
268 SchemaType declaredType = decl.getType();
269 SchemaType xsiType = instr.getXSIType(env);
270 if (xsiType != null) {
271 schemaType = xsiType;
272 } else {
273 schemaType = declaredType;
274 }
275
276 itemType = new CombinedNodeTest(
277 new NameTest(Type.ELEMENT, fp, env.getConfiguration().getNamePool()),
278 Token.INTERSECT,
279 new ContentTypeTest(Type.ELEMENT, schemaType, config, false));
280 if (xsiType != null || !decl.hasTypeAlternatives()) {
281 instr.getValidationOptions().setTopLevelType(schemaType);
282 try {
283 schemaType.analyzeContentExpression(content, Type.ELEMENT);
284 } catch (XPathException e) {
285 e.setErrorCode(instr.isXSLT() ? "XTTE1510" : "XQDY0027");
286 e.setLocation(instr.getLocation());
287 throw e;
288 }
289 if (xsiType != null) {
290 try {
291 config.checkTypeDerivationIsOK(xsiType, declaredType, 0);
292 } catch (SchemaException e) {
293 ValidationFailure ve = new ValidationFailure("The specified xsi:type " + xsiType.getDescription() +
294 " is not validly derived from the required type " + declaredType.getDescription());
295 ve.setConstraintReference(1, "cvc-elt", "4.3");
296 ve.setErrorCode(instr.isXSLT() ? "XTTE1515" : "XQDY0027");
297 ve.setLocator(instr.getLocation());
298 throw ve.makeException();
299 }
300 }
301 }
302 } else if (validation == Validation.LAX) {
303 SchemaDeclaration decl = config.getElementDeclaration(fp);
304 if (decl == null) {
305 env.issueWarning("There is no global element declaration for " +
306 elementName.getDisplayName(), instr.getLocation());
307 itemType = new NameTest(Type.ELEMENT, fp, config.getNamePool());
308 } else {
309 schemaType = decl.getType();
310 instr.getValidationOptions().setTopLevelType(schemaType);
311 itemType = new CombinedNodeTest(
312 new NameTest(Type.ELEMENT, fp, config.getNamePool()),
313 Token.INTERSECT,
314 new ContentTypeTest(Type.ELEMENT, instr.getSchemaType(), config, false));
315 try {
316 schemaType.analyzeContentExpression(content, Type.ELEMENT);
317 } catch (XPathException e) {
318 e.setErrorCode(instr.isXSLT() ? "XTTE1515" : "XQDY0027");
319 e.setLocation(instr.getLocation());
320 throw e;
321 }
322 }
323 } else if (validation == Validation.PRESERVE) {
324 // we know the result will be an element of type xs:anyType
325 itemType = new CombinedNodeTest(
326 new NameTest(Type.ELEMENT, fp, config.getNamePool()),
327 Token.INTERSECT,
328 new ContentTypeTest(Type.ELEMENT, AnyType.getInstance(), config, false));
329 } else {
330 // we know the result will be an untyped element
331 itemType = new CombinedNodeTest(
332 new NameTest(Type.ELEMENT, fp, config.getNamePool()),
333 Token.INTERSECT,
334 new ContentTypeTest(Type.ELEMENT, Untyped.getInstance(), config, false));
335 }
336 } else {
337 itemType = new CombinedNodeTest(
338 new NameTest(Type.ELEMENT, fp, config.getNamePool()),
339 Token.INTERSECT,
340 new ContentTypeTest(Type.ELEMENT, schemaType, config, false)
341 );
342 try {
343 schemaType.analyzeContentExpression(content, Type.ELEMENT);
344 } catch (XPathException e) {
345 e.setErrorCode(instr.isXSLT() ? "XTTE1540" : "XQDY0027");
346 e.setLocation(instr.getLocation());
347 throw e;
348 }
349 }
350 return itemType;
351 }
352
353 /**
354 * Get the type of the item returned by this instruction
355 *
356 * @return the item type
357 */
358 /*@NotNull*/
359 public ItemType getItemType() {
360 if (itemType == null) {
361 return super.getItemType();
362 }
363 return itemType;
364 }
365
366 /**
367 * Callback from the superclass ElementCreator to get the nameCode
368 * for the element name
369 *
370 * @param context The evaluation context (not used)
371 * @param copiedNode For the benefit of the xsl:copy instruction, the node to be copied
372 * @return the name code for the element name
373 */
374
375 public NodeName getElementName(XPathContext context, NodeInfo copiedNode) {
376 return elementName;
377 }
378
379 public NodeName getElementName() {
380 return elementName;
381 }
382
383 public String getNewBaseURI(XPathContext context, NodeInfo copiedNode) {
384 return getStaticBaseURIString();
385 }
386
387 /**
388 * Determine whether the element constructor creates a fixed xsi:type attribute, and if so, return the
389 * relevant type.
390 *
391 * @param env the static context
392 * @return the type denoted by the constructor's xsi:type attribute if there is one.
393 * Return null if there is no xsi:type attribute, or if the value of the xsi:type
394 * attribute is a type that is not statically known (this is allowed)
395 * @throws XPathException if there is an xsi:type attribute and its value is not a QName.
396 */
397
398 private SchemaType getXSIType(StaticContext env) throws XPathException {
399 if (getContentExpression() instanceof FixedAttribute) {
400 return testForXSIType((FixedAttribute) getContentExpression(), env);
401 } else if (getContentExpression() instanceof Block) {
402 for (Operand o : getContentExpression().operands()) {
403 Expression exp = o.getChildExpression();
404 if (exp instanceof FixedAttribute) {
405 SchemaType type = testForXSIType((FixedAttribute) exp, env);
406 if (type != null) {
407 return type;
408 }
409 }
410 }
411 return null;
412 } else {
413 return null;
414 }
415 }
416
417 /**
418 * Test whether a FixedAttribute child instruction of this FixedElement is creating an xsi:type
419 * attribute whose value is known statically; if this is the case, then return the schema type
420 * named in this attribute
421 *
422 * @param fat The FixedAttribute instruction
423 * @param env The XPath static context
424 * @return the schema type if this is an xsi:type attribute instruction whose value is known at compile time;
425 * otherwise null
426 * @throws XPathException if an error occurs
427 */
428
429 private SchemaType testForXSIType(FixedAttribute fat, StaticContext env) throws XPathException {
430 int att = fat.getAttributeFingerprint();
431 if (att == StandardNames.XSI_TYPE) {
432 Expression attValue = fat.getSelect();
433 if (attValue instanceof StringLiteral) {
434 try {
435 NamePool pool = env.getConfiguration().getNamePool();
436 String[] parts = NameChecker.getQNameParts(
437 ((StringLiteral) attValue).getStringValue());
438 // The only namespace bindings we can trust are those declared on this element
439 // We could also trust those on enclosing LREs in the same function/template,
440 // but it's not a big win to go looking for them.
441 String uri = null;
442 for (NamespaceBinding namespaceBinding : namespaceBindings) {
443 String prefix = namespaceBinding.getPrefix();
444 if (prefix.equals(parts[0])) {
445 uri = namespaceBinding.getURI();
446 break;
447 }
448 }
449 if (uri == null) {
450 return null;
451 }
452 return env.getConfiguration().getSchemaType(new StructuredQName("", uri, parts[1]));
453 } catch (QNameException e) {
454 throw new XPathException(e.getMessage());
455 }
456 }
457 }
458 return null;
459 }
460
461 /**
462 * Check that any elements and attributes constructed or returned by this expression are acceptable
463 * in the content model of a given complex type. It's always OK to say yes, since the check will be
464 * repeated at run-time. The process of checking element and attribute constructors against the content
465 * model of a complex type also registers the type of content expected of those constructors, so the
466 * static validation can continue recursively.
467 */
468
469 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
470 if (parentType instanceof SimpleType) {
471 XPathException err = new XPathException("Element " + elementName.getDisplayName() +
472 " is not permitted here: the containing element is of simple type " + parentType.getDescription());
473 err.setIsTypeError(true);
474 err.setLocation(getLocation());
475 throw err;
476 } else if (((ComplexType) parentType).isSimpleContent()) {
477 XPathException err = new XPathException("Element " + elementName.getDisplayName() +
478 " is not permitted here: the containing element has a complex type with simple content");
479 err.setIsTypeError(true);
480 err.setLocation(getLocation());
481 throw err;
482 }
483
484 // Check that a sequence consisting of this element alone is valid against the content model
485 if (whole) {
486 Expression parent = getParentExpression();
487 Block block = new Block(new Expression[]{this});
488 parentType.analyzeContentExpression(block, Type.ELEMENT);
489 setParentExpression(parent);
490 }
491
492 SchemaType type;
493 try {
494 int fp = elementName.obtainFingerprint(getConfiguration().getNamePool());
495 type = ((ComplexType) parentType).getElementParticleType(fp, true);
496 } catch (SchemaException e) {
497 throw new XPathException(e);
498 }
499 if (type == null) {
500 XPathException err = new XPathException("Element " + elementName.getDisplayName() +
501 " is not permitted in the content model of the complex type " +
502 parentType.getDescription());
503 err.setIsTypeError(true);
504 err.setLocation(getLocation());
505 err.setErrorCode(isXSLT() ? "XTTE1510" : "XQDY0027");
506 throw err;
507 }
508 if (type instanceof AnyType) {
509 return;
510 }
511
512 try {
513 getContentExpression().checkPermittedContents(type, true);
514 } catch (XPathException e) {
515 e.maybeSetLocation(getLocation());
516 throw e;
517 }
518 }
519
520 /**
521 * Callback from the superclass ElementCreator to output the namespace nodes
522 *
523 * @param context The evaluation context (not used)
524 * @param out The receiver to handle the output
525 * @param nameCode the name of this element
526 * @param copiedNode in the case of xsl:copy, the node being copied
527 */
528
529 public void outputNamespaceNodes(XPathContext context, Receiver out, NodeName nameCode, NodeInfo copiedNode)
530 throws XPathException {
531 for (NamespaceBinding namespaceBinding : namespaceBindings) {
532 out.namespace(namespaceBinding, 0);
533 }
534 }
535
536 /**
537 * Callback to get a list of the intrinsic namespaces that need to be generated for the element.
538 * The result is an array of namespace codes, the codes either occupy the whole array or are
539 * terminated by a -1 entry. A result of null is equivalent to a zero-length array.
540 */
541
542 public NamespaceBinding[] getActiveNamespaces() {
543 return namespaceBindings;
544 }
545
546 /**
547 * Diagnostic print of expression structure. The abstract expression tree
548 * is written to the supplied output destination.
549 */
550
551 public void export(ExpressionPresenter out) throws XPathException {
552 out.startElement("elem", this);
553 out.emitAttribute("name", elementName.getDisplayName());
554 out.emitAttribute("nsuri", elementName.getURI());
555 String flags = getInheritanceFlags();
556 if (!elementName.getURI().isEmpty() && elementName.getPrefix().isEmpty()) {
557 flags += "d"; // "d" to indicate default namespace
558 }
559 if (isLocal()) {
560 flags += "l";
561 }
562 if (!flags.isEmpty()) {
563 out.emitAttribute("flags", flags);
564 }
565 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C256);
566 if (namespaceBindings.length > 0) {
567 for (NamespaceBinding ns : namespaceBindings) {
568 String prefix = ns.getPrefix();
569 fsb.append(prefix.isEmpty() ? "#" : prefix);
570 if (!ns.getURI().equals(getRetainedStaticContext().getURIForPrefix(prefix, true))) {
571 fsb.append('=');
572 fsb.append(ns.getURI());
573 }
574 fsb.append(' ');
575 }
576 fsb.setLength(fsb.length() - 1);
577 out.emitAttribute("namespaces", fsb.toString());
578 }
579 exportValidationAndType(out);
580 getContentExpression().export(out);
581 out.endElement();
582 }
583
584 @Override
585 public String toString() {
586 return "<" + elementName.getStructuredQName().getDisplayName() + " {" + getContentExpression().toString() + "}/>";
587 }
588
589 @Override
590 public String toShortString() {
591 return "<" + elementName.getStructuredQName().getDisplayName() + " {" + getContentExpression().toShortString() + "}/>";
592 }
593
594 /**
595 * Get a name identifying the kind of expression, in terms meaningful to a user.
596 *
597 * @return a name identifying the kind of expression, in terms meaningful to a user.
598 * The name will always be in the form of a lexical XML QName, and should match the name used
599 * in explain() output displaying the expression.
600 */
601 @Override
602 public String getExpressionName() {
603 return "element";
604 }
605 }
606