| 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; |
| 9 | |
| 10 | import net.sf.saxon.event.*; |
| 11 | import net.sf.saxon.expr.ContextOriginator; |
| 12 | import net.sf.saxon.expr.PackageData; |
| 13 | import net.sf.saxon.expr.XPathContext; |
| 14 | import net.sf.saxon.expr.XPathContextMajor; |
| 15 | import net.sf.saxon.expr.instruct.Bindery; |
| 16 | import net.sf.saxon.expr.instruct.Executable; |
| 17 | import net.sf.saxon.expr.instruct.GlobalParameterSet; |
| 18 | import net.sf.saxon.expr.instruct.GlobalVariable; |
| 19 | import net.sf.saxon.expr.parser.Location; |
| 20 | import net.sf.saxon.expr.parser.PathMap; |
| 21 | import net.sf.saxon.expr.sort.GroupIterator; |
| 22 | import net.sf.saxon.functions.AccessorFn; |
| 23 | import net.sf.saxon.lib.*; |
| 24 | import net.sf.saxon.om.*; |
| 25 | import net.sf.saxon.regex.RegexIterator; |
| 26 | import net.sf.saxon.resource.CollectionURIResolverWrapper; |
| 27 | import net.sf.saxon.trace.TraceEventMulticaster; |
| 28 | import net.sf.saxon.trans.*; |
| 29 | import net.sf.saxon.trans.rules.RuleManager; |
| 30 | import net.sf.saxon.tree.tiny.TinyBuilder; |
| 31 | import net.sf.saxon.tree.wrapper.SpaceStrippedDocument; |
| 32 | import net.sf.saxon.tree.wrapper.SpaceStrippedNode; |
| 33 | import net.sf.saxon.tree.wrapper.TypeStrippedDocument; |
| 34 | import net.sf.saxon.type.Type; |
| 35 | import net.sf.saxon.type.Untyped; |
| 36 | import net.sf.saxon.value.DateTimeValue; |
| 37 | import net.sf.saxon.value.SequenceType; |
| 38 | import net.sf.saxon.z.IntHashMap; |
| 39 | |
| 40 | import javax.xml.transform.ErrorListener; |
| 41 | import javax.xml.transform.Source; |
| 42 | import javax.xml.transform.Transformer; |
| 43 | import javax.xml.transform.URIResolver; |
| 44 | import javax.xml.transform.sax.SAXSource; |
| 45 | import java.net.URI; |
| 46 | import java.net.URISyntaxException; |
| 47 | import java.util.HashMap; |
| 48 | import java.util.HashSet; |
| 49 | import java.util.Map; |
| 50 | import java.util.Set; |
| 51 | import java.util.function.Function; |
| 52 | |
| 53 | import static net.sf.saxon.om.SequenceIterator.GROUNDED; |
| 54 | |
| 55 | /** |
| 56 | * The Controller underpins Saxon's implementation of the JAXP Transformer class, and represents |
| 57 | * an executing instance of a transformation or query. Multiple concurrent executions of |
| 58 | * the same transformation or query will use different Controller instances. This class is |
| 59 | * therefore not thread-safe. |
| 60 | * <p>The Controller is serially reusable: when one transformation or query |
| 61 | * is finished, it can be used to run another. However, there is no advantage in doing this |
| 62 | * rather than allocating a new Controller each time.</p> |
| 63 | * <p> A dummy Controller is created when running free-standing XPath expressions.</p> |
| 64 | * <p>The Controller holds those parts of the dynamic context that do not vary during the course |
| 65 | * of a transformation or query, or that do not change once their value has been computed. |
| 66 | * This also includes those parts of the static context that are required at run-time.</p> |
| 67 | * <p>Many methods on the Controller are designed for internal use and should not be |
| 68 | * considered stable. From release 8.4 onwards, those methods that are considered sufficiently |
| 69 | * stable to constitute path of the Saxon public API are labelled with the JavaDoc tag "since": |
| 70 | * the value indicates the release at which the method was added to the public API.</p> |
| 71 | * <p>Prior to Saxon 9.6 the Controller implemented (extended) the JAXP {@link Transformer} |
| 72 | * interface, and advanced applications were able to down-cast the Transformer to a Controller. |
| 73 | * This is no longer the case. Instead, the JAXP factory delivers an instance of {@link net.sf.saxon.jaxp.TransformerImpl}, |
| 74 | * from which the Controller is accessible if required. Because the Controller is no longer required |
| 75 | * to implement the JAXP interface, it has been possible to make it less monolithic, so some of the |
| 76 | * things it did are now done elsewhere: for example, it no longer handles global parameters</p> |
| 77 | * |
| 78 | * @author Michael H. Kay |
| 79 | * @since 8.4. From 9.6 this class should no longer be considered a public API. In 9.9, the class |
| 80 | * was split into two: XSLT-specific functionality has been moved into the subclass {@link XsltController}. |
| 81 | */ |
| 82 | |
| 83 | public class Controller implements ContextOriginator { |
| 84 | |
| 85 | private Configuration config; |
| 86 | protected Executable executable; |
| 87 | |
| 88 | protected Item<?> globalContextItem; |
| 89 | private boolean globalContextItemPreset; |
| 90 | private Map<PackageData, Bindery> binderies; |
| 91 | private GlobalParameterSet globalParameters; |
| 92 | private boolean convertParameters = true; |
| 93 | private Map<GlobalVariable, Set<GlobalVariable>> globalVariableDependencies = new HashMap<>(); |
| 94 | protected TraceListener traceListener; |
| 95 | private boolean tracingPaused; |
| 96 | private Logger traceFunctionDestination; |
| 97 | private URIResolver standardURIResolver; |
| 98 | private URIResolver userURIResolver; |
| 99 | protected Receiver principalResult; |
| 100 | protected String principalResultURI; |
| 101 | private UnparsedTextURIResolver unparsedTextResolver; |
| 102 | private String defaultCollectionURI; |
| 103 | protected UnfailingErrorListener errorListener; |
| 104 | private TreeModel treeModel = TreeModel.TINY_TREE; |
| 105 | private DocumentPool sourceDocumentPool; |
| 106 | private IntHashMap<Map<Long, KeyIndex>> localIndexes; |
| 107 | private HashMap<String, Object> userDataTable; |
| 108 | private NodeInfo lastRememberedNode = null; |
| 109 | private int lastRememberedNumber = -1; |
| 110 | private DateTimeValue currentDateTime; |
| 111 | private boolean dateTimePreset = false; |
| 112 | private PathMap pathMap = null; |
| 113 | protected int validationMode = Validation.DEFAULT; |
| 114 | protected boolean inUse = false; |
| 115 | private boolean stripSourceTrees = true; |
| 116 | //protected boolean buildTree = true; |
| 117 | private CollectionFinder collectionFinder = null; |
| 118 | |
| 119 | public final static String ANONYMOUS_PRINCIPAL_OUTPUT_URI = "dummy:/anonymous/principal/result"; |
| 120 | private StylesheetCache stylesheetCache = null; |
| 121 | |
| 122 | private Function<SequenceIterator<?>, FocusTrackingIterator<?>> focusTrackerFactory = FocusTrackingIterator::new; |
| 123 | |
| 124 | private Function<SequenceIterator<?>, FocusTrackingIterator<?>> multiThreadedFocusTrackerFactory; |
| 125 | |
| 126 | /** |
| 127 | * Create a Controller and initialise variables. Note: XSLT applications should |
| 128 | * create the Controller by using the JAXP newTransformer() method, or in S9API |
| 129 | * by using XsltExecutable.load() |
| 130 | * |
| 131 | * @param config The Configuration used by this Controller |
| 132 | */ |
| 133 | |
| 134 | public Controller(Configuration config) { |
| 135 | this.config = config; |
| 136 | // create a dummy executable |
| 137 | executable = new Executable(config); |
| 138 | sourceDocumentPool = new DocumentPool(); |
| 139 | reset(); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Create a Controller and initialise variables. |
| 144 | * |
| 145 | * @param config The Configuration used by this Controller |
| 146 | * @param executable The executable used by this Controller |
| 147 | */ |
| 148 | |
| 149 | public Controller(Configuration config, Executable executable) { |
| 150 | this.config = config; |
| 151 | this.executable = executable; |
| 152 | sourceDocumentPool = new DocumentPool(); |
| 153 | reset(); |
| 154 | } |
| 155 | |
| 156 | /** |
| 157 | * <p>Reset this <code>Transformer</code> to its original configuration.</p> |
| 158 | * <p><code>Transformer</code> is reset to the same state as when it was created with |
| 159 | * {@link javax.xml.transform.TransformerFactory#newTransformer()}, |
| 160 | * {@link javax.xml.transform.TransformerFactory#newTransformer(javax.xml.transform.Source source)} or |
| 161 | * {@link javax.xml.transform.Templates#newTransformer()}. |
| 162 | * <code>reset()</code> is designed to allow the reuse of existing <code>Transformer</code>s |
| 163 | * thus saving resources associated with the creation of new <code>Transformer</code>s.</p> |
| 164 | * <p><i>The above is from the JAXP specification. With Saxon, it's unlikely that reusing a Transformer will |
| 165 | * give any performance benefits over creating a new one. The one case where it might be beneficial is |
| 166 | * to reuse the document pool (the set of documents that have been loaded using the doc() or document() |
| 167 | * functions). Therefore, this method does not clear the document pool. If you want to clear the document |
| 168 | * pool, call the method {@link #clearDocumentPool} as well.</i></p> |
| 169 | * <p>The reset <code>Transformer</code> is not guaranteed to have the same {@link javax.xml.transform.URIResolver} |
| 170 | * or {@link javax.xml.transform.ErrorListener} <code>Object</code>s, e.g. {@link Object#equals(Object obj)}. |
| 171 | * It is guaranteed to have a functionally equal <code>URIResolver</code> |
| 172 | * and <code>ErrorListener</code>.</p> |
| 173 | * |
| 174 | * @since 1.5 |
| 175 | */ |
| 176 | |
| 177 | public void reset() { |
| 178 | globalParameters = new GlobalParameterSet(); |
| 179 | focusTrackerFactory = config.getFocusTrackerFactory(executable, false); |
| 180 | multiThreadedFocusTrackerFactory = config.getFocusTrackerFactory(executable, true); |
| 181 | standardURIResolver = config.getSystemURIResolver(); |
| 182 | userURIResolver = config.getURIResolver(); |
| 183 | unparsedTextResolver = config.getUnparsedTextURIResolver(); |
| 184 | setErrorListener(config.getErrorListener()); |
| 185 | validationMode = config.getSchemaValidationMode(); |
| 186 | if (errorListener instanceof StandardErrorListener) { |
| 187 | // if using a standard error listener, make a fresh one |
| 188 | // for each transformation, because it is stateful - and also because the |
| 189 | // host language is now known (a Configuration can serve multiple host languages) |
| 190 | Logger ps = ((StandardErrorListener) errorListener).getLogger(); |
| 191 | errorListener = ((StandardErrorListener) errorListener).makeAnother(executable.getHostLanguage()); |
| 192 | ((StandardErrorListener) errorListener).setLogger(ps); |
| 193 | } |
| 194 | |
| 195 | traceListener = null; |
| 196 | traceFunctionDestination = config.getLogger(); |
| 197 | TraceListener tracer; |
| 198 | try { |
| 199 | tracer = config.makeTraceListener(); |
| 200 | } catch (XPathException err) { |
| 201 | throw new IllegalStateException(err.getMessage()); |
| 202 | } |
| 203 | if (tracer != null) { |
| 204 | addTraceListener(tracer); |
| 205 | } |
| 206 | |
| 207 | setModel(config.getParseOptions().getModel()); |
| 208 | |
| 209 | globalContextItem = null; |
| 210 | currentDateTime = null; |
| 211 | dateTimePreset = false; |
| 212 | clearPerTransformationData(); |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * Reset variables that need to be reset for each transformation if the controller |
| 217 | * is serially reused |
| 218 | */ |
| 219 | |
| 220 | protected synchronized void clearPerTransformationData() { |
| 221 | userDataTable = new HashMap<>(20); |
| 222 | principalResult = null; |
| 223 | tracingPaused = false; |
| 224 | lastRememberedNode = null; |
| 225 | lastRememberedNumber = -1; |
| 226 | stylesheetCache = null; |
| 227 | localIndexes = null; |
| 228 | if (!globalContextItemPreset) { |
| 229 | globalContextItem = null; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Get the Configuration associated with this Controller. The Configuration holds |
| 235 | * settings that potentially apply globally to many different queries and transformations. |
| 236 | * |
| 237 | * @return the Configuration object |
| 238 | * @since 8.4 |
| 239 | */ |
| 240 | public Configuration getConfiguration() { |
| 241 | return config; |
| 242 | } |
| 243 | |
| 244 | /** |
| 245 | * Get the value of a supplied parameter (XSLT) or external variable (XQuery) |
| 246 | * |
| 247 | * @param name the QName of the parameter |
| 248 | * @return the supplied value of the parameter, if such a parameter exists, and if a value |
| 249 | * was supplied. Returns null if the parameter is not declared or if no value was supplied, |
| 250 | * even if there is a default defined in the stylesheet or query. |
| 251 | */ |
| 252 | |
| 253 | public Sequence<?> getParameter(StructuredQName name) { |
| 254 | return globalParameters.get(name); |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * Get the value of a parameter, converted and/or type-checked |
| 259 | * |
| 260 | * @param name the name of the stylesheet parameter (XSLT) or external variable (XQuery) |
| 261 | * @param requiredType the declared type of the parameter |
| 262 | * @param context the dynamic evaluation context |
| 263 | * @return the parameter value if defined, or null otherwise. If the option |
| 264 | * {@link #setApplyFunctionConversionRulesToExternalVariables(boolean)}} is set, the supplied |
| 265 | * value is converted to the required type. Otherwise, the supplied value is checked |
| 266 | * against the required type. |
| 267 | */ |
| 268 | |
| 269 | public GroundedValue<?> getConvertedParameter(StructuredQName name, SequenceType requiredType, XPathContext context) |
| 270 | throws XPathException { |
| 271 | GroundedValue<?> val = |
| 272 | globalParameters.convertParameterValue(name, requiredType, convertParameters, context); |
| 273 | if (val != null) { |
| 274 | |
| 275 | // Check that any nodes belong to the right configuration |
| 276 | |
| 277 | Configuration config = getConfiguration(); |
| 278 | SequenceIterator iter = val.iterate(); |
| 279 | Item next; |
| 280 | while ((next = iter.next()) != null) { |
| 281 | if (next instanceof NodeInfo && !config.isCompatible(((NodeInfo) next).getConfiguration())) { |
| 282 | throw new XPathException("A node supplied in a global parameter must be built using the same Configuration " + |
| 283 | "that was used to compile the stylesheet or query", SaxonErrorCode.SXXP0004); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | // If the supplied value is a document node, and the document node has a systemID that is an absolute |
| 288 | // URI, and the absolute URI does not already exist in the document pool, then register it in the document |
| 289 | // pool, so that the document-uri() function will find it there, and so that a call on doc() will not |
| 290 | // reload it. |
| 291 | |
| 292 | if (val instanceof NodeInfo && ((NodeInfo) val).getNodeKind() == Type.DOCUMENT) { |
| 293 | String systemId = ((NodeInfo) val).getRoot().getSystemId(); |
| 294 | try { |
| 295 | if (systemId != null && new URI(systemId).isAbsolute()) { |
| 296 | DocumentPool pool = getDocumentPool(); |
| 297 | if (pool.find(systemId) == null) { |
| 298 | pool.add(((NodeInfo) val).getTreeInfo(), systemId); |
| 299 | } |
| 300 | } |
| 301 | } catch (URISyntaxException err) { |
| 302 | // ignore it |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | val = val.materialize(); |
| 307 | } |
| 308 | return val; |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Set the base output URI. |
| 313 | * <p>This defaults to the system ID of the Result object for the principal output |
| 314 | * of the transformation if this is known; if it is not known, it defaults |
| 315 | * to the current directory.</p> |
| 316 | * <p> The base output URI is used for resolving relative URIs in the <code>href</code> attribute |
| 317 | * of the <code>xsl:result-document</code> instruction.</p> |
| 318 | * |
| 319 | * @param uri the base output URI |
| 320 | * @since 8.4 |
| 321 | */ |
| 322 | |
| 323 | public void setBaseOutputURI(String uri) { |
| 324 | principalResultURI = uri; |
| 325 | } |
| 326 | |
| 327 | /** |
| 328 | * Get the base output URI. |
| 329 | * <p>This returns the value set using the {@link #setBaseOutputURI} method. If no value has been set |
| 330 | * explicitly, then the method returns null if called before the transformation, or the computed |
| 331 | * default base output URI if called after the transformation.</p> |
| 332 | * <p> The base output URI is used for resolving relative URIs in the <code>href</code> attribute |
| 333 | * of the <code>xsl:result-document</code> instruction.</p> |
| 334 | * |
| 335 | * @return the base output URI |
| 336 | * @since 8.4 |
| 337 | */ |
| 338 | |
| 339 | /*@Nullable*/ |
| 340 | public String getBaseOutputURI() { |
| 341 | return principalResultURI; |
| 342 | } |
| 343 | |
| 344 | /** |
| 345 | * Get the principal result destination. |
| 346 | * <p>This method is intended for internal use only. It is typically called by Saxon during the course |
| 347 | * of a transformation, to discover the result that was supplied in the transform() call.</p> |
| 348 | * |
| 349 | * @return the Result object supplied as the principal result destination. |
| 350 | */ |
| 351 | |
| 352 | /*@Nullable*/ |
| 353 | public Receiver getPrincipalResult() { |
| 354 | return principalResult; |
| 355 | } |
| 356 | |
| 357 | |
| 358 | /** |
| 359 | * Allocate a SequenceOutputter for a new output destination. |
| 360 | * |
| 361 | * @param size the estimated size of the output sequence |
| 362 | * @return SequenceOutputter the allocated SequenceOutputter |
| 363 | */ |
| 364 | |
| 365 | /*@NotNull*/ |
| 366 | public synchronized SequenceOutputter allocateSequenceOutputter(int size) { |
| 367 | PipelineConfiguration pipe = makePipelineConfiguration(); |
| 368 | return new SequenceOutputter(pipe, size); |
| 369 | } |
| 370 | |
| 371 | /*@NotNull*/ |
| 372 | public synchronized SequenceOutputter allocateSequenceOutputter() { |
| 373 | PipelineConfiguration pipe = makePipelineConfiguration(); |
| 374 | return new SequenceOutputter(pipe, 20); |
| 375 | } |
| 376 | |
| 377 | /////////////////////////////////////////////////////////////////////////////// |
| 378 | |
| 379 | /** |
| 380 | * Make a PipelineConfiguration based on the properties of this Controller. |
| 381 | * <p>This interface is intended primarily for internal use, although it may be necessary |
| 382 | * for applications to call it directly if they construct pull or push pipelines.</p> |
| 383 | * |
| 384 | * @return a newly constructed PipelineConfiguration holding a reference to this |
| 385 | * Controller as well as other configuration information. |
| 386 | */ |
| 387 | |
| 388 | /*@NotNull*/ |
| 389 | public PipelineConfiguration makePipelineConfiguration() { |
| 390 | PipelineConfiguration pipe = config.makePipelineConfiguration(); |
| 391 | pipe.setURIResolver(userURIResolver == null ? standardURIResolver : userURIResolver); |
| 392 | pipe.getParseOptions().setSchemaValidationMode(validationMode); // added in 9.7 |
| 393 | pipe.getParseOptions().setErrorListener(errorListener); // added in 9.7.0.4 |
| 394 | pipe.setController(this); |
| 395 | final Executable executable = getExecutable(); |
| 396 | if (executable != null) { |
| 397 | // can be null for an IdentityTransformer |
| 398 | pipe.setHostLanguage(executable.getHostLanguage()); |
| 399 | } |
| 400 | return pipe; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Set the error listener. |
| 405 | * |
| 406 | * @param listener the ErrorListener to be used |
| 407 | */ |
| 408 | |
| 409 | public void setErrorListener(ErrorListener listener) { |
| 410 | if (listener instanceof UnfailingErrorListener) { |
| 411 | errorListener = (UnfailingErrorListener) listener; |
| 412 | } else { |
| 413 | errorListener = new DelegatingErrorListener(listener); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * Get the error listener. |
| 419 | * |
| 420 | * @return the ErrorListener in use. Note that this is not necessarily the ErrorListener that was supplied |
| 421 | * to the {@link #setErrorListener(ErrorListener)} method; if that was not an {@link UnfailingErrorListener}, |
| 422 | * it will have been wrapped in a {@link DelegatingErrorListener}, and it is the DelegatingErrorListener |
| 423 | * that this method returns. |
| 424 | */ |
| 425 | |
| 426 | public UnfailingErrorListener getErrorListener() { |
| 427 | return errorListener; |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Report a recoverable error. This is an XSLT concept: by default, such an error results in a warning |
| 432 | * message, and processing continues. In XQuery, however, there are no recoverable errors so a fatal |
| 433 | * error is reported. |
| 434 | * <p>This method is intended for internal use only.</p> |
| 435 | * |
| 436 | * @param err An exception holding information about the error |
| 437 | * @throws XPathException if the error listener decides not to |
| 438 | * recover from the error |
| 439 | */ |
| 440 | |
| 441 | public void recoverableError(XPathException err) throws XPathException { |
| 442 | if (executable.getHostLanguage() == Configuration.XQUERY) { |
| 443 | throw err; |
| 444 | } else if (executable.getHostLanguage() == Configuration.XSLT) { |
| 445 | errorListener.warning(err); |
| 446 | } else { |
| 447 | errorListener.error(err); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /** |
| 452 | * Report a fatal error |
| 453 | * |
| 454 | * @param err the error to be reported |
| 455 | */ |
| 456 | |
| 457 | public void reportFatalError(XPathException err) { |
| 458 | if (!err.hasBeenReported()) { |
| 459 | if (err.getHostLanguage() == null) { |
| 460 | if (executable.getHostLanguage() == Configuration.XSLT) { |
| 461 | err.setHostLanguage("XSLT"); |
| 462 | } else if (executable.getHostLanguage() == Configuration.XQUERY) { |
| 463 | err.setHostLanguage("XQuery"); |
| 464 | } |
| 465 | } |
| 466 | getErrorListener().fatalError(err); |
| 467 | err.setHasBeenReported(true); |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /** |
| 472 | * Report a run-time warning |
| 473 | * |
| 474 | * @param message the warning message |
| 475 | * @param errorCode the local part of the error code (in the ERR namespace). May be null. |
| 476 | * @param locator the location in the source code. May be null. |
| 477 | */ |
| 478 | |
| 479 | public void warning(String message, String errorCode, Location locator) { |
| 480 | getErrorListener().warning(new XPathException(message, errorCode, locator)); |
| 481 | } |
| 482 | |
| 483 | |
| 484 | ///////////////////////////////////////////////////////////////////////////////////////// |
| 485 | // Methods for managing the various runtime control objects |
| 486 | ///////////////////////////////////////////////////////////////////////////////////////// |
| 487 | |
| 488 | |
| 489 | /** |
| 490 | * Get the Executable object. |
| 491 | * <p>This method is intended for internal use only.</p> |
| 492 | * |
| 493 | * @return the Executable (which represents the compiled stylesheet) |
| 494 | */ |
| 495 | |
| 496 | public Executable getExecutable() { |
| 497 | return executable; |
| 498 | } |
| 499 | |
| 500 | /** |
| 501 | * Get the document pool. This is used only for source documents, not for stylesheet modules. |
| 502 | * <p>This method is intended for internal use only.</p> |
| 503 | * |
| 504 | * @return the source document pool |
| 505 | */ |
| 506 | |
| 507 | public DocumentPool getDocumentPool() { |
| 508 | return sourceDocumentPool; |
| 509 | } |
| 510 | |
| 511 | /** |
| 512 | * Clear the document pool. |
| 513 | * This is sometimes useful when re-using the same Transformer |
| 514 | * for a sequence of transformations, but it isn't done automatically, because when |
| 515 | * the transformations use common look-up documents, the caching is beneficial. |
| 516 | */ |
| 517 | |
| 518 | public void clearDocumentPool() { |
| 519 | for (PackageData pack : getExecutable().getPackages()) { |
| 520 | sourceDocumentPool.discardIndexes(pack.getKeyManager()); |
| 521 | } |
| 522 | sourceDocumentPool = new DocumentPool(); |
| 523 | } |
| 524 | |
| 525 | /** |
| 526 | * Get the bindery for the global variables in a particular package. |
| 527 | * <p>This method is intended for internal use only.</p> |
| 528 | * |
| 529 | * @param packageData the package for which the variables are required |
| 530 | * @return the Bindery (in which values of all variables for the requested package are held) |
| 531 | */ |
| 532 | |
| 533 | public synchronized Bindery getBindery(PackageData packageData) { |
| 534 | Bindery b = binderies.get(packageData); |
| 535 | if (b == null) { |
| 536 | b = new Bindery(packageData); |
| 537 | binderies.put(packageData, b); |
| 538 | } |
| 539 | return b; |
| 540 | } |
| 541 | |
| 542 | /** |
| 543 | * Set the item used as the context for evaluating global variables. This value is used |
| 544 | * as the global context item by XQuery, XSLT and XPath. |
| 545 | * |
| 546 | * @param contextItem the context item for evaluating global variables, or null if there is none |
| 547 | * @throws XPathException if the supplied context item is a node, and if it (a) does not belong |
| 548 | * to the right Configuration, or (b) is schema-validated, when the stylesheet or query is |
| 549 | * not compiled with schema-awareness enabled |
| 550 | * @since 9.7. Changed in 9.9 to raise an exception if the context item is inappropriate. |
| 551 | */ |
| 552 | |
| 553 | public void setGlobalContextItem(Item contextItem) throws XPathException { |
| 554 | setGlobalContextItem(contextItem, false); |
| 555 | } |
| 556 | |
| 557 | /** |
| 558 | * Set the item used as the context for evaluating global variables. This value is used |
| 559 | * as the global context item by XQuery, XSLT, and XPath. |
| 560 | * |
| 561 | * @param contextItem the context item for evaluating global variables, or null if there is none |
| 562 | * @param alreadyStripped true if any stripping of type annotations or whitespace text node specified |
| 563 | * in the stylesheet has already been carried out |
| 564 | * @throws XPathException if the supplied context item is a node, and if it (a) does not belong |
| 565 | * to the right Configuration, or (b) is schema-validated, when the stylesheet or query is |
| 566 | * not compiled with schema-awareness enabled |
| 567 | * @since 9.7. Changed in 9.9 to raise an exception if the context item is inappropriate. |
| 568 | */ |
| 569 | |
| 570 | public void setGlobalContextItem(Item contextItem, boolean alreadyStripped) throws XPathException { |
| 571 | if (!alreadyStripped) { |
| 572 | // Bug 2929 - don't do space-stripping twice |
| 573 | if (globalContextItem instanceof SpaceStrippedNode && ((SpaceStrippedNode) globalContextItem).getUnderlyingNode() == contextItem) { |
| 574 | return; |
| 575 | } |
| 576 | if (contextItem instanceof NodeInfo) { |
| 577 | // In XSLT, apply strip-space and strip-type-annotations options |
| 578 | contextItem = prepareInputTree((NodeInfo) contextItem); |
| 579 | } |
| 580 | } |
| 581 | if (globalContextItem instanceof NodeInfo) { |
| 582 | NodeInfo startNode = (NodeInfo) globalContextItem; |
| 583 | if (startNode.getConfiguration() == null) { |
| 584 | // must be a non-standard document implementation |
| 585 | throw new XPathException("The supplied source document must be associated with a Configuration"); |
| 586 | } |
| 587 | |
| 588 | if (!startNode.getConfiguration().isCompatible(executable.getConfiguration())) { |
| 589 | throw new XPathException( |
| 590 | "Source document and stylesheet must use the same or compatible Configurations", |
| 591 | SaxonErrorCode.SXXP0004); |
| 592 | } |
| 593 | |
| 594 | if (startNode.getTreeInfo().isTyped() && !executable.isSchemaAware()) { |
| 595 | throw new XPathException("Cannot use a schema-validated source document unless the stylesheet is schema-aware"); |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | this.globalContextItem = contextItem; |
| 600 | this.globalContextItemPreset = true; |
| 601 | } |
| 602 | |
| 603 | /** |
| 604 | * Reset the global context item to null. This clears any previous setting of the global context |
| 605 | * item. |
| 606 | */ |
| 607 | |
| 608 | public void clearGlobalContextItem() { |
| 609 | this.globalContextItem = null; |
| 610 | this.globalContextItemPreset = false; |
| 611 | } |
| 612 | |
| 613 | |
| 614 | /** |
| 615 | * Get the item used as the context for evaluating global variables. In XQuery this |
| 616 | * is the same as the initial context item; in XSLT 1.0 and 2.0 it is the root of the tree containing |
| 617 | * the initial context node; in XSLT 3.0 it can be set independently of the initial match selection. |
| 618 | * |
| 619 | * @return the context item for evaluating global variables, or null if there is none |
| 620 | * @since 9.7 |
| 621 | */ |
| 622 | |
| 623 | /*@Nullable*/ |
| 624 | public Item<?> getGlobalContextItem() { |
| 625 | return globalContextItem; |
| 626 | // See W3C bug 5224, which points out that the rules for XQuery 1.0 weren't clearly defined |
| 627 | } |
| 628 | |
| 629 | /** |
| 630 | * Set an object that will be used to resolve URIs used in |
| 631 | * document(), etc. |
| 632 | * |
| 633 | * @param resolver An object that implements the URIResolver interface, or |
| 634 | * null. |
| 635 | */ |
| 636 | |
| 637 | public void setURIResolver(URIResolver resolver) { |
| 638 | userURIResolver = resolver; |
| 639 | if (resolver instanceof StandardURIResolver) { |
| 640 | ((StandardURIResolver) resolver).setConfiguration(getConfiguration()); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /** |
| 645 | * Get the URI resolver. |
| 646 | * <p><i>This method changed in Saxon 8.5, to conform to the JAXP specification. If there |
| 647 | * is no user-specified URIResolver, it now returns null; previously it returned the system |
| 648 | * default URIResolver.</i></p> |
| 649 | * |
| 650 | * @return the user-supplied URI resolver if there is one, or null otherwise. |
| 651 | */ |
| 652 | |
| 653 | public URIResolver getURIResolver() { |
| 654 | return userURIResolver; |
| 655 | } |
| 656 | |
| 657 | /** |
| 658 | * Get the fallback URI resolver. This is the URIResolver that Saxon uses when |
| 659 | * the user-supplied URI resolver returns null. |
| 660 | * <p>This method is intended for internal use only.</p> |
| 661 | * |
| 662 | * @return the the system-defined URIResolver |
| 663 | */ |
| 664 | |
| 665 | public URIResolver getStandardURIResolver() { |
| 666 | return standardURIResolver; |
| 667 | } |
| 668 | |
| 669 | /** |
| 670 | * Set an UnparsedTextURIResolver to be used to resolve URIs passed to the XSLT |
| 671 | * unparsed-text() function. |
| 672 | * |
| 673 | * @param resolver the unparsed text URI resolver to be used. This replaces any unparsed text |
| 674 | * URI resolver previously registered. |
| 675 | * @since 8.9 |
| 676 | */ |
| 677 | |
| 678 | public void setUnparsedTextURIResolver(UnparsedTextURIResolver resolver) { |
| 679 | unparsedTextResolver = resolver; |
| 680 | } |
| 681 | |
| 682 | /** |
| 683 | * Get the URI resolver for the unparsed-text() function. This will |
| 684 | * return the UnparsedTextURIResolver previously set using the {@link #setUnparsedTextURIResolver} |
| 685 | * method. |
| 686 | * |
| 687 | * @return the registered UnparsedTextURIResolver |
| 688 | * @since 8.9 |
| 689 | */ |
| 690 | |
| 691 | public UnparsedTextURIResolver getUnparsedTextURIResolver() { |
| 692 | return unparsedTextResolver; |
| 693 | } |
| 694 | |
| 695 | /** |
| 696 | * Set the CollectionURIResolver used for resolving collection URIs. |
| 697 | * Defaults to the CollectionURIResolver registered with the Configuration |
| 698 | * |
| 699 | * @param resolver the resolver for references to collections |
| 700 | * @since 9.4 |
| 701 | * @deprecated since 9.7. Use {@link #setCollectionFinder(CollectionFinder)} |
| 702 | */ |
| 703 | |
| 704 | public void setCollectionURIResolver(CollectionURIResolver resolver) { |
| 705 | setCollectionFinder(new CollectionURIResolverWrapper(resolver)); |
| 706 | } |
| 707 | |
| 708 | /** |
| 709 | * Get the CollectionURIResolver used for resolving references to collections. |
| 710 | * If none has been set on the Controller, returns the |
| 711 | * CollectionURIResolver registered with the Configuration |
| 712 | * |
| 713 | * @return the resolver for references to collections |
| 714 | * @since 9.4 |
| 715 | * @deprecated since 9.7. Use {@link #getCollectionFinder()} |
| 716 | */ |
| 717 | |
| 718 | /*@NotNull*/ |
| 719 | public CollectionURIResolver getCollectionURIResolver() { |
| 720 | CollectionFinder finder = getCollectionFinder(); |
| 721 | if (finder instanceof CollectionURIResolverWrapper) { |
| 722 | return ((CollectionURIResolverWrapper) finder).getCollectionURIResolver(); |
| 723 | } else { |
| 724 | return null; |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | /** |
| 729 | * Get the collection finder associated with this configuration. This is used to dereference |
| 730 | * collection URIs used in the fn:collection and fn:uri-collection functions |
| 731 | * |
| 732 | * @return the CollectionFinder to be used |
| 733 | * @since 9.7 |
| 734 | */ |
| 735 | |
| 736 | |
| 737 | public CollectionFinder getCollectionFinder() { |
| 738 | if (collectionFinder == null) { |
| 739 | collectionFinder = config.getCollectionFinder(); |
| 740 | } |
| 741 | return collectionFinder; |
| 742 | } |
| 743 | |
| 744 | /** |
| 745 | * Set the collection finder associated with this configuration. This is used to dereference |
| 746 | * collection URIs used in the fn:collection and fn:uri-collection functions |
| 747 | * |
| 748 | * @param cf the CollectionFinder to be used |
| 749 | * @since 9.7 |
| 750 | */ |
| 751 | |
| 752 | public void setCollectionFinder(CollectionFinder cf) { |
| 753 | collectionFinder = cf; |
| 754 | } |
| 755 | |
| 756 | /** |
| 757 | * Set the name of the default collection. Defaults to the default collection |
| 758 | * name registered with the Configuration. |
| 759 | * |
| 760 | * @param uri the collection URI of the default collection. May be null, to cause |
| 761 | * fallback to the collection name registered with the Configuration. The name will be passed |
| 762 | * to the collection URI resolver to identify the documents in the collection, unless |
| 763 | * the name is <code>http://saxon.sf.net/collection/empty</code> which always refers |
| 764 | * to the empty collection. |
| 765 | * @since 9.4 |
| 766 | */ |
| 767 | |
| 768 | public void setDefaultCollection(String uri) { |
| 769 | defaultCollectionURI = uri; |
| 770 | } |
| 771 | |
| 772 | /** |
| 773 | * Get the name of the default collection. Defaults to the default collection |
| 774 | * name registered with the Configuration. |
| 775 | * |
| 776 | * @return the collection URI of the default collection. If no value has been |
| 777 | * set explicitly, the collection URI registered with the Configuration is returned |
| 778 | * @since 9.4 |
| 779 | */ |
| 780 | |
| 781 | public String getDefaultCollection() { |
| 782 | return defaultCollectionURI == null ? getConfiguration().getDefaultCollection() : defaultCollectionURI; |
| 783 | } |
| 784 | |
| 785 | |
| 786 | /** |
| 787 | * Ask whether source documents loaded using the doc(), document(), and collection() |
| 788 | * functions, or supplied as a StreamSource or SAXSource to the transform() or addParameter() method |
| 789 | * should be subjected to schema validation |
| 790 | * |
| 791 | * @return the schema validation mode previously set using setSchemaValidationMode(), |
| 792 | * or the default mode (derived from the global Configuration) otherwise. |
| 793 | */ |
| 794 | |
| 795 | public int getSchemaValidationMode() { |
| 796 | return validationMode; |
| 797 | } |
| 798 | |
| 799 | /** |
| 800 | * Say whether source documents loaded using the doc(), document(), and collection() |
| 801 | * functions, or supplied as a StreamSource or SAXSource to the transform() or addParameter() method, |
| 802 | * should be subjected to schema validation. The default value is taken |
| 803 | * from the corresponding property of the Configuration. |
| 804 | * |
| 805 | * @param validationMode the validation (or construction) mode to be used for source documents. |
| 806 | * One of {@link Validation#STRIP}, {@link Validation#PRESERVE}, {@link Validation#STRICT}, |
| 807 | * {@link Validation#LAX} |
| 808 | * @since 9.2 |
| 809 | */ |
| 810 | |
| 811 | public void setSchemaValidationMode(int validationMode) { |
| 812 | this.validationMode = validationMode; |
| 813 | } |
| 814 | |
| 815 | |
| 816 | /** |
| 817 | * Set the tree model to use. Default is the tiny tree |
| 818 | * |
| 819 | * @param model typically one of the constants {@link net.sf.saxon.om.TreeModel#TINY_TREE}, |
| 820 | * {@link net.sf.saxon.om.TreeModel#TINY_TREE_CONDENSED}, or {@link net.sf.saxon.om.TreeModel#LINKED_TREE}. |
| 821 | * It is also possible to use a user-defined tree model. |
| 822 | * @since 9.2 |
| 823 | */ |
| 824 | |
| 825 | public void setModel(TreeModel model) { |
| 826 | treeModel = model; |
| 827 | } |
| 828 | |
| 829 | /** |
| 830 | * Get the tree model that will be used. |
| 831 | * |
| 832 | * @return typically one of the constants {@link net.sf.saxon.om.TreeModel#TINY_TREE}, |
| 833 | * {@link TreeModel#TINY_TREE_CONDENSED}, or {@link TreeModel#LINKED_TREE}. |
| 834 | * It is also possible to use a user-defined tree model. |
| 835 | * @since 9.2 |
| 836 | */ |
| 837 | |
| 838 | public TreeModel getModel() { |
| 839 | return treeModel; |
| 840 | } |
| 841 | |
| 842 | |
| 843 | /** |
| 844 | * Make a builder for the selected tree model. |
| 845 | * |
| 846 | * @return an instance of the Builder for the chosen tree model |
| 847 | * @since 8.4 |
| 848 | */ |
| 849 | |
| 850 | public Builder makeBuilder() { |
| 851 | Builder b = treeModel.makeBuilder(makePipelineConfiguration()); |
| 852 | b.setTiming(config.isTiming()); |
| 853 | b.setLineNumbering(config.isLineNumbering()); |
| 854 | return b; |
| 855 | } |
| 856 | |
| 857 | /** |
| 858 | * Say whether the transformation should perform whitespace stripping as defined |
| 859 | * by the xsl:strip-space and xsl:preserve-space declarations in the stylesheet |
| 860 | * in the case where a source tree is supplied to the transformation as a tree |
| 861 | * (typically a DOMSource, or a Saxon NodeInfo). |
| 862 | * The default is true. It is legitimate to suppress whitespace |
| 863 | * stripping if the client knows that all unnecessary whitespace has already been removed |
| 864 | * from the tree before it is processed. Note that this option applies to all source |
| 865 | * documents for which whitespace-stripping is normally applied, that is, both the |
| 866 | * principal source documents, and documents read using the doc(), document(), and |
| 867 | * collection() functions. It does not apply to source documents that are supplied |
| 868 | * in the form of a SAXSource or StreamSource, for which whitespace is stripped |
| 869 | * during the process of tree construction. |
| 870 | * <p>Generally, stripping whitespace speeds up the transformation if it is done |
| 871 | * while building the source tree, but slows it down if it is applied to a tree that |
| 872 | * has already been built. So if the same source tree is used as input to a number |
| 873 | * of transformations, it is better to strip the whitespace once at the time of |
| 874 | * tree construction, rather than doing it on-the-fly during each transformation.</p> |
| 875 | * |
| 876 | * @param strip true if whitespace is to be stripped from supplied source trees |
| 877 | * as defined by xsl:strip-space; false to suppress whitespace stripping |
| 878 | * @since 9.3 |
| 879 | */ |
| 880 | |
| 881 | public void setStripSourceTrees(boolean strip) { |
| 882 | stripSourceTrees = strip; |
| 883 | } |
| 884 | |
| 885 | /** |
| 886 | * Ask whether the transformation will perform whitespace stripping for supplied source trees as defined |
| 887 | * by the xsl:strip-space and xsl:preserve-space declarations in the stylesheet. |
| 888 | * |
| 889 | * @return true unless whitespace stripping has been suppressed using |
| 890 | * {@link #setStripSourceTrees(boolean)}. |
| 891 | * @since 9.3 |
| 892 | */ |
| 893 | |
| 894 | public boolean isStripSourceTree() { |
| 895 | return stripSourceTrees; |
| 896 | } |
| 897 | |
| 898 | /** |
| 899 | * Ask whether the executable is a stylesheet whose top-level package |
| 900 | * contains an xsl:strip-space declaration requesting stripping of whitespace |
| 901 | * from the principal source document to the transformation |
| 902 | * |
| 903 | * @return true if whitespace stripping has been requested |
| 904 | */ |
| 905 | |
| 906 | protected boolean isStylesheetContainingStripSpace() { |
| 907 | SpaceStrippingRule rule; |
| 908 | return executable instanceof PreparedStylesheet && |
| 909 | (rule = ((PreparedStylesheet) executable).getTopLevelPackage().getSpaceStrippingRule()) != null && |
| 910 | rule != NoElementsSpaceStrippingRule.getInstance(); |
| 911 | } |
| 912 | |
| 913 | /** |
| 914 | * Ask whether the executable is a stylesheet whose top-level package |
| 915 | * contains requests stripping of type annotations |
| 916 | * |
| 917 | * @return true if stripping of type annotations has been requested |
| 918 | */ |
| 919 | |
| 920 | public boolean isStylesheetStrippingTypeAnnotations() { |
| 921 | return executable instanceof PreparedStylesheet && |
| 922 | ((PreparedStylesheet) executable).getTopLevelPackage().isStripsTypeAnnotations(); |
| 923 | } |
| 924 | |
| 925 | /** |
| 926 | * Make a Stripper configured to implement the whitespace stripping rules. |
| 927 | * In the case of XSLT the whitespace stripping rules are normally defined |
| 928 | * by <code>xsl:strip-space</code> and <code>xsl:preserve-space</code> elements |
| 929 | * in the stylesheet. Alternatively, stripping of all whitespace text nodes |
| 930 | * may be defined at the level of the Configuration, using the code |
| 931 | * {@code Configuration.getParseOptions().setSpaceStrippingRules(AllElementsSpaceStrippingRule.getInstance()}. |
| 932 | * |
| 933 | * @param next the Receiver to which the events filtered by this stripper are |
| 934 | * to be sent (often a Builder). May be null if the stripper is not being used for filtering |
| 935 | * into a Builder or other Receiver. |
| 936 | * @return the required Stripper. A Stripper may be used in two ways. It acts as |
| 937 | * a filter applied to an event stream, that can be used to remove the events |
| 938 | * representing whitespace text nodes before they reach a Builder. Alternatively, |
| 939 | * it can be used to define a view of an existing tree in which the whitespace |
| 940 | * text nodes are dynamically skipped while navigating the XPath axes. |
| 941 | * @since 8.4 - Generalized in 8.5 to accept any Receiver as an argument |
| 942 | */ |
| 943 | |
| 944 | public Stripper makeStripper(/*@Nullable*/ Receiver next) { |
| 945 | if (next == null) { |
| 946 | next = new Sink(makePipelineConfiguration()); |
| 947 | } |
| 948 | return new Stripper(getSpaceStrippingRule(), next); |
| 949 | } |
| 950 | |
| 951 | /** |
| 952 | * Return the default whitespace-stripping rules that apply to this transformation or query. |
| 953 | * |
| 954 | * @return If the configuration-level whitespace-stripping rule is to strip whitespace for |
| 955 | * all elements, then AllElementsSpaceStrippingRule.getInstance(). Otherwise, |
| 956 | */ |
| 957 | |
| 958 | public SpaceStrippingRule getSpaceStrippingRule() { |
| 959 | if (config.getParseOptions().getSpaceStrippingRule() == AllElementsSpaceStrippingRule.getInstance()) { |
| 960 | return AllElementsSpaceStrippingRule.getInstance(); |
| 961 | } else if (executable instanceof PreparedStylesheet) { |
| 962 | SpaceStrippingRule rule = ((PreparedStylesheet) executable).getTopLevelPackage().getSpaceStrippingRule(); |
| 963 | if (rule != null) { |
| 964 | return rule; |
| 965 | } |
| 966 | } |
| 967 | return NoElementsSpaceStrippingRule.getInstance(); |
| 968 | } |
| 969 | |
| 970 | /** |
| 971 | * Add a document to the document pool, and check that it is suitable for use in this query or |
| 972 | * transformation. This check rejects the document if document has been validated (and thus carries |
| 973 | * type annotations) but the query or transformation is not schema-aware. |
| 974 | * <p>This method is intended for internal use only.</p> |
| 975 | * |
| 976 | * @param doc the root node of the document to be added. Must not be null. |
| 977 | * @param uri the document-URI property of this document. If non-null, the document is registered |
| 978 | * in the document pool with this as its document URI. |
| 979 | * @throws XPathException if an error occurs |
| 980 | */ |
| 981 | public void registerDocument(TreeInfo doc, DocumentURI uri) throws XPathException { |
| 982 | if (!getExecutable().isSchemaAware() && !Untyped.getInstance().equals(doc.getRootNode().getSchemaType())) { |
| 983 | boolean isXSLT = getExecutable().getHostLanguage() == Configuration.XSLT; |
| 984 | String message; |
| 985 | if (isXSLT) { |
| 986 | message = "The source document has been schema-validated, but" + |
| 987 | " the stylesheet is not schema-aware. A stylesheet is schema-aware if" + |
| 988 | " either (a) it contains an xsl:import-schema declaration, or (b) the stylesheet compiler" + |
| 989 | " was configured to be schema-aware."; |
| 990 | } else { |
| 991 | message = "The source document has been schema-validated, but" + |
| 992 | " the query is not schema-aware. A query is schema-aware if" + |
| 993 | " either (a) it contains an 'import schema' declaration, or (b) the query compiler" + |
| 994 | " was configured to be schema-aware."; |
| 995 | } |
| 996 | throw new XPathException(message); |
| 997 | } |
| 998 | if (uri != null) { |
| 999 | sourceDocumentPool.add(doc, uri); |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | //////////////////////////////////////////////////////////////////////////////// |
| 1004 | // Methods for registering and retrieving handlers for template rules |
| 1005 | //////////////////////////////////////////////////////////////////////////////// |
| 1006 | |
| 1007 | /** |
| 1008 | * Get the Rule Manager. |
| 1009 | * <p>This method is intended for internal use only.</p> |
| 1010 | * |
| 1011 | * @return the Rule Manager, used to hold details of template rules for |
| 1012 | * all modes; or null in the case of a non-XSLT controller |
| 1013 | */ |
| 1014 | public RuleManager getRuleManager() { |
| 1015 | Executable exec = getExecutable(); |
| 1016 | return exec instanceof PreparedStylesheet ? ((PreparedStylesheet) getExecutable()).getRuleManager() : null; |
| 1017 | } |
| 1018 | |
| 1019 | ///////////////////////////////////////////////////////////////////////// |
| 1020 | // Methods for tracing |
| 1021 | ///////////////////////////////////////////////////////////////////////// |
| 1022 | |
| 1023 | /** |
| 1024 | * Set a TraceListener, replacing any existing TraceListener |
| 1025 | * <p>This method has no effect unless the stylesheet or query was compiled |
| 1026 | * with tracing enabled.</p> |
| 1027 | * |
| 1028 | * @param listener the TraceListener to be set. May be null, in which case |
| 1029 | * trace events will not be reported |
| 1030 | * @since 9.2 |
| 1031 | */ |
| 1032 | |
| 1033 | public void setTraceListener(TraceListener listener) { |
| 1034 | this.traceListener = listener; |
| 1035 | } |
| 1036 | |
| 1037 | /** |
| 1038 | * Get the TraceListener. By default, there is no TraceListener, and this |
| 1039 | * method returns null. A TraceListener may be added using the method |
| 1040 | * {@link #addTraceListener}. If more than one TraceListener has been added, |
| 1041 | * this method will return a composite TraceListener. Because the form |
| 1042 | * this takes is implementation-dependent, this method is not part of the |
| 1043 | * stable Saxon public API. |
| 1044 | * |
| 1045 | * @return the TraceListener used for XSLT or XQuery instruction tracing, or null if absent. |
| 1046 | */ |
| 1047 | /*@Nullable*/ |
| 1048 | public TraceListener getTraceListener() { |
| 1049 | return traceListener; |
| 1050 | } |
| 1051 | |
| 1052 | /** |
| 1053 | * Test whether instruction execution is being traced. This will be true |
| 1054 | * if (a) at least one TraceListener has been registered using the |
| 1055 | * {@link #addTraceListener} method, and (b) tracing has not been temporarily |
| 1056 | * paused using the {@link #pauseTracing} method. |
| 1057 | * |
| 1058 | * @return true if tracing is active, false otherwise |
| 1059 | * @since 8.4 |
| 1060 | */ |
| 1061 | |
| 1062 | public final boolean isTracing() { |
| 1063 | return traceListener != null && !tracingPaused; |
| 1064 | } |
| 1065 | |
| 1066 | /** |
| 1067 | * Pause or resume tracing. While tracing is paused, trace events are not sent to any |
| 1068 | * of the registered TraceListeners. |
| 1069 | * |
| 1070 | * @param pause true if tracing is to pause; false if it is to resume |
| 1071 | * @since 8.4 |
| 1072 | */ |
| 1073 | public final void pauseTracing(boolean pause) { |
| 1074 | tracingPaused = pause; |
| 1075 | } |
| 1076 | |
| 1077 | /** |
| 1078 | * Adds the specified trace listener to receive trace events from |
| 1079 | * this instance. Note that although TraceListeners can be added |
| 1080 | * or removed dynamically, this has no effect unless the stylesheet |
| 1081 | * or query has been compiled with tracing enabled. This is achieved |
| 1082 | * by calling {@link Configuration#setTraceListener} or by setting |
| 1083 | * the attribute {@link net.sf.saxon.lib.FeatureKeys#TRACE_LISTENER} on the |
| 1084 | * TransformerFactory. Conversely, if this property has been set in the |
| 1085 | * Configuration or TransformerFactory, the TraceListener will automatically |
| 1086 | * be added to every Controller that uses that Configuration. |
| 1087 | * |
| 1088 | * @param trace the trace listener. If null is supplied, the call has no effect. |
| 1089 | * @since 8.4 |
| 1090 | */ |
| 1091 | |
| 1092 | public void addTraceListener(/*@Nullable*/ TraceListener trace) { |
| 1093 | if (trace != null) { |
| 1094 | traceListener = TraceEventMulticaster.add(traceListener, trace); |
| 1095 | } |
| 1096 | } |
| 1097 | |
| 1098 | /** |
| 1099 | * Removes the specified trace listener so that the listener will no longer |
| 1100 | * receive trace events. |
| 1101 | * |
| 1102 | * @param trace the trace listener. |
| 1103 | * @since 8.4 |
| 1104 | */ |
| 1105 | |
| 1106 | public void removeTraceListener(TraceListener trace) { |
| 1107 | traceListener = TraceEventMulticaster.remove(traceListener, trace); |
| 1108 | } |
| 1109 | |
| 1110 | /** |
| 1111 | * Set the destination for output from the fn:trace() function. |
| 1112 | * By default, the destination is System.err. If a TraceListener is in use, |
| 1113 | * this is ignored, and the trace() output is sent to the TraceListener. |
| 1114 | * |
| 1115 | * @param stream the PrintStream to which trace output will be sent. If set to |
| 1116 | * null, trace output is suppressed entirely. It is the caller's responsibility |
| 1117 | * to close the stream after use. |
| 1118 | * @since 9.1. Changed in 9.6 to use a Logger |
| 1119 | */ |
| 1120 | |
| 1121 | public void setTraceFunctionDestination(Logger stream) { |
| 1122 | traceFunctionDestination = stream; |
| 1123 | } |
| 1124 | |
| 1125 | /** |
| 1126 | * Get the destination for output from the fn:trace() function. |
| 1127 | * |
| 1128 | * @return the PrintStream to which trace output will be sent. If no explicitly |
| 1129 | * destination has been set, returns System.err. If the destination has been set |
| 1130 | * to null to suppress trace output, returns null. |
| 1131 | * @since 9.1. Changed in 9.6 to use a Logger |
| 1132 | */ |
| 1133 | |
| 1134 | public Logger getTraceFunctionDestination() { |
| 1135 | return traceFunctionDestination; |
| 1136 | } |
| 1137 | |
| 1138 | /** |
| 1139 | * Initialize the controller ready for a new transformation. This method should not normally be called by |
| 1140 | * users (it is done automatically when transform() is invoked). However, it is available as a low-level API |
| 1141 | * especially for use with XQuery. |
| 1142 | * |
| 1143 | * @param params the values of stylesheet parameters. Changed in 9.9.1.1 so this no longer includes |
| 1144 | * static parameters (which are already available in the {@link PreparedStylesheet}). |
| 1145 | * @throws XPathException if an error occurs, for example if a required parameter is not supplied. |
| 1146 | */ |
| 1147 | |
| 1148 | public void initializeController(GlobalParameterSet params) throws XPathException { |
| 1149 | |
| 1150 | |
| 1151 | // get a new bindery, to clear out any variables from previous runs |
| 1152 | |
| 1153 | binderies = new HashMap<>(); |
| 1154 | |
| 1155 | // if parameters were supplied, set them up |
| 1156 | |
| 1157 | try { |
| 1158 | executable.checkSuppliedParameters(params); |
| 1159 | } catch (XPathException e) { |
| 1160 | if (!e.hasBeenReported()) { |
| 1161 | getErrorListener().fatalError(e); |
| 1162 | throw e; |
| 1163 | } |
| 1164 | } |
| 1165 | globalParameters = params; |
| 1166 | |
| 1167 | // Check the global context item |
| 1168 | |
| 1169 | globalContextItem = executable.checkInitialContextItem(globalContextItem, newXPathContext()); |
| 1170 | |
| 1171 | if (traceListener != null) { |
| 1172 | traceListener.open(this); |
| 1173 | preEvaluateGlobals(newXPathContext()); |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | public void setApplyFunctionConversionRulesToExternalVariables(boolean applyConversionRules) { |
| 1178 | convertParameters = applyConversionRules; |
| 1179 | //topLevelBindery.setApplyFunctionConversionRulesToExternalVariables(applyConversionRules); |
| 1180 | } |
| 1181 | |
| 1182 | |
| 1183 | ///////////////////////////////////////////////////////////////////////// |
| 1184 | // Allow user data to be associated with nodes on a tree |
| 1185 | ///////////////////////////////////////////////////////////////////////// |
| 1186 | |
| 1187 | /** |
| 1188 | * Get user data associated with a key. To retrieve user data, two objects are required: |
| 1189 | * an arbitrary object that may be regarded as the container of the data (originally, and |
| 1190 | * typically still, a node in a tree), and a name. The name serves to distingush data objects |
| 1191 | * associated with the same node by different client applications. |
| 1192 | * <p>This method is intended primarily for internal use, though it may also be |
| 1193 | * used by advanced applications.</p> |
| 1194 | * |
| 1195 | * @param key an object acting as a key for this user data value. This must be equal |
| 1196 | * (in the sense of the equals() method) to the key supplied when the data value was |
| 1197 | * registered using {@link #setUserData}. |
| 1198 | * @param name the name of the required property |
| 1199 | * @return the value of the required property |
| 1200 | */ |
| 1201 | |
| 1202 | public synchronized Object getUserData(Object key, String name) { |
| 1203 | String keyValue = key.hashCode() + " " + name; |
| 1204 | // System.err.println("getUserData " + name + " on object returning " + userDataTable.get(key)); |
| 1205 | return userDataTable.get(keyValue); |
| 1206 | } |
| 1207 | |
| 1208 | /** |
| 1209 | * Set user data associated with a key. To store user data, two objects are required: |
| 1210 | * an arbitrary object that may be regarded as the container of the data (originally, and |
| 1211 | * typically still, a node in a tree), and a name. The name serves to distingush data objects |
| 1212 | * associated with the same node by different client applications. |
| 1213 | * <p>This method is intended primarily for internal use, though it may also be |
| 1214 | * used by advanced applications.</p> |
| 1215 | * |
| 1216 | * @param key an object acting as a key for this user data value. This can be any object, for example |
| 1217 | * a node or a string. If data for the given object and name already exists, it is overwritten. |
| 1218 | * @param name the name of the required property |
| 1219 | * @param data the value of the required property. If null is supplied, any existing entry |
| 1220 | * for the key is removed. |
| 1221 | */ |
| 1222 | |
| 1223 | public synchronized void setUserData(Object key, String name, /*@Nullable*/ Object data) { |
| 1224 | // System.err.println("setUserData " + name + " on object to " + data); |
| 1225 | String keyVal = key.hashCode() + " " + name; |
| 1226 | if (data == null) { |
| 1227 | userDataTable.remove(keyVal); |
| 1228 | } else { |
| 1229 | userDataTable.put(keyVal, data); |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | /** |
| 1234 | * Get the table of local indexes supporting xsl:key (or implicit keys created |
| 1235 | * by the optimizer). Indexes are held at Controller level (rather than being |
| 1236 | * shared across transformations) if the key definition is dependent on local |
| 1237 | * information, for example stylesheet parameters. |
| 1238 | * @return the index of indexes. The master index is created if it does not |
| 1239 | * already exist. The master index is a two-level index: the first level is indexed |
| 1240 | * by the integer fingerprint of the key name; the second level is indexed by |
| 1241 | * the document number (a long) for the specific document or temporary tree. |
| 1242 | */ |
| 1243 | |
| 1244 | public synchronized IntHashMap<Map<Long, KeyIndex>> getLocalIndexes() { |
| 1245 | if (localIndexes == null) { |
| 1246 | localIndexes = new IntHashMap<>(); |
| 1247 | } |
| 1248 | return localIndexes; |
| 1249 | } |
| 1250 | |
| 1251 | /** |
| 1252 | * Set the last remembered node, for node numbering purposes. |
| 1253 | * <p>This method is strictly for internal use only.</p> |
| 1254 | * |
| 1255 | * @param node the node in question |
| 1256 | * @param number the number of this node |
| 1257 | */ |
| 1258 | |
| 1259 | public synchronized void setRememberedNumber(NodeInfo node, int number) { |
| 1260 | lastRememberedNode = node; |
| 1261 | lastRememberedNumber = number; |
| 1262 | } |
| 1263 | |
| 1264 | /** |
| 1265 | * Get the number of a node if it is the last remembered one. |
| 1266 | * <p>This method is strictly for internal use only.</p> |
| 1267 | * |
| 1268 | * @param node the node for which remembered information is required |
| 1269 | * @return the number of this node if known, else -1. |
| 1270 | */ |
| 1271 | |
| 1272 | public synchronized int getRememberedNumber(NodeInfo node) { |
| 1273 | if (lastRememberedNode == node) { |
| 1274 | return lastRememberedNumber; |
| 1275 | } |
| 1276 | return -1; |
| 1277 | } |
| 1278 | |
| 1279 | |
| 1280 | protected void checkReadiness() throws XPathException { |
| 1281 | if (inUse) { |
| 1282 | throw new IllegalStateException( |
| 1283 | "The Controller is being used recursively or concurrently. This is not permitted."); |
| 1284 | } |
| 1285 | if (binderies == null) { |
| 1286 | throw new IllegalStateException("The Controller has not been initialized"); |
| 1287 | } |
| 1288 | inUse = true; |
| 1289 | clearPerTransformationData(); |
| 1290 | if (executable == null) { |
| 1291 | throw new XPathException("Stylesheet has not been prepared"); |
| 1292 | } |
| 1293 | if (!dateTimePreset) { |
| 1294 | currentDateTime = null; // reset at start of each transformation |
| 1295 | } |
| 1296 | |
| 1297 | } |
| 1298 | |
| 1299 | /** |
| 1300 | * Make a source tree from a source supplied as a StreamSource or SAXSource |
| 1301 | * |
| 1302 | * @param source the source |
| 1303 | * @param validationMode indicates whether the source should be schema-validated |
| 1304 | * @return the root of the constructed tree |
| 1305 | * @throws XPathException if tree construction fails |
| 1306 | */ |
| 1307 | |
| 1308 | public NodeInfo makeSourceTree(Source source, int validationMode) throws XPathException { |
| 1309 | |
| 1310 | if (source instanceof SAXSource && config.getBooleanProperty(Feature.IGNORE_SAX_SOURCE_PARSER)) { |
| 1311 | // This option is provided to allow the parser set by applications such as Ant to be overridden by |
| 1312 | // the parser requested using FeatureKeys.SOURCE_PARSER |
| 1313 | ((SAXSource) source).setXMLReader(null); |
| 1314 | } |
| 1315 | Builder sourceBuilder = makeBuilder(); |
| 1316 | sourceBuilder.setUseEventLocation(true); |
| 1317 | if (sourceBuilder instanceof TinyBuilder) { |
| 1318 | ((TinyBuilder) sourceBuilder).setStatistics(config.getTreeStatistics().SOURCE_DOCUMENT_STATISTICS); |
| 1319 | } |
| 1320 | Receiver r = sourceBuilder; |
| 1321 | SpaceStrippingRule spaceStrippingRule = NoElementsSpaceStrippingRule.getInstance(); |
| 1322 | if (config.isStripsAllWhiteSpace() || isStylesheetContainingStripSpace() || |
| 1323 | validationMode == Validation.STRICT || validationMode == Validation.LAX) { |
| 1324 | r = makeStripper(sourceBuilder); |
| 1325 | spaceStrippingRule = getSpaceStrippingRule(); |
| 1326 | } |
| 1327 | if (isStylesheetStrippingTypeAnnotations()) { |
| 1328 | r = config.getAnnotationStripper(r); |
| 1329 | } |
| 1330 | PipelineConfiguration pipe = sourceBuilder.getPipelineConfiguration(); |
| 1331 | pipe.getParseOptions().setSchemaValidationMode(validationMode); |
| 1332 | r.setPipelineConfiguration(pipe); |
| 1333 | Sender.send(source, r, null); |
| 1334 | if (source instanceof AugmentedSource && ((AugmentedSource)source).isPleaseCloseAfterUse()) { |
| 1335 | ((AugmentedSource) source).close(); |
| 1336 | } |
| 1337 | NodeInfo doc = sourceBuilder.getCurrentRoot(); |
| 1338 | //globalContextItem = doc; |
| 1339 | sourceBuilder.reset(); |
| 1340 | if (source.getSystemId() != null) { |
| 1341 | registerDocument(doc.getTreeInfo(), new DocumentURI(source.getSystemId())); |
| 1342 | } |
| 1343 | doc.getTreeInfo().setSpaceStrippingRule(spaceStrippingRule); |
| 1344 | return doc; |
| 1345 | } |
| 1346 | |
| 1347 | |
| 1348 | /** |
| 1349 | * Prepare an input tree for processing. This is used when either the initial |
| 1350 | * input, or a Source returned by the document() function, is a NodeInfo or a |
| 1351 | * DOMSource. The preparation consists of wrapping a DOM document inside a wrapper |
| 1352 | * that implements the NodeInfo interface, and/or adding a space-stripping wrapper |
| 1353 | * if the stylesheet strips whitespace nodes, and/or adding a type-stripping wrapper |
| 1354 | * if the stylesheet strips input type annotations. |
| 1355 | * <p>This method is intended for internal use.</p> |
| 1356 | * |
| 1357 | * @param source the input tree. Must be either a DOMSource or a NodeInfo |
| 1358 | * @return the NodeInfo representing the input node, suitably wrapped. Exceptionally, |
| 1359 | * the the source is a whitespace text node that is itself stripped, return null. |
| 1360 | */ |
| 1361 | |
| 1362 | public NodeInfo prepareInputTree(Source source) { |
| 1363 | NodeInfo start = getConfiguration().unravel(source); |
| 1364 | // Stripping type annotations happens before stripping of whitespace |
| 1365 | if (isStylesheetStrippingTypeAnnotations()) { |
| 1366 | TreeInfo docInfo = start.getTreeInfo(); |
| 1367 | if (docInfo.isTyped()) { |
| 1368 | TypeStrippedDocument strippedDoc = new TypeStrippedDocument(docInfo); |
| 1369 | start = strippedDoc.wrap(start); |
| 1370 | } |
| 1371 | } |
| 1372 | if (stripSourceTrees && isStylesheetContainingStripSpace()) { |
| 1373 | TreeInfo docInfo = start.getTreeInfo(); |
| 1374 | SpaceStrippingRule spaceStrippingRule = getSpaceStrippingRule(); |
| 1375 | if (docInfo.getSpaceStrippingRule() != spaceStrippingRule) { // if not already space-stripped |
| 1376 | SpaceStrippedDocument strippedDoc = new SpaceStrippedDocument(docInfo, spaceStrippingRule); |
| 1377 | // Edge case: the global context item might itself be a whitespace text node that is stripped |
| 1378 | if (!SpaceStrippedNode.isPreservedNode(start, strippedDoc, start.getParent())) { |
| 1379 | return null; |
| 1380 | } |
| 1381 | start = strippedDoc.wrap(start); |
| 1382 | } |
| 1383 | } |
| 1384 | return start; |
| 1385 | } |
| 1386 | |
| 1387 | |
| 1388 | /** |
| 1389 | * Pre-evaluate global variables (when debugging/tracing). |
| 1390 | * <p>This method is intended for internal use.</p> |
| 1391 | * |
| 1392 | * @param context the dynamic context for evaluating the global variables |
| 1393 | */ |
| 1394 | |
| 1395 | public void preEvaluateGlobals(XPathContext context) throws XPathException { |
| 1396 | for (PackageData pack : getExecutable().getPackages()) { |
| 1397 | for (GlobalVariable var : pack.getGlobalVariableList()) { |
| 1398 | if (!var.isUnused()) { |
| 1399 | try { |
| 1400 | var.evaluateVariable(context, var.getDeclaringComponent()); |
| 1401 | } catch (XPathException err) { |
| 1402 | // Don't report an exception unless the variable is actually evaluated |
| 1403 | getBindery(var.getPackageData()).setGlobalVariable(var, new Bindery.FailureValue(err)); |
| 1404 | } |
| 1405 | } |
| 1406 | } |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | /** |
| 1411 | * Register the dependency of one variable ("one") upon another ("two"), throwing an exception if this would establish |
| 1412 | * a cycle of dependencies. |
| 1413 | * |
| 1414 | * @param one the first (dependent) variable |
| 1415 | * @param two the second (dependee) variable |
| 1416 | * @throws XPathException if adding this dependency creates a cycle of dependencies among global variables. |
| 1417 | */ |
| 1418 | |
| 1419 | public synchronized void registerGlobalVariableDependency(GlobalVariable one, GlobalVariable two) throws XPathException { |
| 1420 | if (one == two) { |
| 1421 | throw new XPathException.Circularity("Circular dependency among global variables: " |
| 1422 | + one.getVariableQName().getDisplayName() + " depends on its own value"); |
| 1423 | } |
| 1424 | Set<GlobalVariable> transitiveDependencies = globalVariableDependencies.get(two); |
| 1425 | if (transitiveDependencies != null) { |
| 1426 | if (transitiveDependencies.contains(one)) { |
| 1427 | throw new XPathException.Circularity("Circular dependency among variables: " |
| 1428 | + one.getVariableQName().getDisplayName() + " depends on the value of " |
| 1429 | + two.getVariableQName().getDisplayName() + ", which depends directly or indirectly on the value of " |
| 1430 | + one.getVariableQName().getDisplayName()); |
| 1431 | } |
| 1432 | for (GlobalVariable var : transitiveDependencies) { |
| 1433 | // register the transitive dependencies |
| 1434 | registerGlobalVariableDependency(one, var); |
| 1435 | } |
| 1436 | } |
| 1437 | Set<GlobalVariable> existingDependencies = |
| 1438 | globalVariableDependencies.computeIfAbsent(one, k -> new HashSet<>()); |
| 1439 | existingDependencies.add(two); |
| 1440 | |
| 1441 | } |
| 1442 | |
| 1443 | |
| 1444 | /** |
| 1445 | * Set the current date and time for this query or transformation. |
| 1446 | * This method is provided primarily for testing purposes, to allow tests to be run with |
| 1447 | * a fixed date and time. The supplied date/time must include a timezone, which is used |
| 1448 | * as the implicit timezone. |
| 1449 | * <p>Note that comparisons of date/time values currently use the implicit timezone |
| 1450 | * taken from the system clock, not from the value supplied here.</p> |
| 1451 | * |
| 1452 | * @param dateTime the date/time value to be used as the current date and time |
| 1453 | * @throws IllegalStateException if a current date/time has already been |
| 1454 | * established by calling getCurrentDateTime(), or by a previous call on setCurrentDateTime() |
| 1455 | * @throws net.sf.saxon.trans.XPathException if the supplied dateTime contains no timezone |
| 1456 | */ |
| 1457 | |
| 1458 | public void setCurrentDateTime(/*@NotNull*/ DateTimeValue dateTime) throws XPathException { |
| 1459 | if (currentDateTime == null) { |
| 1460 | if (dateTime.getComponent(AccessorFn.Component.TIMEZONE) == null) { |
| 1461 | throw new XPathException("No timezone is present in supplied value of current date/time"); |
| 1462 | } |
| 1463 | currentDateTime = dateTime; |
| 1464 | dateTimePreset = true; |
| 1465 | } else { |
| 1466 | throw new IllegalStateException( |
| 1467 | "Current date and time can only be set once, and cannot subsequently be changed"); |
| 1468 | } |
| 1469 | } |
| 1470 | |
| 1471 | /** |
| 1472 | * Get the current date and time for this query or transformation. |
| 1473 | * All calls during one transformation return the same answer. |
| 1474 | * |
| 1475 | * @return Get the current date and time. This will deliver the same value |
| 1476 | * for repeated calls within the same transformation. The returned dateTime |
| 1477 | * value will have a timezone, which will be the default/local timezone |
| 1478 | * determined by the platform on which the application is running. |
| 1479 | */ |
| 1480 | |
| 1481 | /*@Nullable*/ |
| 1482 | public DateTimeValue getCurrentDateTime() { |
| 1483 | if (currentDateTime == null) { |
| 1484 | currentDateTime = DateTimeValue.now(); |
| 1485 | } |
| 1486 | return currentDateTime; |
| 1487 | } |
| 1488 | |
| 1489 | /** |
| 1490 | * Get the implicit timezone offset for this query or transformation |
| 1491 | * |
| 1492 | * @return the implicit timezone as an offset in minutes. This will be the default/local timezone |
| 1493 | * determined by the platform on which the application is running. The value will be unchanged for |
| 1494 | * repeated calls within the same transformation. |
| 1495 | */ |
| 1496 | |
| 1497 | public int getImplicitTimezone() { |
| 1498 | return getCurrentDateTime().getTimezoneInMinutes(); |
| 1499 | } |
| 1500 | |
| 1501 | ///////////////////////////////////////// |
| 1502 | // Methods for handling dynamic context |
| 1503 | ///////////////////////////////////////// |
| 1504 | |
| 1505 | /** |
| 1506 | * Make an XPathContext object for expression evaluation. |
| 1507 | * <p>This method is intended for internal use.</p> |
| 1508 | * |
| 1509 | * @return the new XPathContext |
| 1510 | */ |
| 1511 | |
| 1512 | public XPathContextMajor newXPathContext() { |
| 1513 | XPathContextMajor c = new XPathContextMajor(this); |
| 1514 | c.setCurrentOutputUri(principalResultURI); |
| 1515 | return c; |
| 1516 | } |
| 1517 | |
| 1518 | /** |
| 1519 | * Indicate whether document projection should be used, and supply the PathMap used to control it. |
| 1520 | * Note: this is available only under Saxon-EE. |
| 1521 | * |
| 1522 | * @param pathMap a path map to be used for projecting source documents |
| 1523 | */ |
| 1524 | |
| 1525 | public void setUseDocumentProjection(PathMap pathMap) { |
| 1526 | this.pathMap = pathMap; |
| 1527 | } |
| 1528 | |
| 1529 | /** |
| 1530 | * Get the path map used for document projection, if any. |
| 1531 | * |
| 1532 | * @return the path map to be used for document projection, if one has been supplied; otherwise null |
| 1533 | */ |
| 1534 | |
| 1535 | /*@Nullable*/ |
| 1536 | public PathMap getPathMapForDocumentProjection() { |
| 1537 | return pathMap; |
| 1538 | } |
| 1539 | |
| 1540 | |
| 1541 | /** |
| 1542 | * Get the cache of stylesheets (cached during calls on fn:transform()) for this query or transformation. |
| 1543 | * |
| 1544 | * @return the stylesheet cache |
| 1545 | */ |
| 1546 | |
| 1547 | public synchronized StylesheetCache getStylesheetCache() { |
| 1548 | if (stylesheetCache == null) { |
| 1549 | this.stylesheetCache = new StylesheetCache(); |
| 1550 | } |
| 1551 | return stylesheetCache; |
| 1552 | } |
| 1553 | |
| 1554 | /** |
| 1555 | * Get the factory function that is used to create new instances of FocusTrackingIterator. |
| 1556 | * The standard function for instantiating a FocusTrackingIterator can be overridden to deliver |
| 1557 | * one with extra diagnostic capability for use in debuggers |
| 1558 | * @param multithreaded true if the focus tracker must be suitable for executing a multi-threaded |
| 1559 | * xsl:for-each iteration |
| 1560 | * @return a factory function that is used to create FocusTrackingIterator instances |
| 1561 | */ |
| 1562 | |
| 1563 | public Function<SequenceIterator<?>, FocusTrackingIterator<?>> getFocusTrackerFactory(boolean multithreaded) { |
| 1564 | return multithreaded && multiThreadedFocusTrackerFactory != null ? |
| 1565 | multiThreadedFocusTrackerFactory : |
| 1566 | focusTrackerFactory; |
| 1567 | } |
| 1568 | |
| 1569 | /** |
| 1570 | * Set a factory function that will be used to create new instances of FocusTrackingIterator. |
| 1571 | * The standard function for instantiating a FocusTrackingIterator can be overridden to deliver |
| 1572 | * one with extra diagnostic capability for use in debuggers. |
| 1573 | * |
| 1574 | * @param focusTrackerFactory a factory function that is used to create FocusTrackingIterator instances |
| 1575 | */ |
| 1576 | |
| 1577 | public void setFocusTrackerFactory(Function<SequenceIterator<?>, FocusTrackingIterator<?>> focusTrackerFactory) { |
| 1578 | this.focusTrackerFactory = focusTrackerFactory; |
| 1579 | } |
| 1580 | |
| 1581 | /** |
| 1582 | * Set a factory function that will be used to create new instances of FocusTrackingIterator for |
| 1583 | * multithreaded operation. |
| 1584 | * The standard function for instantiating a FocusTrackingIterator can be overridden to deliver |
| 1585 | * one with extra diagnostic capability for use in debuggers. |
| 1586 | * |
| 1587 | * @param focusTrackerFactory a factory function that is used to create FocusTrackingIterator instances |
| 1588 | */ |
| 1589 | |
| 1590 | public void setMultithreadedFocusTrackerFactory(Function<SequenceIterator<?>, FocusTrackingIterator<?>> focusTrackerFactory) { |
| 1591 | this.multiThreadedFocusTrackerFactory = focusTrackerFactory; |
| 1592 | } |
| 1593 | |
| 1594 | /** |
| 1595 | * Set the focus tracker factory function to a function that creates a memoizing focus tracker, which |
| 1596 | * has the effect that all items read by the focus iterator are accessible to a debugger at any stage |
| 1597 | * while iterating over the sequence |
| 1598 | */ |
| 1599 | |
| 1600 | public void setMemoizingFocusTrackerFactory() { |
| 1601 | setFocusTrackerFactory(base -> { |
| 1602 | FocusTrackingIterator<?> fti; |
| 1603 | if ((base.getProperties() & GROUNDED) == 0 && |
| 1604 | !(base instanceof GroupIterator) && !(base instanceof RegexIterator)) { |
| 1605 | try { |
| 1606 | MemoSequence<?> ms = new MemoSequence<>(base); |
| 1607 | fti = FocusTrackingIterator.track(ms.iterate()); |
| 1608 | } catch (XPathException e) { |
| 1609 | fti = FocusTrackingIterator.track(base); |
| 1610 | } |
| 1611 | } else { |
| 1612 | fti = FocusTrackingIterator.track(base); |
| 1613 | } |
| 1614 | return fti; |
| 1615 | }); |
| 1616 | } |
| 1617 | |
| 1618 | } |
| 1619 |