Debian Codegraph @

net/sf/saxon/style/LiteralResultElement.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.style;
9
10 import net.sf.saxon.expr.Expression;
11 import net.sf.saxon.expr.Literal;
12 import net.sf.saxon.expr.instruct.*;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.lib.Validation;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.trace.LocationKind;
19 import net.sf.saxon.trans.Err;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.tree.linked.DocumentImpl;
22 import net.sf.saxon.tree.linked.LinkedTreeBuilder;
23 import net.sf.saxon.tree.util.NamespaceIterator;
24 import net.sf.saxon.type.BuiltInAtomicType;
25 import net.sf.saxon.type.SchemaType;
26 import net.sf.saxon.type.Untyped;
27 import net.sf.saxon.z.IntHashSet;
28 import net.sf.saxon.z.IntSet;
29
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Iterator;
33 import java.util.List;
34
35
36 /**
37 * This class represents a literal result element in the style sheet
38 * (typically an HTML element to be output). <br>
39 * It is also used to represent unknown top-level elements, which are ignored.
40 */
41
42 public class LiteralResultElement extends StyleElement {
43
44 private NodeName resultNodeName;
45 private NodeName[] attributeNames;
46 private Expression[] attributeValues;
47 private int numberOfAttributes;
48 private boolean toplevel;
49 private List<NamespaceBinding> namespaceCodes = new ArrayList<>();
50 private StructuredQName[] attributeSets;
51 /*@Nullable*/ private SchemaType schemaType = null;
52 private int validation = Validation.STRIP;
53 private boolean inheritNamespaces = true;
54
55 /**
56 * Determine whether this type of element is allowed to contain a sequence constructor
57 *
58 * @return true: yes, it may contain a sequence constructor
59 */
60
61 public boolean mayContainSequenceConstructor() {
62 return true;
63 }
64
65 /**
66 * Specify that this is an instruction
67 */
68
69 public boolean isInstruction() {
70 return true;
71 }
72
73 /**
74 * Process the attribute list
75 */
76
77 public void prepareAttributes() throws XPathException {
78
79 // Process the values of all attributes. At this stage we deal with attribute
80 // values (especially AVTs), but we do not apply namespace aliasing to the
81 // attribute names.
82
83 AttributeCollection atts = getAttributeList();
84 int num = atts.getLength();
85
86 if (num == 0) {
87 numberOfAttributes = 0;
88 } else {
89 NamePool namePool = getNamePool();
90 attributeNames = new NodeName[num];
91 attributeValues = new Expression[num];
92 numberOfAttributes = 0;
93
94 for (int i = 0; i < num; i++) {
95
96 int fp = atts.getFingerprint(i);
97 NodeName name = atts.getNodeName(i);
98 String attURI = name.getURI();
99
100 if (attURI.equals(NamespaceConstant.XSLT)) {
101
102 if (fp == StandardNames.XSL_USE_ATTRIBUTE_SETS) {
103 // deal with this later
104 } else if (fp == StandardNames.XSL_DEFAULT_COLLATION) {
105 // already dealt with
106 } else if (fp == StandardNames.XSL_DEFAULT_MODE) {
107 // already dealt with
108 } else if (fp == StandardNames.XSL_DEFAULT_VALIDATION) {
109 // already dealt with
110 } else if (fp == StandardNames.XSL_EXTENSION_ELEMENT_PREFIXES) {
111 // already dealt with
112 } else if (fp == StandardNames.XSL_EXCLUDE_RESULT_PREFIXES) {
113 // already dealt with
114 } else if (fp == StandardNames.XSL_EXPAND_TEXT) {
115 // already dealt with
116 } else if (fp == StandardNames.XSL_VERSION) {
117 // already dealt with
118 } else if (fp == StandardNames.XSL_XPATH_DEFAULT_NAMESPACE) {
119 // already dealt with
120 } else if (fp == StandardNames.XSL_TYPE) {
121 // deal with this later
122 } else if (fp == StandardNames.XSL_USE_WHEN) {
123 // already dealt with
124 } else if (fp == StandardNames.XSL_VALIDATION) {
125 // deal with this later
126 } else if (fp == StandardNames.XSL_INHERIT_NAMESPACES) {
127 inheritNamespaces = processBooleanAttribute("xsl:inherit-namespaces", atts.getValue(i));
128 } else if (forwardsCompatibleModeIsEnabled()) {
129 // the attribute is ignored
130 } else {
131 compileError("Unknown XSLT attribute " +
132 Err.wrap(atts.getNodeName(i).getDisplayName(), Err.ATTRIBUTE), "XTSE0805");
133 }
134 } else {
135 attributeNames[numberOfAttributes] = name;
136 Expression exp = makeAttributeValueTemplate(atts.getValue(i), i);
137 attributeValues[numberOfAttributes] = exp;
138 numberOfAttributes++;
139 }
140 }
141
142 // now shorten the arrays if necessary. This is necessary if there are [xsl:]-prefixed
143 // attributes that weren't copied into the arrays.
144
145 if (numberOfAttributes < attributeNames.length) {
146 attributeNames = Arrays.copyOf(attributeNames, numberOfAttributes);
147 attributeValues = Arrays.copyOf(attributeValues, numberOfAttributes);
148 }
149 }
150 resultNodeName = getNodeName();
151
152 }
153
154 /**
155 * Validate that this node is OK
156 *
157 * @param decl
158 */
159
160 public void validate(ComponentDeclaration decl) throws XPathException {
161
162 toplevel = (getParent() instanceof XSLStylesheet);
163
164 resultNodeName = getNodeName();
165
166 String elementURI = getURI();
167
168 if (toplevel) {
169 // A top-level element can never be a "real" literal result element,
170 // but this class gets used for unknown elements found at the top level
171
172 if (elementURI.isEmpty()) {
173 compileError("Top level elements must have a non-null namespace URI", "XTSE0130");
174 }
175 } else {
176
177 // Build the list of output namespace nodes. Note we no longer optimize this list.
178 // See comments in the 9.1 source code for some history of this decision.
179
180 Iterator<NamespaceBinding> inscope = NamespaceIterator.iterateNamespaces(this);
181 while (inscope.hasNext()) {
182 namespaceCodes.add(inscope.next());
183 }
184
185 // Spec bug 5857: if there is no other binding for the default namespace, add an undeclaration
186 // String defaultNamespace = getURIForPrefix("", true);
187 // if (defaultNamespace.length()==0) {
188 // namespaceCodes.add(NamespaceBinding.DEFAULT_UNDECLARATION);
189 // }
190
191 // apply any aliases required to create the list of output namespaces
192
193 PrincipalStylesheetModule sheet = getPrincipalStylesheetModule();
194
195 if (sheet.hasNamespaceAliases()) {
196 for (int i = 0; i < namespaceCodes.size(); i++) {
197 // System.err.println("Examining namespace " + namespaceCodes[i]);
198 String suri = namespaceCodes.get(i).getURI();
199 NamespaceBinding ncode = sheet.getNamespaceAlias(suri);
200 if (ncode != null && !ncode.getURI().equals(suri)) {
201 // apply the namespace alias. Change in 7.3: use the prefix associated
202 // with the new namespace, not the old prefix.
203 namespaceCodes.set(i, ncode);
204 }
205 }
206
207 // determine if there is an alias for the namespace of the element name
208
209 NamespaceBinding elementAlias = sheet.getNamespaceAlias(elementURI);
210 if (elementAlias != null && !elementAlias.getURI().equals(elementURI)) {
211 resultNodeName = new FingerprintedQName(elementAlias.getPrefix(),
212 elementAlias.getURI(),
213 getLocalPart());
214 }
215 }
216
217 // deal with special attributes
218
219 String useAttSets = getAttributeValue(NamespaceConstant.XSLT, "use-attribute-sets");
220 if (useAttSets != null) {
221 attributeSets = getUsedAttributeSets(useAttSets);
222 }
223
224 validation = getDefaultValidation();
225 String type = getAttributeValue(NamespaceConstant.XSLT, "type");
226 if (type != null) {
227 if (!isSchemaAware()) {
228 compileError("The xsl:type attribute is available only with a schema-aware XSLT processor", "XTSE1660");
229 }
230 schemaType = getSchemaType(type);
231 validation = Validation.BY_TYPE;
232 }
233
234 String validate = getAttributeValue(NamespaceConstant.XSLT, "validation");
235 if (validate != null) {
236 validation = validateValidationAttribute(validate);
237 if (schemaType != null) {
238 compileError("The attributes xsl:type and xsl:validation are mutually exclusive", "XTSE1505");
239 }
240 }
241
242 // establish the names to be used for all the output attributes;
243 // also type-check the AVT expressions
244
245 if (numberOfAttributes > 0) {
246 boolean changed = false;
247 for (int i = 0; i < numberOfAttributes; i++) {
248
249 NodeName anameCode = attributeNames[i];
250 NodeName alias = anameCode;
251 String attURI = anameCode.getURI();
252
253 if (!attURI.isEmpty()) { // attribute has a namespace prefix
254 NamespaceBinding newBinding = sheet.getNamespaceAlias(attURI);
255 if (newBinding != null && !newBinding.getURI().equals(attURI)) {
256 alias = new FingerprintedQName(
257 newBinding.getPrefix(),
258 newBinding.getURI(),
259 getAttributeList().getLocalName(i));
260 changed = true;
261 }
262 }
263
264 attributeNames[i] = alias;
265 attributeValues[i] = typeCheck(alias.getDisplayName(), attributeValues[i]);
266 }
267
268 if (changed && numberOfAttributes > 1) {
269 // spec bug 30400. Check that the attribute names are still distinct
270 IntSet names = new IntHashSet(numberOfAttributes);
271 for (int i=0; i<numberOfAttributes; i++) {
272 int fp = attributeNames[i].obtainFingerprint(getNamePool());
273 boolean absent = names.add(fp);
274 if (!absent) {
275 compileError("As a result of namespace aliasing, two attributes have the same expanded name", "XTSE0813");
276 }
277 }
278 }
279 }
280
281 // remove any namespaces that are on the exclude-result-prefixes list.
282 // The namespace is excluded even if it is the namespace of the element or an attribute,
283 // though in that case namespace fixup will reinstate it.
284
285 for (int n = namespaceCodes.size() - 1; n >= 0; n--) {
286 String uri = namespaceCodes.get(n).getURI();
287 if (isExcludedNamespace(uri) && !sheet.isAliasResultNamespace(uri)) {
288 namespaceCodes.remove(n);
289 }
290 }
291 }
292 }
293
294 /**
295 * Validate the children of this node, recursively. Overridden for top-level
296 * data elements.
297 *
298 * @param decl
299 * @param excludeStylesheet
300 */
301
302 protected void validateChildren(ComponentDeclaration decl, boolean excludeStylesheet) throws XPathException {
303 if (!toplevel) {
304 super.validateChildren(decl, excludeStylesheet);
305 }
306 }
307
308 /**
309 * Compile code to process the literal result element at runtime
310 */
311
312 public Expression compile(Compilation exec, ComponentDeclaration decl) throws XPathException {
313 // top level elements in the stylesheet are ignored
314 if (toplevel) {
315 return null;
316 }
317
318 NamespaceBinding[] bindings = namespaceCodes.toArray(NamespaceBinding.EMPTY_ARRAY);
319 FixedElement inst = new FixedElement(
320 resultNodeName,
321 bindings,
322 inheritNamespaces,
323 true, schemaType,
324 validation);
325
326 Expression content = compileSequenceConstructor(exec, decl, true);
327
328 if (numberOfAttributes > 0) {
329 for (int i = attributeNames.length - 1; i >= 0; i--) {
330 FixedAttribute att = new FixedAttribute(
331 attributeNames[i],
332 Validation.STRIP,
333 null);
334 att.setRetainedStaticContext(makeRetainedStaticContext());
335 att.setSelect(attributeValues[i]);
336 att.setLocation(allocateLocation());
337 Expression exp = att;
338 if (exec.getCompilerInfo().isCompileWithTracing()) {
339 TraceExpression trace = new TraceExpression(exp);
340 trace.setNamespaceResolver(getNamespaceResolver());
341 trace.setConstructType(LocationKind.LITERAL_RESULT_ATTRIBUTE);
342 trace.setLocation(allocateLocation());
343 trace.setObjectName(attributeNames[i].getStructuredQName());
344 exp = trace;
345 }
346
347 if (content == null) {
348 content = exp;
349 } else {
350 content = Block.makeBlock(exp, content);
351 content.setLocation(allocateLocation());
352 }
353 }
354 }
355
356 if (attributeSets != null) {
357 Expression use = UseAttributeSet.makeUseAttributeSets(attributeSets, this);
358 if (content == null) {
359 content = use;
360 } else {
361 content = Block.makeBlock(use, content);
362 content.setLocation(allocateLocation());
363 }
364 }
365
366 if (content == null) {
367 content = Literal.makeEmptySequence();
368 }
369 inst.setContentExpression(content);
370 inst.setRetainedStaticContext(makeRetainedStaticContext());
371 inst.setLocation(allocateLocation());
372 return inst;
373 }
374
375 /**
376 * Make a top-level literal result element into a stylesheet. This implements
377 * the "Simplified Stylesheet" facility.
378 * @param topLevel true if this is the top level module of a stylesheet; false if it is included or imported
379 * @return the reconstructed stylesheet with an xsl:stylesheet and xsl:template element added
380 * @throws XPathException if anything goes wrong
381 */
382
383 public DocumentImpl makeStylesheet(boolean topLevel) throws XPathException {
384
385 // the implementation grafts the LRE node onto a containing xsl:template and
386 // xsl:stylesheet
387
388 StyleNodeFactory nodeFactory = getCompilation().getStyleNodeFactory(topLevel);
389 if (!isInScopeNamespace(NamespaceConstant.XSLT)) {
390 String message;
391 if (getLocalPart().equals("stylesheet") || getLocalPart().equals("transform")) {
392 message = "Namespace for stylesheet element should be " + NamespaceConstant.XSLT;
393 } else {
394 message = "The supplied file does not appear to be a stylesheet";
395 }
396 XPathException err = new XPathException(message);
397 err.setLocation(allocateLocation());
398 err.setErrorCode("XTSE0150");
399 err.setIsStaticError(true);
400 //noinspection EmptyCatchBlock
401 compileError(err);
402 throw err;
403
404 }
405
406 // check there is an xsl:version attribute (it's mandatory), and copy
407 // it to the new xsl:stylesheet element
408
409 String version = getAttributeValue(NamespaceConstant.XSLT, "version");
410 if (version == null) {
411 XPathException err = new XPathException("Simplified stylesheet: xsl:version attribute is missing");
412 err.setErrorCode("XTSE0150");
413 err.setIsStaticError(true);
414 err.setLocation(allocateLocation());
415 //noinspection EmptyCatchBlock
416 compileError(err);
417 throw err;
418 }
419
420 try {
421 DocumentImpl oldRoot = (DocumentImpl) getRoot();
422 LinkedTreeBuilder builder = new LinkedTreeBuilder(getConfiguration().makePipelineConfiguration());
423 builder.setNodeFactory(nodeFactory);
424 builder.setSystemId(this.getSystemId());
425
426 builder.open();
427 builder.startDocument(0);
428
429 int st = StandardNames.XSL_STYLESHEET;
430 final Location loc = ExplicitLocation.UNKNOWN_LOCATION;
431 builder.startElement(new CodedName(st, "xsl", getNamePool()), Untyped.getInstance(), loc, 0);
432 builder.namespace(new NamespaceBinding("xsl", NamespaceConstant.XSLT), 0);
433 builder.attribute(new NoNamespaceName("version"), BuiltInAtomicType.UNTYPED_ATOMIC, version, loc, 0);
434 builder.startContent();
435
436 int te = StandardNames.XSL_TEMPLATE;
437 builder.startElement(new CodedName(te, "xsl", getNamePool()), Untyped.getInstance(), loc, 0);
438 builder.attribute(new NoNamespaceName("match"), BuiltInAtomicType.UNTYPED_ATOMIC, "/", loc, 0);
439 builder.startContent();
440
441 builder.graftElement(this);
442
443 builder.endElement();
444 builder.endElement();
445 builder.endDocument();
446 builder.close();
447
448 DocumentImpl newRoot = (DocumentImpl) builder.getCurrentRoot();
449 newRoot.graftLocationMap(oldRoot);
450 return newRoot;
451 } catch (XPathException err) {
452 //TransformerConfigurationException e = new TransformerConfigurationException(err);
453 err.setLocation(allocateLocation());
454 throw err;
455 }
456
457 }
458
459 /**
460 * Get the type of construct. This will be a constant in
461 * class {@link LocationKind}. This method is part of the
462 * {@link net.sf.saxon.trace.InstructionInfo} interface
463 */
464
465 public int getConstructType() {
466 return LocationKind.LITERAL_RESULT_ELEMENT;
467 }
468
469 /**
470 * Get a name identifying the object of the expression, for example a function name, template name,
471 * variable name, key name, element name, etc. This is used only where the name is known statically.
472 * If there is no name, the value will be -1.
473 *
474 * @return the name of the literal result element
475 */
476
477 public StructuredQName getObjectName() {
478 return new StructuredQName(getPrefix(), getURI(), getLocalPart());
479 }
480
481 /**
482 * Get the value of a particular property of the instruction. This is part of the
483 * {@link net.sf.saxon.trace.InstructionInfo} interface for run-time tracing and debugging. The properties
484 * available include all the attributes of the source instruction (named by the attribute name):
485 * these are all provided as string values.
486 *
487 * @param name The name of the required property
488 * @return The value of the requested property, or null if the property is not available
489 */
490
491 public Object getProperty(String name) {
492 if (name.equals("name")) {
493 return getDisplayName();
494 }
495 return null;
496 }
497
498 }