Debian Codegraph @

net/sf/saxon/expr/instruct/ComputedElement.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.Receiver;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.*;
15 import net.sf.saxon.functions.SystemFunction;
16 import net.sf.saxon.lib.NamespaceConstant;
17 import net.sf.saxon.lib.StandardURIChecker;
18 import net.sf.saxon.lib.Validation;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.pattern.ContentTypeTest;
21 import net.sf.saxon.pattern.NodeKindTest;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.type.*;
25 import net.sf.saxon.value.*;
26
27
28 /**
29 * An instruction representing an xsl:element element in an XSLT stylesheet,
30 * or a computed element constructor in XQuery. (In both cases, if the element name
31 * is expressed as a compile-time expression, then a FixedElement instruction
32 * is used instead.)
33 *
34 * @see FixedElement
35 */
36
37 public class ComputedElement extends ElementCreator {
38
39 private Operand nameOp;
40 private Operand namespaceOp;
41
42 private boolean allowNameAsQName;
43 private ItemType itemType;
44
45 /**
46 * Create an instruction that creates a new element node
47 * @param elementName Expression that evaluates to produce the name of the
48 * element node as a lexical QName
49 * @param namespace Expression that evaluates to produce the namespace URI of
50 * the element node. Set to null if the namespace is to be deduced from the prefix
51 * of the elementName.
52 * @param schemaType The required schema type for the content
53 * @param validation Required validation mode (e.g. STRICT, LAX, SKIP)
54 * @param inheritNamespaces true if child elements automatically inherit the namespaces of their parent
55 * @param allowQName True if the elementName expression is allowed to return a QNameValue; false if
56 */
57 public ComputedElement(Expression elementName,
58 Expression namespace,
59 SchemaType schemaType,
60 int validation,
61 boolean inheritNamespaces,
62 boolean allowQName) {
63
64 nameOp = new Operand(this, elementName, OperandRole.SINGLE_ATOMIC);
65 if (namespace != null) {
66 namespaceOp = new Operand(this, namespace, OperandRole.SINGLE_ATOMIC);
67 }
68 setValidationAction(validation, schemaType);
69 preservingTypes = schemaType == null && validation == Validation.PRESERVE;
70 this.inheritNamespacesToChildren = inheritNamespaces;
71 allowNameAsQName = allowQName;
72 }
73
74 /**
75 * Get the expression used to compute the element name
76 *
77 * @return the expression used to compute the element name
78 */
79
80 public Expression getNameExp() {
81 return nameOp.getChildExpression();
82 }
83
84 /**
85 * Get the expression used to compute the namespace URI
86 *
87 * @return the expression used to compute the namespace URI
88 */
89
90 public Expression getNamespaceExp() {
91 return namespaceOp == null ? null : namespaceOp.getChildExpression();
92 }
93
94 protected void setNameExp(Expression elementName) {
95 nameOp.setChildExpression(elementName);
96 }
97
98 protected void setNamespaceExp(Expression namespace) {
99 if (namespaceOp == null) {
100 namespaceOp = new Operand(this, namespace, OperandRole.SINGLE_ATOMIC);
101 } else {
102 namespaceOp.setChildExpression(namespace);
103 }
104 }
105
106 @Override
107 public Iterable<Operand> operands() {
108 return operandSparseList(contentOp, nameOp, namespaceOp);
109 }
110
111 /**
112 * Get the namespace resolver that provides the namespace bindings defined in the static context
113 *
114 * @return the namespace resolver
115 */
116
117 public NamespaceResolver getNamespaceResolver() {
118 return getRetainedStaticContext();
119 }
120
121 /*@NotNull*/
122 public Expression simplify() throws XPathException {
123 setNameExp(getNameExp().simplify());
124 if (getNamespaceExp() != null) {
125 setNamespaceExp(getNamespaceExp().simplify());
126 }
127 Configuration config = getConfiguration();
128 boolean schemaAware = getPackageData().isSchemaAware();
129 preservingTypes |= !schemaAware;
130
131 final SchemaType schemaType = getSchemaType();
132 if (schemaType != null) {
133 itemType = new ContentTypeTest(Type.ELEMENT, schemaType, config, false);
134 schemaType.analyzeContentExpression(getContentExpression(), Type.ELEMENT);
135 } else if (getValidationAction() == Validation.STRIP || !schemaAware) {
136 itemType = new ContentTypeTest(Type.ELEMENT, Untyped.getInstance(), config, false);
137 } else {
138 // paradoxically, we know less about the type if validation="strict" is specified!
139 // We know that it won't be untyped, but we have no way of representing that.
140 itemType = NodeKindTest.ELEMENT;
141 }
142 return super.simplify();
143 }
144
145 /*@NotNull*/
146 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
147 super.typeCheck(visitor, contextInfo);
148 Configuration config = visitor.getConfiguration();
149 TypeHierarchy th = config.getTypeHierarchy();
150
151 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "element/name", 0);
152 if (allowNameAsQName) {
153 // Can only happen in XQuery
154 setNameExp(config.getTypeChecker(false).staticTypeCheck(getNameExp(),
155 SequenceType.SINGLE_ATOMIC, role, visitor));
156 ItemType supplied = getNameExp().getItemType();
157 if (th.relationship(supplied, BuiltInAtomicType.STRING) == TypeHierarchy.DISJOINT &&
158 th.relationship(supplied, BuiltInAtomicType.UNTYPED_ATOMIC) == TypeHierarchy.DISJOINT &&
159 th.relationship(supplied, BuiltInAtomicType.QNAME) == TypeHierarchy.DISJOINT) {
160 XPathException de = new XPathException("The name of a constructed element must be a string, QName, or untypedAtomic");
161 de.setErrorCode("XPTY0004");
162 de.setIsTypeError(true);
163 de.setLocation(getLocation());
164 throw de;
165 }
166 } else {
167 if (!th.isSubType(getNameExp().getItemType(), BuiltInAtomicType.STRING)) {
168 setNameExp(SystemFunction.makeCall("string", getRetainedStaticContext(), getNameExp()));
169 }
170 }
171 if (Literal.isAtomic(getNameExp())) {
172 // Check we have a valid lexical QName, whose prefix is in scope where necessary
173 try {
174 AtomicValue val = (AtomicValue) ((Literal) getNameExp()).getValue();
175 if (val instanceof StringValue) {
176 String[] parts = NameChecker.checkQNameParts(val.getStringValueCS());
177 if (getNamespaceExp() == null) {
178 String prefix = parts[0];
179 String uri = getNamespaceResolver().getURIForPrefix(prefix, true);
180 if (uri == null) {
181 XPathException se = new XPathException("Prefix " + prefix + " has not been declared");
182 se.setErrorCode("XPST0081");
183 se.setIsStaticError(true);
184 throw se;
185 }
186 setNamespaceExp(new StringLiteral(uri));
187 }
188 }
189 } catch (XPathException e) {
190 String code = e.getErrorCodeLocalPart();
191 if (code == null || code.equals("FORG0001")) {
192 e.setErrorCode(isXSLT() ? "XTDE0820" : "XQDY0074");
193 } else if (code.equals("XPST0081")) {
194 e.setErrorCode(isXSLT() ? "XTDE0830" : "XQDY0074");
195 }
196 e.maybeSetLocation(getLocation());
197 e.setIsStaticError(true);
198 throw e;
199 }
200 }
201 return super.typeCheck(visitor, contextInfo);
202 }
203
204 /**
205 * Copy an expression. This makes a deep copy.
206 *
207 * @return the copy of the original expression
208 * @param rebindings a mutable list of (old binding, new binding) pairs
209 * that is used to update the bindings held in any
210 * local variable references that are copied.
211 */
212
213 /*@NotNull*/
214 public Expression copy(RebindingMap rebindings) {
215 ComputedElement ce = new ComputedElement(
216 getNameExp().copy(rebindings), getNamespaceExp() == null ? null : getNamespaceExp().copy(rebindings),
217 /*defaultNamespace,*/ getSchemaType(),
218 getValidationAction(), inheritNamespacesToChildren, allowNameAsQName);
219 ExpressionTool.copyLocationInfo(this, ce);
220 ce.setContentExpression(getContentExpression().copy(rebindings));
221 return ce;
222 }
223
224 /**
225 * Get the item type of the value returned by this instruction
226 *
227 * @return the item type
228 */
229
230 /*@NotNull*/
231 public ItemType getItemType() {
232 if (itemType == null) {
233 return super.getItemType();
234 }
235 return itemType;
236 }
237
238
239 /**
240 * Check that any elements and attributes constructed or returned by this expression are acceptable
241 * in the content model of a given complex type. It's always OK to say yes, since the check will be
242 * repeated at run-time. The process of checking element and attribute constructors against the content
243 * model of a complex type also registers the type of content expected of those constructors, so the
244 * static validation can continue recursively.
245 */
246
247 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
248 if (parentType instanceof SimpleType || ((ComplexType) parentType).isSimpleContent()) {
249 String msg = "Elements are not permitted here: the containing element ";
250 if (parentType instanceof SimpleType) {
251 if (parentType.isAnonymousType()) {
252 msg += "is defined to have a simple type";
253 } else {
254 msg += "is of simple type " + parentType.getDescription();
255 }
256 } else {
257 msg += "has a complex type with simple content";
258 }
259 XPathException err = new XPathException(msg);
260 err.setIsTypeError(true);
261 err.setLocation(getLocation());
262 throw err;
263 }
264 // NOTE: we could in principle check that if all the elements permitted in the content of the parentType
265 // themselves have a simple type (not uncommon, perhaps) then this element must not have element content.
266 }
267
268
269 /**
270 * Callback from the superclass ElementCreator to get the nameCode
271 * for the element name
272 *
273 * @param context The evaluation context (not used)
274 * @param copiedNode Not applicable to this overload
275 * @return the name code for the element name
276 */
277
278 public NodeName getElementName(XPathContext context, NodeInfo copiedNode)
279 throws XPathException {
280
281 Controller controller = context.getController();
282 assert controller != null;
283
284 String prefix;
285 String localName;
286 String uri = null;
287
288 // name needs to be evaluated at run-time
289 AtomicValue nameValue = (AtomicValue) getNameExp().evaluateItem(context);
290 if (nameValue == null) {
291 String errorCode = isXSLT() ? "XTDE0820" : "XPTY0004";
292 XPathException err1 = new XPathException("Invalid element name (empty sequence)", errorCode, getLocation());
293 throw dynamicError(getLocation(), err1, context);
294 }
295 //nameValue = nameValue.getPrimitiveValue();
296 if (nameValue instanceof StringValue) { // which includes UntypedAtomic
297 // this will always be the case in XSLT
298 CharSequence rawName = nameValue.getStringValueCS();
299 rawName = Whitespace.trimWhitespace(rawName);
300 try {
301 String[] parts = NameChecker.getQNameParts(rawName);
302 prefix = parts[0];
303 localName = parts[1];
304 } catch (QNameException err) {
305 String message = "Invalid element name. " + err.getMessage();
306 if (rawName.length() == 0) {
307 message = "Supplied element name is a zero-length string";
308 }
309 String errorCode = isXSLT() ? "XTDE0820" : "XQDY0074";
310 XPathException err1 = new XPathException(message, errorCode, getLocation());
311 throw dynamicError(getLocation(), err1, context);
312 }
313 } else if (nameValue instanceof QNameValue && allowNameAsQName) {
314 // this is allowed in XQuery
315 localName = ((QNameValue) nameValue).getLocalName();
316 uri = ((QNameValue) nameValue).getNamespaceURI();
317 prefix = ((QNameValue) nameValue).getPrefix();
318 if (prefix.equals("xmlns")) {
319 XPathException err = new XPathException("Computed element name has prefix xmlns", "XQDY0096", getLocation());
320 throw dynamicError(getLocation(), err, context);
321 }
322 } else {
323 String errorCode = isXSLT() ? "XTDE0820" : "XPTY0004";
324 XPathException err = new XPathException("Computed element name has incorrect type", errorCode, getLocation());
325 err.setIsTypeError(true);
326 throw dynamicError(getLocation(), err, context);
327 }
328
329 if (getNamespaceExp() == null && uri == null) {
330 uri = getRetainedStaticContext().getURIForPrefix(prefix, true);
331 if (uri == null) {
332 String errorCode = isXSLT() ? "XTDE0830" : prefix.equals("xmlns") ? "XQDY0096" : "XQDY0074";
333 XPathException err = new XPathException("Undeclared prefix in element name: " + prefix, errorCode, getLocation());
334 throw dynamicError(getLocation(), err, context);
335 }
336 } else {
337 if (uri == null) {
338 if (getNamespaceExp() instanceof StringLiteral) {
339 uri = ((StringLiteral) getNamespaceExp()).getStringValue();
340 } else {
341 uri = getNamespaceExp().evaluateAsString(context).toString();
342 if (!StandardURIChecker.getInstance().isValidURI(uri)) {
343 XPathException de = new XPathException(
344 "The value of the namespace attribute must be a valid URI", "XTDE0835", getLocation());
345 throw dynamicError(getLocation(), de, context);
346 }
347 }
348 }
349 if (uri.isEmpty()) {
350 // there is a special rule for this case in the specification;
351 // we force the element to go in the null namespace
352 prefix = "";
353 }
354 if (prefix.equals("xmlns")) {
355 // this isn't a legal prefix so we mustn't use it
356 prefix = "x-xmlns";
357 }
358 }
359 if (uri.equals(NamespaceConstant.XMLNS)) {
360 String errorCode = isXSLT() ? "XTDE0835" : "XQDY0096";
361 XPathException err = new XPathException("Cannot create element in namespace " + uri, errorCode, getLocation());
362 throw dynamicError(getLocation(), err, context);
363 }
364 if (uri.equals(NamespaceConstant.XML) != prefix.equals("xml")) {
365 String message;
366 if (prefix.equals("xml")) {
367 message = "When the prefix is 'xml', the namespace URI must be " + NamespaceConstant.XML;
368 } else {
369 message = "When the namespace URI is " + NamespaceConstant.XML + ", the prefix must be 'xml'";
370 }
371 String errorCode = isXSLT() ? "XTDE0835" : "XQDY0096";
372 XPathException err = new XPathException(message, errorCode, getLocation());
373 throw dynamicError(getLocation(), err, context);
374 }
375
376 return new FingerprintedQName(prefix, uri, localName);
377 }
378
379
380 /**
381 * Ask whether the name can be supplied as a QName. In practice this is true for XQuery, false for XSLT
382 *
383 * @return true if the name can be supplied as a QName
384 */
385
386 public boolean isAllowNameAsQName() {
387 return allowNameAsQName;
388 }
389
390 public String getNewBaseURI(XPathContext context, NodeInfo copiedNode) {
391 return getStaticBaseURIString();
392 }
393
394 /**
395 * Callback to output namespace nodes for the new element.
396 *
397 * @param context The execution context
398 * @param out the Receiver where the namespace nodes are to be written
399 * @param nameCode The name of the element node being output
400 * @param copiedNode Where this is a copied node, the node being copied
401 */
402 public void outputNamespaceNodes(XPathContext context, Receiver out, NodeName nameCode, NodeInfo copiedNode) {
403 // no action
404 }
405
406
407 /**
408 * Get the name of this instruction for diagnostic and tracing purposes
409 */
410
411 public int getInstructionNameCode() {
412 return StandardNames.XSL_ELEMENT;
413 }
414
415 /**
416 * Diagnostic print of expression structure. The abstract expression tree
417 * is written to the supplied output destination.
418 */
419
420 public void export(ExpressionPresenter out) throws XPathException {
421 out.startElement("compElem", this);
422 String flags = getInheritanceFlags();
423 if (isLocal()) {
424 flags += "l";
425 }
426 if (!flags.isEmpty()) {
427 out.emitAttribute("flags", flags);
428 }
429 exportValidationAndType(out);
430 out.setChildRole("name");
431 getNameExp().export(out);
432 if (getNamespaceExp() != null) {
433 out.setChildRole("namespace");
434 getNamespaceExp().export(out);
435 }
436 out.setChildRole("content");
437 getContentExpression().export(out);
438 out.endElement();
439 }
440
441
442 }
443