Debian Codegraph @

net/sf/saxon/expr/XPathContextMinor.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.expr.instruct.ParameterSet;
14 import net.sf.saxon.expr.sort.GroupIterator;
15 import net.sf.saxon.lib.DelegatingErrorListener;
16 import net.sf.saxon.lib.UnfailingErrorListener;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.regex.RegexIterator;
19 import net.sf.saxon.trace.ContextStackIterator;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.trans.rules.Rule;
22 import net.sf.saxon.tree.iter.LookaheadIterator;
23 import net.sf.saxon.value.DateTimeValue;
24
25 import javax.xml.transform.URIResolver;
26 import java.util.Iterator;
27 import java.util.function.Function;
28
29 /**
30 * This class represents a minor change in the dynamic context in which an XPath expression is evaluated:
31 * a "major context" object allows all aspects of the dynamic context to change, whereas
32 * a "minor context" only allows changes to the focus and the destination for push output.
33 */
34
35 public class XPathContextMinor implements XPathContext {
36
37 Controller controller;
38 FocusIterator<?> currentIterator;
39 /*@Nullable*/ LastValue last = null;
40 Receiver currentReceiver;
41
42 XPathContext caller = null;
43 protected StackFrame stackFrame;
44 protected String currentDestination = "";
45 protected int temporaryOutputState = 0;
46
47
48 /**
49 * Private Constructor
50 */
51
52 protected XPathContextMinor() {
53 }
54
55 /**
56 * Construct a new context as a copy of another. The new context is effectively added
57 * to the top of a stack, and contains a pointer to the previous context
58 */
59
60 public XPathContextMajor newContext() {
61 return XPathContextMajor.newContext(this);
62 }
63
64 /**
65 * Construct a new context as a copy of another. The new context is effectively added
66 * to the top of a stack, and contains a pointer to the previous context
67 */
68
69 public XPathContextMinor newMinorContext() {
70 XPathContextMinor c = new XPathContextMinor();
71 //System.err.println("NEW MINOR CONTEXT " + c);
72 c.controller = controller;
73 c.caller = this;
74 c.currentIterator = currentIterator;
75 c.currentReceiver = currentReceiver;
76 c.last = last;
77 c.stackFrame = stackFrame;
78 c.currentDestination = currentDestination;
79 c.temporaryOutputState = temporaryOutputState;
80 return c;
81 }
82
83 /**
84 * Set the calling XPathContext
85 */
86
87 public void setCaller(XPathContext caller) {
88 this.caller = caller;
89 }
90
91 /**
92 * Construct a new context without copying (used for the context in a function call)
93 */
94
95 public XPathContextMajor newCleanContext() {
96 XPathContextMajor c = new XPathContextMajor(getController());
97 c.setCaller(this);
98 return c;
99 }
100
101 /**
102 * Get the local parameters for the current template call.
103 *
104 * @return the supplied parameters
105 */
106
107 public ParameterSet getLocalParameters() {
108 return getCaller().getLocalParameters();
109 }
110
111 /**
112 * Get the tunnel parameters for the current template call.
113 *
114 * @return the supplied tunnel parameters
115 */
116
117 public ParameterSet getTunnelParameters() {
118 return getCaller().getTunnelParameters();
119 }
120
121 /**
122 * Get the Controller. May return null when running outside XSLT or XQuery
123 */
124
125 public final Controller getController() {
126 return controller;
127 }
128
129 /**
130 * Get the Configuration
131 */
132
133 public final Configuration getConfiguration() {
134 return controller.getConfiguration();
135 }
136
137 /**
138 * Get the Name Pool
139 */
140
141 public final NamePool getNamePool() {
142 return controller.getConfiguration().getNamePool();
143 }
144
145 /**
146 * Get the calling XPathContext (the next one down the stack). This will be null if unknown, or
147 * if the bottom of the stack has been reached.
148 */
149
150 public final XPathContext getCaller() {
151 return caller;
152 }
153
154 /**
155 * Set a new sequence iterator.
156 */
157
158 public void setCurrentIterator(FocusIterator<?> iter) {
159 currentIterator = iter;
160 last = new LastValue(-1);
161 }
162
163 /**
164 * Create, set, and return a focus tracking iterator that wraps a supplied sequence iterator.
165 *
166 * @param iter the current iterator. The context item, position, and size are determined by reference
167 * to the current iterator.
168 */
169
170 public <T extends Item<?>> FocusIterator<T> trackFocus(SequenceIterator<T> iter) {
171 Function<SequenceIterator<?>, FocusTrackingIterator<?>> factory =
172 controller.getFocusTrackerFactory(false);
173 //noinspection unchecked
174 FocusIterator<T> fit = (FocusIterator<T>)factory.apply(iter);
175 setCurrentIterator(fit);
176 return fit;
177 }
178
179 /**
180 * Create, set, and return a focus tracking iterator that wraps a supplied sequence iterator,
181 * suitable for use in a multithreaded xsl:for-each iteration
182 *
183 * @param iter the current iterator. The context item, position, and size are determined by reference
184 * to the current iterator.
185 */
186
187 public <T extends Item<?>> FocusIterator<T> trackFocusMultithreaded(SequenceIterator<T> iter) {
188 Function<SequenceIterator<?>, FocusTrackingIterator<?>> factory = controller.getFocusTrackerFactory(true);
189 FocusIterator<T> fit = (FocusIterator<T>)factory.apply(iter);
190 setCurrentIterator(fit);
191 return fit;
192 }
193
194
195 /**
196 * Get the current iterator.
197 * This encapsulates the context item, context position, and context size.
198 *
199 * @return the current iterator, or null if there is no current iterator
200 * (which means the context item, position, and size are undefined).
201 */
202
203 public final FocusIterator<?> getCurrentIterator() {
204 return currentIterator;
205 }
206
207 /**
208 * Get the context item
209 *
210 * @return the context item, or null if the context item is undefined
211 */
212
213 public final Item getContextItem() {
214 if (currentIterator == null) {
215 return null;
216 }
217 return currentIterator.current();
218 }
219
220 /**
221 * Get the context size (the position of the last item in the current node list)
222 *
223 * @return the context size
224 * @throws XPathException if the context position is undefined
225 */
226
227 public final int getLast() throws XPathException {
228 if (currentIterator == null) {
229 XPathException e = new XPathException("The context item is absent, so last() is undefined");
230 e.setXPathContext(this);
231 e.setErrorCode("XPDY0002");
232 throw e;
233 }
234 if (last.value >= 0) {
235 return last.value;
236 }
237 return currentIterator.getLength();
238 }
239
240 /**
241 * Determine whether the context position is the same as the context size
242 * that is, whether position()=last()
243 */
244
245 public final boolean isAtLast() throws XPathException {
246 if ((currentIterator.getProperties() & SequenceIterator.LOOKAHEAD) != 0) {
247 return !((LookaheadIterator) currentIterator).hasNext();
248 }
249 return currentIterator.position() == getLast();
250 }
251
252 /**
253 * Get the URI resolver. This gets the local URIResolver set in the XPathContext if there
254 * is one; if not, it gets the URIResolver from the Controller (which itself defaults to the
255 * one set in the Configuration).
256 *
257 * @return the user-supplied URI resolver if there is one, or null otherwise.
258 * @since 9.6
259 */
260 public URIResolver getURIResolver() {
261 return caller.getURIResolver();
262 }
263
264 /**
265 * Get the error listener. If no ErrorListener
266 * has been set locally, the ErrorListener in the Controller is returned; this in turn defaults
267 * to the ErrorListener set in the Configuration.
268 *
269 * @return the ErrorListener in use. Note that this is not necessarily the ErrorListener that was supplied
270 * by the caller; if that was not an {@link UnfailingErrorListener},
271 * it will have been wrapped in a {@link DelegatingErrorListener}, and it is the DelegatingErrorListener
272 * that this method returns.
273 * @since 9.6
274 */
275 public UnfailingErrorListener getErrorListener() {
276 return caller.getErrorListener();
277 }
278
279 /**
280 * Get the current exception (in saxon:catch)
281 *
282 * @return the current exception, or null if there is none defined
283 */
284 public XPathException getCurrentException() {
285 return caller.getCurrentException();
286 }
287
288 /**
289 * Get the thread manager used to process asynchronous xsl:result-document threads.
290 *
291 * @return the current thread manager; or null if multithreading is not supported
292 */
293 public XPathContextMajor.ThreadManager getThreadManager() {
294 return caller.getThreadManager();
295 }
296
297 /**
298 * Get the current component
299 */
300
301 public Component getCurrentComponent() {
302 return caller.getCurrentComponent();
303 }
304
305
306 /**
307 * Get a reference to the local stack frame for variables. Note that it's
308 * the caller's job to make a local copy of this. This is used for creating
309 * a Closure containing a retained copy of the variables for delayed evaluation.
310 *
311 * @return array of variables.
312 */
313
314 public StackFrame getStackFrame() {
315 return stackFrame;
316 }
317
318 public void makeStackFrameMutable() {
319 if (stackFrame == StackFrame.EMPTY) {
320 stackFrame = new StackFrame(null, SequenceTool.makeSequenceArray(0));
321 }
322 }
323
324 /**
325 * Get the value of a local variable, identified by its slot number
326 */
327
328 public final Sequence<?> evaluateLocalVariable(int slotnumber) {
329 return stackFrame.slots[slotnumber];
330 }
331
332 /**
333 * Set the value of a local variable, identified by its slot number
334 */
335
336 public final void setLocalVariable(int slotNumber, Sequence<?> value) throws XPathException {
337
338 // The following code is deep defence against attempting to store a non-memo Closure in a variable.
339 // This should not happen, and if it does, it means that the evaluation mode has been miscalculated.
340 // But if it does happen, we recover by wrapping the Closure in a MemoSequence which remembers the
341 // value as it is calculated.
342
343 value = value.makeRepeatable();
344 try {
345 stackFrame.slots[slotNumber] = value;
346 } catch (ArrayIndexOutOfBoundsException e) {
347 if (slotNumber == -999) {
348 throw new AssertionError("Internal error: Cannot set local variable: no slot allocated");
349 } else {
350 throw new AssertionError("Internal error: Cannot set local variable (slot " + slotNumber +
351 " of " + getStackFrame().getStackFrameValues().length + ")");
352 }
353 }
354 }
355
356 public synchronized void waitForChildThreads() throws XPathException {
357 getCaller().waitForChildThreads();
358 }
359
360 /**
361 * Change the Receiver to which output is written
362 */
363
364 public void setReceiver(Receiver receiver) {
365 // System.err.println("SET RECEIVER new=" + receiver);
366 currentReceiver = receiver;
367 }
368
369 /**
370 * Get the Receiver to which output is currently being written.
371 *
372 * @return the current Receiver
373 */
374 public final Receiver getReceiver() {
375 // System.err.println("GET RECEIVER return=" + currentReceiver);
376 return currentReceiver;
377 }
378
379 /**
380 * Set the XSLT output state to "temporary" or "final"
381 *
382 * @param temporary set non-zero to set temporary output state; zero to set final output state. The integer
383 * gives clues as to the reason temporary output state is being set, e.g. StandardNames.XSL_VARIABLE
384 * indicates we are evaluating a variable.
385 *
386 */
387
388 public void setTemporaryOutputState(int temporary) {
389 temporaryOutputState = temporary;
390 }
391
392 /**
393 * Ask whether the XSLT output state is "temporary" or "final"
394 *
395 * @return non-zero if in temporary output state (integer identifies the reason); zero if in final output state
396 */
397
398 public int getTemporaryOutputState() {
399 return temporaryOutputState;
400 }
401
402 /**
403 * Set the current output URI
404 * @param uri the current output URI, or null if in temporary output state
405 */
406
407 public void setCurrentOutputUri(String uri) {
408 currentDestination = uri;
409 }
410
411 /**
412 * Get the current output URI
413 * @return the current output URI, or null if in temporary output state
414 */
415
416 public String getCurrentOutputUri() {
417 return currentDestination;
418 }
419
420 /**
421 * Use local parameter. This is called when a local xsl:param element is processed.
422 * If a parameter of the relevant name was supplied, it is bound to the xsl:param element.
423 * Otherwise the method returns false, so the xsl:param default will be evaluated
424 *
425 * @param parameterId Globally-unique parameter identifier
426 * @param slotNumber Slot number of the parameter within the stack frame of the called template
427 * @param isTunnel True if a tunnel parameter is required, else false @return ParameterSet.NOT_SUPPLIED, ParameterSet.SUPPLIED, or ParameterSet.SUPPLIED_AND_CHECKED
428 */
429
430 public int useLocalParameter(
431 StructuredQName parameterId, int slotNumber, boolean isTunnel) throws XPathException {
432 return getCaller().useLocalParameter(parameterId, slotNumber, isTunnel);
433 }
434
435 /**
436 * Get the current mode.
437 *
438 * @return the current mode
439 */
440
441 public Component.M getCurrentMode() {
442 return getCaller().getCurrentMode();
443 }
444
445 /**
446 * Get the current template. This is used to support xsl:apply-imports
447 *
448 * @return the current template
449 */
450
451 public Rule getCurrentTemplateRule() {
452 // In a minor context, the current template rule is always null. This is a consequence
453 // of the way they are used.
454 return null;
455 //return getCaller().getCurrentTemplateRule();
456 }
457
458 /**
459 * Get the current group iterator. This supports the current-group() and
460 * current-grouping-key() functions in XSLT 2.0
461 *
462 * @return the current grouped collection
463 */
464
465 public GroupIterator getCurrentGroupIterator() {
466 return getCaller().getCurrentGroupIterator();
467 }
468
469 /**
470 * Get the current merge group iterator. This supports the current-merge-group() and
471 * current-merge-key() functions in XSLT 3.0
472 *
473 * @return the current grouped collection
474 */
475
476 public GroupIterator getCurrentMergeGroupIterator() {
477 return getCaller().getCurrentMergeGroupIterator();
478 }
479
480 /**
481 * Get the current regex iterator. This supports the functionality of the regex-group()
482 * function in XSLT 2.0.
483 *
484 * @return the current regular expressions iterator
485 */
486
487 public RegexIterator getCurrentRegexIterator() {
488 return getCaller().getCurrentRegexIterator();
489 }
490
491 /**
492 * Get the current date and time for this query or transformation.
493 * All calls during one transformation return the same answer.
494 *
495 * @return Get the current date and time. This will deliver the same value
496 * for repeated calls within the same transformation
497 */
498
499 public DateTimeValue getCurrentDateTime() {
500 return controller.getCurrentDateTime();
501 }
502
503 /**
504 * Get the implicit timezone, as a positive or negative offset from UTC in minutes.
505 * The range is -14hours to +14hours
506 *
507 * @return the implicit timezone as an offset from UTC in minutes
508 */
509
510 public final int getImplicitTimezone() {
511 return controller.getImplicitTimezone();
512 }
513
514 /**
515 * Get the context stack. This method returns an iterator whose items are instances of
516 * {@link net.sf.saxon.trace.ContextStackFrame}, starting with the top-most stackframe and
517 * ending at the point the query or transformation was invoked by a calling application.
518 *
519 * @return an iterator over a copy of the run-time call stack
520 */
521
522 public Iterator iterateStackFrames() {
523 return new ContextStackIterator(this);
524 }
525
526
527
528 public Component getTargetComponent(int bindingSlot) {
529 return getCaller().getTargetComponent(bindingSlot);
530 }
531
532 // Note: consider eliminating this class. A new XPathContextMinor is created under two circumstances,
533 // (a) when the focus changes (i.e., a new current iterator), and (b) when the current
534 // receiver changes. We could handle these by maintaining a stack of iterators and a stack of
535 // receivers in the XPathContextMajor object. Adding a new iterator or receiver to the stack would
536 // generally be cheaper than creating the new XPathContextMinor object. The main difficulty (in the
537 // case of iterators) is knowing when to pop the stack: currently we rely on the garbage collector.
538 // We can only really do this when the iterator comes to its end, which is difficult to detect.
539 // Perhaps we should try to do static allocation, so that fixed slots are allocated for different
540 // minor-contexts within a Procedure, and a compiled expression that uses the focus knows which
541 // slot to look in.
542
543 // Investigated the above Sept 2008. On xmark, with a 100Mb input, the path expression
544 // count(site/people/person/watches/watch) takes just 13ms to execute (compared with 6500ms for building
545 // the tree). Only 6 context objects are created while doing this. This doesn't appear to be a productive
546 // area to look for new optimizations.
547
548 /**
549 * Container for cached value of the last() function.
550 * This is shared between all context objects that share the same current iterator.
551 * Introduced in 9.2 to handle the case where a new context is introduced when the current
552 * outputter changes, without changing the current iterator: in this case the cached value
553 * was being lost because each call on last() used a different context object.
554 */
555
556 protected static class LastValue {
557 public int value = 0;
558
559 public LastValue(int count) {
560 value = count;
561 }
562 }
563 }
564