Debian Codegraph @

net/sf/saxon/expr/instruct/ComputedAttribute.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.ReceiverOptions;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.SystemFunction;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.lib.StandardURIChecker;
17 import net.sf.saxon.lib.Validation;
18 import net.sf.saxon.om.*;
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.Orphan;
23 import net.sf.saxon.type.*;
24 import net.sf.saxon.value.*;
25 import net.sf.saxon.value.StringValue;
26
27 /**
28 * An instruction derived from an xsl:attribute element in stylesheet, or from
29 * an attribute constructor in XQuery, in cases where the attribute name is not known
30 * statically
31 */
32
33 public final class ComputedAttribute extends AttributeCreator {
34
35 private Operand nameOp;
36 private Operand namespaceOp;
37 private boolean allowNameAsQName;
38
39 /**
40 * Construct an Attribute instruction
41 *
42 * @param attributeName An expression to calculate the attribute name
43 * @param namespace An expression to calculate the attribute namespace
44 * @param nsContext a NamespaceContext object containing the static namespace context of the
45 * stylesheet instruction
46 * @param validationAction e.g. validation=strict, lax, strip, preserve
47 * @param schemaType Type against which the attribute must be validated. This must not be a namespace-sensitive
48 * type; it is the caller's responsibility to check this.
49 * @param allowNameAsQName true if the attributeName expression is allowed to evaluate to a value
50 * of type xs:QName (true in XQuery, false in XSLT)
51 */
52
53 public ComputedAttribute(Expression attributeName,
54 Expression namespace,
55 NamespaceResolver nsContext,
56 int validationAction,
57 SimpleType schemaType,
58 boolean allowNameAsQName) {
59 nameOp = new Operand(this, attributeName, OperandRole.SINGLE_ATOMIC);
60 if (namespace != null) {
61 namespaceOp = new Operand(this, namespace, OperandRole.SINGLE_ATOMIC);
62 }
63 setSchemaType(schemaType);
64 setValidationAction(validationAction);
65 setOptions(0);
66 this.allowNameAsQName = allowNameAsQName;
67 }
68
69 /**
70 * Indicate that two attributes with the same name are not acceptable.
71 * (This option is set in XQuery, but not in XSLT)
72 */
73
74 public void setRejectDuplicates() {
75 setOptions(getOptions() | ReceiverOptions.REJECT_DUPLICATES);
76 }
77
78 /**
79 * Get the name of this instruction
80 */
81
82 public int getInstructionNameCode() {
83 return StandardNames.XSL_ATTRIBUTE;
84 }
85
86 /**
87 * Get the expression used to compute the name of the attribute
88 *
89 * @return the expression used to compute the name of the attribute
90 */
91
92 public Expression getNameExp() {
93 return nameOp.getChildExpression();
94 }
95
96 /**
97 * Get the expression used to compute the namespace part of the name of the attribute
98 *
99 * @return the expression used to compute the namespace part of the name of the attribute
100 */
101
102 public Expression getNamespaceExp() {
103 return namespaceOp == null ? null : namespaceOp.getChildExpression();
104 }
105
106 public void setNameExp(Expression attributeName) {
107 nameOp.setChildExpression(attributeName);
108 }
109
110 public void setNamespace(Expression namespace) {
111 if (namespace != null) {
112 if (namespaceOp == null) {
113 namespaceOp = new Operand(this, namespace, OperandRole.SINGLE_ATOMIC);
114 } else {
115 namespaceOp.setChildExpression(namespace);
116 }
117 }
118 }
119
120 @Override
121 public Iterable<Operand> operands() {
122 return operandSparseList(selectOp, nameOp, namespaceOp);
123 }
124
125 /**
126 * Get the namespace resolver used to resolve any prefix in the name of the attribute
127 *
128 * @return the namespace resolver if one has been saved; or null otherwise
129 */
130
131 public NamespaceResolver getNamespaceResolver() {
132 return getRetainedStaticContext();
133 }
134
135 /**
136 * Get the static type of this expression
137 *
138 * @return the static type of the item returned by this expression
139 */
140
141 /*@NotNull*/
142 public ItemType getItemType() {
143 return NodeKindTest.ATTRIBUTE;
144 }
145
146 /**
147 * Get the static cardinality of this expression
148 *
149 * @return the static cardinality (exactly one)
150 */
151
152 public int getCardinality() {
153 return StaticProperty.ALLOWS_ZERO_OR_ONE;
154 }
155
156 /**
157 * Ask whether it is allowed for the name to be evaluted as an xs:QName instance (true in XQuery)
158 *
159 * @return the boolean if name is allowed as a QName
160 */
161 public boolean isAllowNameAsQName() {
162 return allowNameAsQName;
163 }
164
165 /**
166 * Get the static properties of this expression (other than its type). The result is
167 * bit-signficant. These properties are used for optimizations. In general, if
168 * property bit is set, it is true, but if it is unset, the value is unknown.
169 *
170 * @return a set of flags indicating static properties of this expression
171 */
172
173 public int computeSpecialProperties() {
174 return super.computeSpecialProperties() |
175 StaticProperty.SINGLE_DOCUMENT_NODESET;
176 }
177
178
179 public void localTypeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
180 nameOp.typeCheck(visitor, contextItemType);
181
182 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "attribute/name", 0);
183 Configuration config = visitor.getConfiguration();
184 TypeHierarchy th = config.getTypeHierarchy();
185
186 if (allowNameAsQName) {
187 // Can only happen in XQuery
188 setNameExp(config.getTypeChecker(false).staticTypeCheck(getNameExp(),
189 SequenceType.SINGLE_ATOMIC, role, visitor));
190 ItemType nameItemType = getNameExp().getItemType();
191 boolean maybeString = th.relationship(nameItemType, BuiltInAtomicType.STRING) != TypeHierarchy.DISJOINT ||
192 th.relationship(nameItemType, BuiltInAtomicType.UNTYPED_ATOMIC) != TypeHierarchy.DISJOINT;
193 boolean maybeQName = th.relationship(nameItemType, BuiltInAtomicType.QNAME) != TypeHierarchy.DISJOINT;
194 if (!(maybeString || maybeQName)) {
195 XPathException err = new XPathException(
196 "The attribute name must be either an xs:string, an xs:QName, or untyped atomic");
197 err.setErrorCode("XPTY0004");
198 err.setIsTypeError(true);
199 err.setLocation(getLocation());
200 throw err;
201 }
202 } else {
203 if (!th.isSubType(getNameExp().getItemType(), BuiltInAtomicType.STRING)) {
204 setNameExp(SystemFunction.makeCall("string", getRetainedStaticContext(), getNameExp()));
205 }
206 }
207
208 if (getNamespaceExp() != null) {
209 namespaceOp.typeCheck(visitor, contextItemType);
210
211 // Deleted MHK Aug 2014 because the namespace expression is an AVT and therefore necessarily a string
212 // role = new RoleLocator(RoleLocator.INSTRUCTION, "attribute/namespace", 0);
213 // namespace = config.getTypeChecker().staticTypeCheck(
214 // namespace, SequenceType.SINGLE_STRING, false, role, visitor);
215 }
216
217 if (Literal.isAtomic(getNameExp())) {
218 // Check we have a valid lexical QName, whose prefix is in scope where necessary
219 try {
220 AtomicValue val = (AtomicValue) ((Literal) getNameExp()).getValue();
221 if (val instanceof StringValue) {
222 String[] parts = NameChecker.checkQNameParts(val.getStringValueCS());
223 if (getNamespaceExp() == null) {
224 String uri = getNamespaceResolver().getURIForPrefix(parts[0], false);
225 if (uri == null) {
226 XPathException se = new XPathException("Prefix " + parts[0] + " has not been declared");
227 if (isXSLT()) {
228 se.setErrorCode("XTDE0860");
229 se.setIsStaticError(true);
230 throw se;
231 } else {
232 se.setErrorCode("XQDY0074");
233 se.setIsStaticError(false);
234 throw se;
235 }
236 }
237 setNamespace(new StringLiteral(uri));
238 }
239 }
240 } catch (XPathException e) {
241 if (e.getErrorCodeQName() == null || e.getErrorCodeLocalPart().equals("FORG0001")) {
242 e.setErrorCode(isXSLT() ? "XTDE0850" : "XQDY0074");
243 }
244 e.maybeSetLocation(getLocation());
245 e.setIsStaticError(true);
246 throw e;
247 }
248 }
249 }
250
251
252 /*@NotNull*/
253 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
254 Expression exp = super.optimize(visitor, contextItemType);
255 if (exp != this) {
256 return exp;
257 }
258 // If the name is known statically, use a FixedAttribute instead
259 if (getNameExp() instanceof Literal && (getNamespaceExp() == null || getNamespaceExp() instanceof Literal)) {
260 XPathContext context = visitor.getStaticContext().makeEarlyEvaluationContext();
261 NodeName nc = evaluateNodeName(context);
262 FixedAttribute fa = new FixedAttribute(nc, getValidationAction(), getSchemaType());
263 fa.setSelect(getSelect());
264 return fa;
265 }
266 return this;
267 }
268
269 /**
270 * Copy an expression. This makes a deep copy.
271 *
272 * @return the copy of the original expression
273 * @param rebindings a mutable list of (old binding, new binding) pairs
274 * that is used to update the bindings held in any
275 * local variable references that are copied.
276 */
277
278 /*@NotNull*/
279 public Expression copy(RebindingMap rebindings) {
280 ComputedAttribute exp = new ComputedAttribute(
281 getNameExp() == null ? null : getNameExp().copy(rebindings),
282 getNamespaceExp() == null ? null : getNamespaceExp().copy(rebindings),
283 getRetainedStaticContext(), getValidationAction(), getSchemaType(), allowNameAsQName);
284 ExpressionTool.copyLocationInfo(this, exp);
285 exp.setSelect(getSelect().copy(rebindings));
286 exp.setInstruction(isInstruction());
287 return exp;
288 }
289
290
291 /**
292 * Check that any elements and attributes constructed or returned by this expression are acceptable
293 * in the content model of a given complex type. It's always OK to say yes, since the check will be
294 * repeated at run-time. The process of checking element and attribute constructors against the content
295 * model of a complex type also registers the type of content expected of those constructors, so the
296 * static validation can continue recursively.
297 */
298
299 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
300 if (parentType instanceof SimpleType) {
301 String msg = "Attributes are not permitted here: ";
302 if (parentType.isAnonymousType()) {
303 msg += "the containing element is defined to have a simple type";
304 } else {
305 msg += "the containing element is of simple type " + parentType.getDescription();
306 }
307 XPathException err = new XPathException(msg);
308 err.setIsTypeError(true);
309 err.setLocation(getLocation());
310 throw err;
311 }
312 }
313
314
315 /**
316 * Determine the name to be used for the attribute, as an integer name code
317 *
318 * @param context Dynamic evaluation context
319 * @return the integer name code for the attribute name
320 * @throws XPathException if a dynamic error occurs (for example, if the attribute name is invalid)
321 */
322
323 public NodeName evaluateNodeName(XPathContext context) throws XPathException {
324 NamePool pool = context.getNamePool();
325
326 Item nameValue = getNameExp().evaluateItem(context);
327
328 String prefix;
329 String localName;
330 String uri = null;
331
332 if (nameValue instanceof StringValue) {
333 // this will always be the case in XSLT
334 CharSequence rawName = nameValue.getStringValueCS();
335 rawName = Whitespace.trimWhitespace(rawName); // required in XSLT; possibly wrong in XQuery
336 try {
337 String[] parts = NameChecker.getQNameParts(rawName);
338 prefix = parts[0];
339 localName = parts[1];
340 } catch (QNameException err) {
341 String errorCode = isXSLT() ? "XTDE0850" : "XQDY0074";
342 XPathException err1 = new XPathException("Invalid attribute name: " + rawName, errorCode, this.getLocation());
343 throw dynamicError(getLocation(), err1, context);
344 }
345 if (rawName.toString().equals("xmlns")) {
346 if (getNamespaceExp() == null) {
347 String errorCode = isXSLT() ? "XTDE0855" : "XQDY0044";
348 XPathException err = new XPathException("Invalid attribute name: " + rawName, errorCode, this.getLocation());
349 throw dynamicError(getLocation(), err, context);
350 }
351 }
352 if (prefix.equals("xmlns")) {
353 if (getNamespaceExp() == null) {
354 String errorCode = isXSLT() ? "XTDE0860" : "XQDY0044";
355 XPathException err = new XPathException("Invalid attribute name: " + rawName, errorCode, this.getLocation());
356 throw dynamicError(getLocation(), err, context);
357 } else {
358 // ignore the prefix "xmlns"
359 prefix = "";
360 }
361 }
362
363 } else if (nameValue instanceof QNameValue && allowNameAsQName) {
364 // this is allowed in XQuery
365 localName = ((QNameValue) nameValue).getLocalName();
366 uri = ((QNameValue) nameValue).getNamespaceURI();
367 if (localName.equals("xmlns") && uri.isEmpty()) {
368 XPathException err = new XPathException("Invalid attribute name: xmlns", "XQDY0044", this.getLocation());
369 throw dynamicError(getLocation(), err, context);
370 }
371
372 if (uri.isEmpty()) {
373 prefix = "";
374 } else {
375 prefix = ((QNameValue) nameValue).getPrefix();
376 if (prefix.isEmpty()) {
377 prefix = pool.suggestPrefixForURI(uri);
378 if (prefix == null) {
379 prefix = "ns0";
380 // If the prefix is a duplicate, a different one will be substituted
381 }
382 }
383 if (uri.equals(NamespaceConstant.XML) != "xml".equals(prefix)) {
384 String message;
385 if ("xml".equals(prefix)) {
386 message = "When the prefix is 'xml', the namespace URI must be " + NamespaceConstant.XML;
387 } else {
388 message = "When the namespace URI is " + NamespaceConstant.XML + ", the prefix must be 'xml'";
389 }
390 String errorCode = isXSLT() ? "XTDE0835" : "XQDY0044";
391 XPathException err = new XPathException(message, errorCode, this.getLocation());
392 throw dynamicError(getLocation(), err, context);
393 }
394 }
395
396 if ("xmlns".equals(prefix)) {
397 XPathException err = new XPathException("Invalid attribute namespace: http://www.w3.org/2000/xmlns/", "XQDY0044", this.getLocation());
398 throw dynamicError(getLocation(), err, context);
399 }
400
401 } else {
402 XPathException err = new XPathException("Attribute name must be either a string or a QName", "XPTY0004", this.getLocation());
403 err.setIsTypeError(true);
404 throw dynamicError(getLocation(), err, context);
405 }
406
407 if (getNamespaceExp() == null && uri == null) {
408 if (prefix.isEmpty()) {
409 uri = "";
410 } else {
411 uri = getRetainedStaticContext().getURIForPrefix(prefix, false);
412 if (uri == null) {
413 String errorCode = isXSLT() ? "XTDE0860" : "XQDY0074";
414 XPathException err = new XPathException("Undeclared prefix in attribute name: " + prefix, errorCode, this.getLocation());
415 throw dynamicError(getLocation(), err, context);
416 }
417 }
418
419 } else {
420 if (uri == null) {
421 // generate a name using the supplied namespace URI
422 if (getNamespaceExp() instanceof StringLiteral) {
423 uri = ((StringLiteral) getNamespaceExp()).getStringValue();
424 } else {
425 uri = getNamespaceExp().evaluateAsString(context).toString();
426 if (!StandardURIChecker.getInstance().isValidURI(uri)) {
427 XPathException de = new XPathException("The value of the namespace attribute must be a valid URI", "XTDE0865", this.getLocation());
428 throw dynamicError(getLocation(), de, context);
429 }
430 }
431 }
432 if (uri.isEmpty()) {
433 // there is a special rule for this case in the XSLT specification;
434 // we force the attribute to go in the null namespace
435 prefix = "";
436
437 } else {
438 // if a suggested prefix is given, use it; otherwise try to find a prefix
439 // associated with this URI; if all else fails, invent one.
440 if (prefix.isEmpty()) {
441 prefix = pool.suggestPrefixForURI(uri);
442 if (prefix == null) {
443 prefix = "ns0";
444 // this will be replaced later if it is already in use
445 }
446 }
447 }
448 }
449
450 if (uri.equals(NamespaceConstant.XMLNS)) {
451 String errorCode = isXSLT() ? "XTDE0865" : "XQDY0044";
452 XPathException err = new XPathException("Cannot create attribute in namespace " + uri, errorCode, this.getLocation());
453 throw dynamicError(getLocation(), err, context);
454 }
455
456 return new FingerprintedQName(prefix, uri, localName);
457 }
458
459 @Override
460 public Item evaluateItem(XPathContext context) throws XPathException {
461 Item node = super.evaluateItem(context);
462 validateOrphanAttribute((Orphan) node, context);
463 return node;
464 }
465
466 /**
467 * Diagnostic print of expression structure. The abstract expression tree
468 * is written to the supplied output destination.
469 */
470
471 public void export(ExpressionPresenter out) throws XPathException {
472 out.startElement("compAtt", this);
473 if (getValidationAction() != Validation.SKIP) {
474 out.emitAttribute("validation", Validation.toString(getValidationAction()));
475 }
476 SimpleType type = getSchemaType();
477 if (type != null) {
478 out.emitAttribute("type", type.getStructuredQName());
479 }
480 String flags = "";
481 if (isLocal()) {
482 flags += "l";
483 }
484 if (!flags.isEmpty()) {
485 out.emitAttribute("flags", flags);
486 }
487 out.setChildRole("name");
488 getNameExp().export(out);
489 if (getNamespaceExp() != null) {
490 out.setChildRole("namespace");
491 getNamespaceExp().export(out);
492 }
493 out.setChildRole("select");
494 getSelect().export(out);
495 out.endElement();
496 }
497
498
499 }
500