Debian Codegraph @

net/sf/saxon/style/StylesheetModule.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.Configuration;
11 import net.sf.saxon.PreparedStylesheet;
12 import net.sf.saxon.event.*;
13 import net.sf.saxon.lib.*;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.trans.packages.IPackageLoader;
17 import net.sf.saxon.tree.iter.AxisIterator;
18 import net.sf.saxon.tree.linked.DocumentImpl;
19 import net.sf.saxon.tree.linked.LinkedTreeBuilder;
20 import net.sf.saxon.tree.tiny.TinyBuilder;
21 import net.sf.saxon.type.Type;
22 import net.sf.saxon.value.NestedIntegerValue;
23 import net.sf.saxon.value.Whitespace;
24 import org.jetbrains.annotations.NotNull;
25 import org.xml.sax.InputSource;
26 import org.xml.sax.XMLReader;
27
28 import javax.xml.transform.Source;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.URIResolver;
31 import javax.xml.transform.sax.SAXSource;
32 import java.io.StringReader;
33 import java.util.ArrayList;
34 import java.util.Comparator;
35 import java.util.List;
36
37 /**
38 * A stylesheet module represents a module of a stylesheet. It is possible for two modules
39 * to share the same stylesheet tree in the case where two includes or imports reference
40 * the same URI; in this case the two modules will typically have a different import precedence.
41 */
42 public class StylesheetModule {
43
44 private StyleElement rootElement;
45 private int precedence;
46 private int minImportPrecedence;
47 private StylesheetModule importer;
48 boolean wasIncluded;
49
50
51 // the value of the inputTypeAnnotations attribute on this module, combined with the values
52 // on all imported/included modules. This is a combination of the bit-significant values
53 // ANNOTATION_STRIP and ANNOTATION_PRESERVE.
54 private int inputTypeAnnotations = 0;
55
56 // A list of all the declarations in the stylesheet and its descendants, in increasing precedence order
57 protected List<ComponentDeclaration> topLevel = new ArrayList<ComponentDeclaration>();
58
59 public StylesheetModule(StyleElement rootElement, int precedence) {
60 this.rootElement = rootElement;
61 this.precedence = precedence;
62 }
63
64 /**
65 * Build the tree representation of a stylesheet module
66 *
67 *
68 * @param styleSource the source of the module
69 * @param topLevelModule true if this module is the outermost module of a package
70 * @param compilation the XSLT compilation episode
71 * @param precedence the import precedence for static variables declared
72 * in the module. (This is handled differently from the precedence of other components
73 * because it needs to be allocated purely sequentially).
74 * @return the tree representation of the XML document containing the stylesheet module
75 * @throws net.sf.saxon.trans.XPathException
76 * if XML parsing or tree
77 * construction fails
78 */
79 public static DocumentImpl loadStylesheetModule(
80 Source styleSource, boolean topLevelModule, Compilation compilation, NestedIntegerValue precedence) throws XPathException {
81 String systemId = styleSource.getSystemId();
82 DocumentURI docURI = systemId == null ? null : new DocumentURI(systemId);
83 if (systemId != null && compilation.getImportStack().contains(docURI)) {
84 throw new XPathException("The stylesheet module includes/imports itself directly or indirectly", "XTSE0180");
85 }
86 compilation.getImportStack().push(docURI);
87
88 Configuration config = compilation.getConfiguration();
89 PipelineConfiguration pipe = config.makePipelineConfiguration();
90 pipe.setErrorListener(compilation.getCompilerInfo().getErrorListener());
91 LinkedTreeBuilder styleBuilder = new LinkedTreeBuilder(pipe);
92 pipe.setURIResolver(compilation.getCompilerInfo().getURIResolver());
93 styleBuilder.setSystemId(styleSource.getSystemId());
94 //styleBuilder.freezeSystemIdAndBaseURI();
95 styleBuilder.setNodeFactory(compilation.getStyleNodeFactory(topLevelModule));
96 styleBuilder.setLineNumbering(true);
97
98 UseWhenFilter useWhenFilter = new UseWhenFilter(compilation, styleBuilder, precedence);
99 useWhenFilter.setSystemId(styleSource.getSystemId());
100 StartTagBuffer startTagBuffer = new StartTagBuffer(useWhenFilter);
101 useWhenFilter.setStartTagBuffer(startTagBuffer);
102
103 StylesheetSpaceStrippingRule rule = new StylesheetSpaceStrippingRule(config.getNamePool());
104 Stripper styleStripper = new Stripper(rule, startTagBuffer);
105 CommentStripper commentStripper = new CommentStripper(styleStripper);
106
107 // build the stylesheet document
108
109 DocumentImpl doc;
110
111 ParseOptions options = makeStylesheetParseOptions(styleSource, pipe);
112 try {
113 sendStylesheetSource(styleSource, config, commentStripper, options);
114 doc = (DocumentImpl)styleBuilder.getCurrentRoot();
115 styleBuilder.reset();
116 compilation.getImportStack().pop();
117 return doc;
118 } catch (XPathException err) {
119 if (topLevelModule && !err.hasBeenReported()) { // bug 2244
120 compilation.reportError(err);
121 }
122 throw err;
123 } finally {
124 if (options.isPleaseCloseAfterUse()) {
125 ParseOptions.close(styleSource);
126 }
127 }
128 }
129
130 /**
131 * Build the tree representation of a stylesheet module
132 *
133 * @param styleSource the source of the module. This must contain either XSLT source code
134 * of a top-level module (which may contains xsl:include, xsl:import, or
135 * xsl:use-package), or it must contain a package in export format. This method
136 * is not used when compiling subsidiary modules or library packages.
137 * @param compilation the XSLT compilation episode
138 * @return the tree representation of the XML document containing the stylesheet module
139 * @throws net.sf.saxon.trans.XPathException if XML parsing or tree
140 * construction fails
141 */
142 public static PreparedStylesheet loadStylesheet (
143 Source styleSource, Compilation compilation) throws XPathException {
144
145 if (styleSource instanceof SAXSource &&
146 compilation.getConfiguration().getBooleanProperty(Feature.IGNORE_SAX_SOURCE_PARSER)) {
147 // This option is provided to allow the parser set by applications such as Ant to be overridden by
148 // the parser requested using FeatureKeys.SOURCE_PARSER
149 ((SAXSource) styleSource).setXMLReader(null);
150 }
151
152 String systemId = styleSource.getSystemId();
153 DocumentURI docURI = systemId == null ? null : new DocumentURI(systemId);
154 if (systemId != null && compilation.getImportStack().contains(docURI)) {
155 throw new XPathException("The stylesheet module includes/imports itself directly or indirectly", "XTSE0180");
156 }
157 compilation.getImportStack().push(docURI);
158 compilation.setMinimalPackageData();
159
160 Configuration config = compilation.getConfiguration();
161 PipelineConfiguration pipe = config.makePipelineConfiguration();
162 pipe.setErrorListener(compilation.getCompilerInfo().getErrorListener());
163
164 LinkedTreeBuilder styleBuilder = new LinkedTreeBuilder(pipe);
165 pipe.setURIResolver(compilation.getCompilerInfo().getURIResolver());
166 styleBuilder.setSystemId(styleSource.getSystemId());
167 //styleBuilder.freezeSystemIdAndBaseURI();
168 styleBuilder.setNodeFactory(compilation.getStyleNodeFactory(true));
169 styleBuilder.setLineNumbering(true);
170
171 // Pipeline for source XSLT code
172
173 Receiver sourcePipeline;
174
175 UseWhenFilter useWhenFilter = new UseWhenFilter(compilation, styleBuilder, NestedIntegerValue.TWO);
176 useWhenFilter.setSystemId(styleSource.getSystemId());
177 StartTagBuffer startTagBuffer = new StartTagBuffer(useWhenFilter);
178 useWhenFilter.setStartTagBuffer(startTagBuffer);
179
180 StylesheetSpaceStrippingRule rule = new StylesheetSpaceStrippingRule(config.getNamePool());
181 Stripper styleStripper = new Stripper(rule, startTagBuffer);
182 CommentStripper commentStripper = new CommentStripper(styleStripper);
183
184 // Pipeline for compiled XSLT code
185
186 TinyBuilder packageBuilder = new TinyBuilder(pipe);
187 packageBuilder.setSystemId(styleSource.getSystemId());
188 CheckSumFilter checksummer = new CheckSumFilter(packageBuilder);
189 checksummer.setCheckExistingChecksum(true);
190
191 Valve valve = new Valve(NamespaceConstant.SAXON_XSLT_EXPORT, commentStripper, checksummer);
192 sourcePipeline = valve;
193
194 // build the stylesheet document
195
196 ParseOptions options;
197 options = makeStylesheetParseOptions(styleSource, pipe);
198 try {
199 sendStylesheetSource(styleSource, config, sourcePipeline, options);
200
201 NodeInfo doc;
202 if (valve.wasDiverted()) {
203 // Implies we have loaded a pre-compiled package
204 if (!checksummer.isChecksumCorrect()) {
205 throw new XPathException("Compiled package cannot be loaded: incorrect checksum");
206 }
207 IPackageLoader loader = config.makePackageLoader();
208 StylesheetPackage pack = loader.loadPackageDoc(packageBuilder.getCurrentRoot());
209 compilation.setPackageData(pack);
210 PreparedStylesheet pss = new PreparedStylesheet(compilation);
211 pack.checkForAbstractComponents();
212 pack.updatePreparedStylesheet(pss);
213 //pss.addPackage(compilation.getPackageData());
214 return pss;
215 } else {
216 // We loaded source XSLT (could be xsl:package or xsl:stylesheet or an LRE...
217 doc = styleBuilder.getCurrentRoot();
218 styleBuilder.reset();
219 compilation.getImportStack().pop();
220
221 PreparedStylesheet pss = new PreparedStylesheet(compilation);
222 PrincipalStylesheetModule psm = compilation.compilePackage(doc);
223 if (compilation.getErrorCount() > 0) {
224 XPathException e = new XPathException("Errors were reported during stylesheet compilation");
225 e.setHasBeenReported(true); // only intended as an exception message, not something to report to ErrorListener
226 throw e;
227 }
228 psm.getStylesheetPackage().checkForAbstractComponents();
229 psm.getStylesheetPackage().updatePreparedStylesheet(pss);
230 pss.addPackage(compilation.getPackageData());
231 return pss;
232
233 }
234 } catch (XPathException err) {
235 if (!err.hasBeenReported()) { // bug 2244
236 compilation.reportError(err);
237 }
238 throw err;
239 } finally {
240 if (options.isPleaseCloseAfterUse()) {
241 ParseOptions.close(styleSource);
242 }
243 }
244 }
245
246 @NotNull
247 private static ParseOptions makeStylesheetParseOptions(Source styleSource, PipelineConfiguration pipe) {
248 ParseOptions options;
249 if (styleSource instanceof AugmentedSource) {
250 options = ((AugmentedSource) styleSource).getParseOptions();
251 } else {
252 options = new ParseOptions();
253 }
254 options.setSchemaValidationMode(Validation.STRIP);
255 options.setDTDValidationMode(Validation.STRIP);
256 options.setLineNumbering(true);
257 options.setSpaceStrippingRule(NoElementsSpaceStrippingRule.getInstance());
258 options.setErrorListener(pipe.getErrorListener());
259 return options;
260 }
261
262
263 private static void sendStylesheetSource(Source styleSource, Configuration config, Receiver sourcePipeline, ParseOptions options) throws XPathException {
264 boolean knownParser =
265 options.getXMLReader() != null ||
266 options.getXMLReaderMaker() != null ||
267 (styleSource instanceof SAXSource && ((SAXSource) styleSource).getXMLReader() != null);
268
269 if (knownParser) {
270 Sender.send(styleSource, sourcePipeline, options);
271 } else {
272 XMLReader styleParser = config.getStyleParser();
273 options.setXMLReader(styleParser);
274 Sender.send(styleSource, sourcePipeline, options);
275 config.reuseStyleParser(styleParser);
276 }
277 }
278
279 /**
280 * Get the stylesheet specification(s) associated
281 * via the xml-stylesheet processing instruction (see
282 * http://www.w3.org/TR/xml-stylesheet/) with the document
283 * document specified in the source parameter, and that match
284 * the given criteria. Note that it is possible to return several
285 * stylesheets, in which case they are applied as if they were
286 * a list of imports or cascades.
287 *
288 * @param config The Saxon Configuration
289 * @param source The XML source document.
290 * @param media The media attribute to be matched. May be null, in which
291 * case the prefered templates will be used (i.e. alternate = no).
292 * Note that Saxon does not implement the complex CSS3-based syntax for
293 * media queries. By default, the media value is simply ignored. An algorithm for
294 * comparing the requested media with the declared media can be defined using
295 * the method {@link Configuration#setMediaQueryEvaluator(Comparator)}.
296 * @param title The value of the title attribute to match. May be null.
297 * @param charset The value of the charset attribute to match. May be null.
298 * @return A Source object suitable for passing to the TransformerFactory.
299 * @throws net.sf.saxon.trans.XPathException
300 * if any problems occur
301 */
302
303
304 public static Source getAssociatedStylesheet(
305 Configuration config, URIResolver resolver, Source source, String media, String title, String charset)
306 throws XPathException {
307 PIGrabber grabber = new PIGrabber(new Sink(config.makePipelineConfiguration()));
308 grabber.setFactory(config);
309 grabber.setCriteria(media, title);
310 grabber.setBaseURI(source.getSystemId());
311 grabber.setURIResolver(resolver);
312
313 try {
314 Sender.send(source, grabber, null);
315 // this parse will be aborted when the first start tag is found
316 } catch (XPathException err) {
317 if (grabber.isTerminated()) {
318 // do nothing
319 } else {
320 throw new XPathException(
321 "Failed while looking for xml-stylesheet PI", err);
322 }
323 }
324
325 try {
326 Source[] sources = grabber.getAssociatedStylesheets();
327 if (sources == null) {
328 throw new XPathException(
329 "No matching <?xml-stylesheet?> processing instruction found");
330 }
331 return compositeStylesheet(config, source.getSystemId(), sources);
332 } catch (TransformerException err) {
333 if (err instanceof XPathException) {
334 throw (XPathException) err;
335 } else {
336 throw new XPathException(err);
337 }
338 }
339 }
340
341 /**
342 * Process a series of stylesheet inputs, treating them in import or cascade
343 * order. This is mainly for support of the getAssociatedStylesheets
344 * method, but may be useful for other purposes.
345 *
346 * @param config the Saxon configuration
347 * @param baseURI the base URI to be used for the synthesized composite stylesheet
348 * @param sources An array of Source objects representing individual stylesheets.
349 * @return A Source object representing a composite stylesheet.
350 * @throws XPathException if there is a static error in the stylesheet
351 */
352
353 private static Source compositeStylesheet(Configuration config, String baseURI, Source[] sources)
354 throws XPathException {
355
356 if (sources.length == 1) {
357 return sources[0];
358 } else if (sources.length == 0) {
359 throw new XPathException(
360 "No stylesheets were supplied");
361 }
362
363 // create a new top-level stylesheet that imports all the others
364
365 StringBuilder sb = new StringBuilder(250);
366 sb.append("<xsl:stylesheet version='1.0' ");
367 sb.append(" xmlns:xsl='" + NamespaceConstant.XSLT + "'>");
368 for (Source source : sources) {
369 sb.append("<xsl:import href='").append(source.getSystemId()).append("'/>");
370 }
371 sb.append("</xsl:stylesheet>");
372 InputSource composite = new InputSource();
373 composite.setSystemId(baseURI);
374 composite.setCharacterStream(new StringReader(sb.toString()));
375 return new SAXSource(config.getStyleParser(), composite);
376 }
377
378 public void setImporter(StylesheetModule importer) {
379 this.importer = importer;
380 }
381
382 public StylesheetModule getImporter() {
383 return importer;
384 }
385
386 /*@NotNull*/
387 public PrincipalStylesheetModule getPrincipalStylesheetModule() {
388 return importer.getPrincipalStylesheetModule();
389 }
390
391 public StyleElement getRootElement() {
392 return rootElement;
393 }
394
395 public XSLModuleRoot getStylesheetElement() {
396 return (XSLModuleRoot) rootElement;
397 }
398
399 public Configuration getConfiguration() {
400 return rootElement.getConfiguration();
401 }
402
403 public int getPrecedence() {
404 return wasIncluded ? importer.getPrecedence() : precedence;
405 }
406
407 /**
408 * Indicate that this stylesheet was included (by its "importer") using an xsl:include
409 * statement as distinct from xsl:import
410 */
411
412 public void setWasIncluded() {
413 wasIncluded = true;
414 }
415
416 /**
417 * Set the minimum import precedence of this module, that is, the lowest import precedence of the modules
418 * that it imports. This information is used to decide which template rules are eligible for consideration
419 * by xsl:apply-imports
420 *
421 * @param min the minimum import precedence
422 */
423
424 public void setMinImportPrecedence(int min) {
425 this.minImportPrecedence = min;
426 }
427
428 /**
429 * Get the minimum import precedence of this module, that is, the lowest import precedence of the modules
430 * that it imports. This information is used to decide which template rules are eligible for consideration
431 * by xsl:apply-imports
432 *
433 * @return the minimum import precedence
434 */
435
436 public int getMinImportPrecedence() {
437 return this.minImportPrecedence;
438 }
439
440 /**
441 * Process xsl:include and xsl:import elements.
442 *
443 * @throws XPathException if the included/imported module is invalid
444 */
445
446 public void spliceIncludes() throws XPathException {
447
448 boolean foundNonImport = false;
449 if (topLevel == null || topLevel.size() == 0) {
450 topLevel = new ArrayList<ComponentDeclaration>(50);
451 }
452 minImportPrecedence = precedence;
453 StyleElement previousElement = rootElement;
454
455 AxisIterator kids = getStylesheetElement().iterateAxis(AxisInfo.CHILD);
456
457 NodeInfo child;
458 while ((child = kids.next()) != null) {
459 if (child.getNodeKind() == Type.TEXT) {
460 // in an embedded stylesheet, white space nodes may still be there
461 if (!Whitespace.isWhite(child.getStringValueCS())) {
462 previousElement.compileError(
463 "No character data is allowed between top-level elements", "XTSE0120");
464 }
465
466 } else if (child instanceof DataElement) {
467 foundNonImport = true;
468 } else {
469 previousElement = (StyleElement) child;
470 if (child instanceof XSLGeneralIncorporate) {
471 XSLGeneralIncorporate xslinc = (XSLGeneralIncorporate) child;
472 xslinc.processAttributes();
473
474 if (!xslinc.isImport()) {
475 foundNonImport = true;
476 }
477
478 // get the included stylesheet. This follows the URL, builds a tree, and splices
479 // in any indirectly-included stylesheets.
480
481 xslinc.validateInstruction();
482 int errors = ((XSLGeneralIncorporate) child).getCompilation().getErrorCount();
483 StylesheetModule inc =
484 xslinc.getIncludedStylesheet(this, precedence);
485 if (inc == null) {
486 return; // error has been reported
487 }
488 errors = ((XSLGeneralIncorporate) child).getCompilation().getErrorCount() - errors;
489 if (errors > 0) {
490 xslinc.compileError("Reported " + errors + (errors == 1 ? " error" : " errors") +
491 " in " + (xslinc.isImport() ? "imported" : "included") +
492 " stylesheet module", "XTSE0165");
493 }
494
495 // after processing the imported stylesheet and any others it brought in,
496 // adjust the import precedence of this stylesheet if necessary
497
498 if (xslinc.isImport()) {
499 precedence = inc.getPrecedence() + 1;
500 } else {
501 precedence = inc.getPrecedence();
502 inc.setMinImportPrecedence(minImportPrecedence);
503 inc.setWasIncluded();
504 }
505
506 // copy the top-level elements of the included stylesheet into the top level of this
507 // stylesheet. Normally we add these elements at the end, in order, but if the precedence
508 // of an element is less than the precedence of the previous element, we promote it.
509 // This implements the requirement in the spec that when xsl:include is used to
510 // include a stylesheet, any xsl:import elements in the included document are moved
511 // up in the including document to after any xsl:import elements in the including
512 // document.
513
514 List<ComponentDeclaration> incchildren = inc.topLevel;
515 for (ComponentDeclaration decl : incchildren) {
516 int last = topLevel.size() - 1;
517 if (last < 0 || decl.getPrecedence() >= topLevel.get(last).getPrecedence()) {
518 topLevel.add(decl);
519 } else {
520 while (last >= 0 && decl.getPrecedence() < topLevel.get(last).getPrecedence()) {
521 last--;
522 }
523 topLevel.add(last + 1, decl);
524 }
525 }
526 } else {
527 foundNonImport = true;
528 ComponentDeclaration decl = new ComponentDeclaration(this, (StyleElement) child);
529 topLevel.add(decl);
530 }
531 }
532 }
533 }
534
535 /**
536 * Get the value of the input-type-annotations attribute, for this module combined with that
537 * of all included/imported modules. The value is an or-ed combination of the two bits
538 * {@link XSLModuleRoot#ANNOTATION_STRIP} and {@link XSLModuleRoot#ANNOTATION_PRESERVE}
539 *
540 * @return the value of the input-type-annotations attribute, for this module combined with that
541 * of all included/imported modules
542 */
543
544 public int getInputTypeAnnotations() {
545 return inputTypeAnnotations;
546 }
547
548 /**
549 * Set the value of the input-type-annotations attribute, for this module combined with that
550 * of all included/imported modules. The value is an or-ed combination of the two bits
551 * {@link XSLModuleRoot#ANNOTATION_STRIP} and {@link XSLModuleRoot#ANNOTATION_PRESERVE}
552 *
553 * @param annotations the value of the input-type-annotations attribute, for this module combined with that
554 * of all included/imported modules.
555 * @throws XPathException if the values of the attribute in different modules are inconsistent
556 */
557
558 public void setInputTypeAnnotations(int annotations) throws XPathException {
559 inputTypeAnnotations |= annotations;
560 if (inputTypeAnnotations == (XSLModuleRoot.ANNOTATION_STRIP | XSLModuleRoot.ANNOTATION_PRESERVE)) {
561 getPrincipalStylesheetModule().compileError(
562 "One stylesheet module specifies input-type-annotations='strip', " +
563 "another specifies input-type-annotations='preserve'", "XTSE0265");
564 }
565 if (annotations == XSLModuleRoot.ANNOTATION_STRIP) {
566 getPrincipalStylesheetModule().getStylesheetPackage().setStripsTypeAnnotations(true);
567 }
568 }
569
570
571 }
572