Debian Codegraph @

net/sf/saxon/expr/XPathContextMajor.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.Controller;
11 import net.sf.saxon.PreparedStylesheet;
12 import net.sf.saxon.expr.instruct.Executable;
13 import net.sf.saxon.expr.instruct.ParameterSet;
14 import net.sf.saxon.expr.instruct.SlotManager;
15 import net.sf.saxon.expr.sort.GroupIterator;
16 import net.sf.saxon.lib.DelegatingErrorListener;
17 import net.sf.saxon.lib.StandardURIResolver;
18 import net.sf.saxon.lib.UnfailingErrorListener;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.regex.RegexIterator;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.trans.XsltController;
23 import net.sf.saxon.trans.rules.Rule;
24 import net.sf.saxon.trans.rules.RuleManager;
25 import net.sf.saxon.tree.iter.SingletonIterator;
26 import net.sf.saxon.tree.iter.UnfailingIterator;
27
28 import javax.xml.transform.ErrorListener;
29 import javax.xml.transform.URIResolver;
30 import java.util.Arrays;
31
32 /**
33 * This class represents a "major context" in which an XPath expression is evaluated:
34 * a "major context" object allows all aspects of the dynamic context to change, whereas
35 * a "minor context" only allows changes to the focus and the destination for push output.
36 */
37
38 public class XPathContextMajor extends XPathContextMinor {
39
40 private ParameterSet localParameters;
41 private ParameterSet tunnelParameters;
42 /*@Nullable*/ private TailCallLoop.TailCallInfo tailCallInfo;
43 private Component.M currentMode;
44 /*@Nullable*/ private Rule currentTemplate;
45 private GroupIterator currentGroupIterator;
46 private GroupIterator currentMergeGroupIterator;
47 private RegexIterator currentRegexIterator;
48 private ContextOriginator origin;
49 private ThreadManager threadManager = null;
50
51 private URIResolver uriResolver;
52 private UnfailingErrorListener errorListener;
53 private Component currentComponent;
54 XPathException currentException;
55
56
57 /**
58 * Constructor should only be called by the Controller,
59 * which acts as a XPathContext factory.
60 *
61 * @param controller the Controller
62 */
63
64 public XPathContextMajor(Controller controller) {
65 this.controller = controller;
66 stackFrame = StackFrame.EMPTY;
67 origin = controller;
68 }
69
70
71 /**
72 * Private Constructor
73 */
74
75 private XPathContextMajor() {
76 }
77
78 /**
79 * Constructor for use in free-standing Java applications.
80 *
81 * @param item the item to use as the initial context item. If this is null,
82 * the comtext item is initially undefined (which will cause a dynamic error
83 * if it is referenced).
84 * @param exec the Executable
85 */
86
87 public XPathContextMajor(Item<?> item, Executable exec) {
88 controller = exec instanceof PreparedStylesheet ?
89 new XsltController(exec.getConfiguration(), (PreparedStylesheet)exec) :
90 new Controller(exec.getConfiguration(), exec);
91 if (item != null) {
92 UnfailingIterator<?> iter = SingletonIterator.makeIterator(item);
93 currentIterator = new FocusTrackingIterator<>(iter);
94 try {
95 currentIterator.next();
96 } catch (XPathException e) {
97 // cannot happen
98 }
99 last = new LastValue(1);
100 }
101 origin = controller;
102 }
103
104 /**
105 * Construct a new context as a copy of another. The new context is effectively added
106 * to the top of a stack, and contains a pointer to the previous context.
107 */
108
109 public XPathContextMajor newContext() {
110 XPathContextMajor c = new XPathContextMajor();
111 c.controller = controller;
112 c.currentIterator = currentIterator;
113 c.stackFrame = stackFrame;
114 c.localParameters = localParameters;
115 c.tunnelParameters = tunnelParameters;
116 c.last = last;
117 c.currentReceiver = currentReceiver;
118 c.currentDestination = currentDestination;
119 c.currentMode = currentMode;
120 c.currentTemplate = currentTemplate;
121 c.currentRegexIterator = currentRegexIterator;
122 c.currentGroupIterator = currentGroupIterator;
123 c.currentMergeGroupIterator = currentMergeGroupIterator;
124 c.currentException = currentException;
125 c.caller = this;
126 c.tailCallInfo = null;
127 c.temporaryOutputState = temporaryOutputState;
128 c.threadManager = threadManager;
129 c.currentComponent = currentComponent;
130 c.errorListener = errorListener;
131 c.uriResolver = uriResolver;
132 return c;
133 }
134
135 /**
136 * Create a new "major" context (one that is capable of holding a stack frame with local variables
137 *
138 * @param prev the previous context (the one causing the new context to be created)
139 * @return the new major context
140 */
141
142 public static XPathContextMajor newContext(XPathContextMinor prev) {
143 XPathContextMajor c = new XPathContextMajor();
144 XPathContext p = prev;
145 while (!(p instanceof XPathContextMajor)) {
146 p = p.getCaller();
147 }
148 c.controller = p.getController();
149 c.currentIterator = prev.getCurrentIterator();
150 c.stackFrame = prev.getStackFrame();
151 c.localParameters = p.getLocalParameters();
152 c.tunnelParameters = p.getTunnelParameters();
153 c.last = prev.last;
154 c.currentReceiver = prev.currentReceiver;
155 c.currentDestination = prev.currentDestination;
156 c.currentMode = p.getCurrentMode();
157 c.currentTemplate = p.getCurrentTemplateRule();
158 c.currentRegexIterator = p.getCurrentRegexIterator();
159 c.currentGroupIterator = p.getCurrentGroupIterator();
160 c.currentMergeGroupIterator = null;
161 c.caller = prev;
162 c.tailCallInfo = null;
163 c.threadManager = ((XPathContextMajor) p).threadManager;
164 c.currentComponent = ((XPathContextMajor) p).currentComponent;
165 c.errorListener = ((XPathContextMajor) p).errorListener;
166 c.uriResolver = ((XPathContextMajor) p).uriResolver;
167 c.temporaryOutputState = prev.temporaryOutputState;
168 return c;
169 }
170
171 /**
172 * Make a copy of the supplied context for use in a new thread (typically for
173 * an asynchronous xsl:result-document
174 *
175 * @param prev the context to be copied
176 * @return the copy of the context
177 */
178
179 public static XPathContextMajor newThreadContext(XPathContextMinor prev) {
180 XPathContextMajor c = newContext(prev);
181 c.stackFrame = prev.stackFrame.copy();
182 return c;
183 }
184
185 /**
186 * The ThreadManager is used to manage asynchronous execution of xsl:result-document instructions in Saxon-EE.
187 * This is a dummy implementation for Saxon-HE and Saxon-PE; it is subclassed in Saxon-EE
188 */
189
190 public abstract static class ThreadManager {
191 public abstract void waitForChildThreads() throws XPathException;
192 }
193
194 /**
195 * Get the thread manager in use for this context.
196 *
197 * @return the current thread manager. This will be null if not running XSLT under Saxon-EE
198 */
199 public ThreadManager getThreadManager() {
200 return threadManager;
201 }
202
203 /**
204 * Create a new thread manager. This is called when starting an XSLT Transformation, and also
205 * when entering a try/catch block. In Saxon-HE it does nothing.
206 */
207
208 public void createThreadManager() {
209 threadManager = getConfiguration().makeThreadManager();
210 }
211
212 /**
213 * Wait for child threads started under the control of this context to finish.
214 * This is called at the end of the (main thread of a) transformation, and also
215 * at the end of the "try" part of a try/catch. The threads affected are those
216 * used to implement xsl:result-document instructions.
217 *
218 * @throws XPathException if any of the child threads have failed with a dynamic
219 * error.
220 */
221
222 public void waitForChildThreads() throws XPathException {
223 if (threadManager != null) {
224 threadManager.waitForChildThreads();
225 }
226 }
227
228
229 /**
230 * Get the local parameters for the current template call.
231 *
232 * @return the supplied parameters
233 */
234
235 public ParameterSet getLocalParameters() {
236 if (localParameters == null) {
237 localParameters = new ParameterSet();
238 }
239 return localParameters;
240 }
241
242 /**
243 * Set the local parameters for the current template call.
244 *
245 * @param localParameters the supplied parameters
246 */
247
248 public void setLocalParameters(ParameterSet localParameters) {
249 this.localParameters = localParameters;
250 }
251
252 /**
253 * Get the tunnel parameters for the current template call.
254 *
255 * @return the supplied tunnel parameters
256 */
257
258 public ParameterSet getTunnelParameters() {
259 return tunnelParameters;
260 }
261
262 /**
263 * Set the tunnel parameters for the current template call.
264 *
265 * @param tunnelParameters the supplied tunnel parameters
266 */
267
268 public void setTunnelParameters(ParameterSet tunnelParameters) {
269 this.tunnelParameters = tunnelParameters;
270 }
271
272 /**
273 * Set the creating expression (for use in diagnostics). The origin is generally set to "this" by the
274 * object that creates the new context. It's up to the debugger to determine whether this information
275 * is useful. The object will either be an {@link Expression}, allowing information
276 * about the calling instruction to be obtained, or null.
277 */
278
279 public void setOrigin(ContextOriginator expr) {
280 origin = expr;
281 }
282
283 /**
284 * Get information about the creating expression or other construct.
285 */
286
287 public ContextOriginator getOrigin() {
288 return origin;
289 }
290
291
292 /**
293 * Set the local stack frame. This method is used when creating a Closure to support
294 * delayed evaluation of expressions. The "stack frame" is actually on the Java heap, which
295 * means it can survive function returns and the like.
296 *
297 * @param map the SlotManager, which holds static details of the allocation of variables to slots
298 * @param variables the array of "slots" to hold the actual variable values. This array will be
299 * copied if it is too small to hold all the variables defined in the SlotManager
300 */
301
302 public void setStackFrame(SlotManager map, Sequence[] variables) {
303 stackFrame = new StackFrame(map, variables);
304 if (map != null && variables.length != map.getNumberOfVariables()) {
305 if (variables.length > map.getNumberOfVariables()) {
306 throw new IllegalStateException(
307 "Attempting to set more local variables (" + variables.length +
308 ") than the stackframe can accommodate (" + map.getNumberOfVariables() + ")");
309 }
310 stackFrame.slots = (Sequence<?>[])new Sequence[map.getNumberOfVariables()];
311 System.arraycopy(variables, 0, stackFrame.slots, 0, variables.length);
312 }
313 }
314
315 /**
316 * Reset the stack frame variable map, while reusing the StackFrame object itself. This
317 * is done on a tail call to a different function
318 *
319 * @param map the SlotManager representing the stack frame contents
320 * @param numberOfParams the number of parameters required on the new stack frame
321 */
322
323 public void resetStackFrameMap(SlotManager map, int numberOfParams) {
324 stackFrame.map = map;
325 if (stackFrame.slots.length != map.getNumberOfVariables()) {
326 Sequence<?>[] v2 =
327 (Sequence<?>[])new Sequence[map.getNumberOfVariables()];
328 System.arraycopy(stackFrame.slots, 0, v2, 0, numberOfParams);
329 stackFrame.slots = v2;
330 } else {
331 // not strictly necessary
332 Arrays.fill(stackFrame.slots, numberOfParams, stackFrame.slots.length, null);
333 }
334 }
335
336 /**
337 * Get a all the variables in the stack frame
338 *
339 * @return an array holding all the variables, each referenceable by its slot number
340 */
341
342 public Sequence[] getAllVariableValues() {
343 return stackFrame.getStackFrameValues();
344 }
345
346 /**
347 * Overwrite all the variables in the stack frame
348 *
349 * @param values an array holding all the variables, each referenceable by its slot number;
350 * the caller must ensure this is the correct length (and valid in other ways)
351 */
352
353 public void resetAllVariableValues(Sequence[] values) {
354 stackFrame.setStackFrameValues(values);
355 }
356
357 /**
358 * Overwrite all the parameters in the stack frame. (Used from compiled bytecode)
359 *
360 * @param values an array holding all the parameters, each referenceable by its slot number;
361 * the caller must ensure this is the correct length (and valid in other ways)
362 */
363
364 public void resetParameterValues(Sequence[] values) {
365 System.arraycopy(values, 0, stackFrame.slots, 0, values.length);
366 }
367
368 /**
369 * Reset the local stack frame. This method is used when processing a tail-recursive function.
370 * Instead of the function being called recursively, the parameters are set to new values and the
371 * function body is evaluated repeatedly
372 *
373 * @param targetFn the user function being called using tail recursion
374 * @param variables the parameter to be supplied to the user function
375 */
376
377 public void requestTailCall(TailCallLoop.TailCallInfo targetFn, Sequence<?>[] variables) {
378 if (variables != null) {
379 if (variables.length > stackFrame.slots.length) {
380 stackFrame.slots = Arrays.copyOf(variables, variables.length);
381 } else {
382 System.arraycopy(variables, 0, stackFrame.slots, 0, variables.length);
383 }
384 }
385 tailCallInfo = targetFn;
386 }
387
388
389 /**
390 * Determine whether the body of a function is to be repeated, due to tail-recursive function calls
391 *
392 * @return null if no tail call has been requested, or the name of the function to be called otherwise
393 */
394
395 public TailCallLoop.TailCallInfo getTailCallInfo() {
396 TailCallLoop.TailCallInfo fn = tailCallInfo;
397 tailCallInfo = null;
398 return fn;
399 }
400
401 /**
402 * Create a new stack frame for local variables, using the supplied SlotManager to
403 * define the allocation of slots to individual variables
404 *
405 * @param map the SlotManager for the new stack frame
406 */
407 public void openStackFrame(SlotManager map) {
408 int numberOfSlots = map.getNumberOfVariables();
409 if (numberOfSlots == 0) {
410 stackFrame = StackFrame.EMPTY;
411 } else {
412 stackFrame = new StackFrame(map, new Sequence[numberOfSlots]);
413 }
414 }
415
416 /**
417 * Create a new stack frame large enough to hold a given number of local variables,
418 * for which no stack frame map is available. This is used in particular when evaluating
419 * match patterns of template rules.
420 *
421 * @param numberOfVariables The number of local variables to be accommodated.
422 */
423
424 public void openStackFrame(int numberOfVariables) {
425 stackFrame = new StackFrame(new SlotManager(numberOfVariables),
426 SequenceTool.makeSequenceArray(numberOfVariables));
427 }
428
429 /**
430 * Set the current mode.
431 *
432 * @param mode the new current mode
433 */
434
435 public void setCurrentMode(Component.M mode) {
436 this.currentMode = mode;
437 }
438
439 /**
440 * Get the current mode.
441 *
442 * @return the current mode. May return null if the current mode is the default mode.
443 */
444
445 public Component.M getCurrentMode() {
446 Component.M m = currentMode;
447 if (m == null) {
448 RuleManager rm = getController().getRuleManager();
449 if (rm != null) {
450 return rm.getUnnamedMode().getDeclaringComponent();
451 } else {
452 return null;
453 }
454 } else {
455 return m;
456 }
457 }
458
459 /**
460 * Set the current template. This is used to support xsl:apply-imports. The caller
461 * is responsible for remembering the previous current template and resetting it
462 * after use.
463 *
464 * @param rule the current template rule, or null to indicate that there is no current template rule
465 */
466
467 public void setCurrentTemplateRule(/*@Nullable*/ Rule rule) {
468 this.currentTemplate = rule;
469 }
470
471 /**
472 * Get the current template. This is used to support xsl:apply-imports
473 *
474 * @return the current template
475 */
476
477 public Rule getCurrentTemplateRule() {
478 return currentTemplate;
479 }
480
481 /**
482 * Set the current grouping iterator. This supports the current-group() and
483 * current-grouping-key() functions in XSLT 2.0
484 *
485 * @param iterator the new current GroupIterator
486 */
487
488 public void setCurrentGroupIterator(GroupIterator iterator) {
489 this.currentGroupIterator = iterator;
490 }
491
492 /**
493 * Get the current group iterator. This supports the current-group() and
494 * current-grouping-key() functions in XSLT 2.0
495 *
496 * @return the current grouped collection
497 */
498
499 public GroupIterator getCurrentGroupIterator() {
500 return currentGroupIterator;
501 }
502
503 /**
504 * Set the current merge group iterator. This supports the current-merge-group() and
505 * current-merge-key() functions in XSLT 3.0
506 *
507 * @param iterator the new current GroupIterator
508 */
509
510 public void setCurrentMergeGroupIterator(GroupIterator iterator) {
511 this.currentMergeGroupIterator = iterator;
512 }
513
514 /**
515 * Get the current merge group iterator. This supports the current-merge-group() and
516 * current-merge-key() functions in XSLT 3.0
517 *
518 * @return the current grouped collection
519 */
520
521 public GroupIterator getCurrentMergeGroupIterator() {
522 return currentMergeGroupIterator;
523 }
524
525 /**
526 * Set the current regex iterator. This supports the functionality of the regex-group()
527 * function in XSLT 2.0.
528 *
529 * @param currentRegexIterator the current regex iterator
530 */
531
532 public void setCurrentRegexIterator(RegexIterator currentRegexIterator) {
533 this.currentRegexIterator = currentRegexIterator;
534 }
535
536 /**
537 * Get the current regex iterator. This supports the functionality of the regex-group()
538 * function in XSLT 2.0.
539 *
540 * @return the current regular expressions iterator
541 */
542
543 public RegexIterator getCurrentRegexIterator() {
544 return currentRegexIterator;
545 }
546
547 /**
548 * Use local parameter. This is called when a local xsl:param element is processed.
549 * If a parameter of the relevant name was supplied, it is bound to the xsl:param element.
550 * Otherwise the method returns false, so the xsl:param default will be evaluated
551 *
552 * @param paramName the name of the parameter
553 * @param slotNumber the slot number of the parameter on the callee's stack frame
554 * @param isTunnel True if a tunnel parameter is required, else false
555 * @return ParameterSet.NOT_SUPPLIED, ParameterSet.SUPPLIED, or ParameterSet.SUPPLIED_AND_CHECKED
556 */
557
558 public int useLocalParameter(
559 StructuredQName paramName, int slotNumber, boolean isTunnel) throws XPathException {
560
561 ParameterSet params = isTunnel ? getTunnelParameters() : localParameters;
562 if (params == null) {
563 return ParameterSet.NOT_SUPPLIED;
564 }
565 int index = params.getIndex(paramName);
566 if (index < 0) {
567 return ParameterSet.NOT_SUPPLIED;
568 }
569 Sequence<?> val = params.getValue(index);
570 stackFrame.slots[slotNumber] = val;
571 boolean checked = params.isTypeChecked(index);
572 return checked ? ParameterSet.SUPPLIED_AND_CHECKED : ParameterSet.SUPPLIED;
573 }
574
575 /**
576 * Set an object that will be used to resolve URIs used in
577 * document(), etc. This method allows a URIResolver to be set that is local
578 * to this particular XPathContext, which is useful when local behaviour is
579 * needed, e.g. during schema validation. The URIResolver set in the Controller
580 * and in the Configuration are not affected by this call.
581 *
582 * @param resolver An object that implements the URIResolver interface, or
583 * null.
584 * @since 9.6
585 */
586
587 public void setURIResolver(URIResolver resolver) {
588 uriResolver = resolver;
589 if (resolver instanceof StandardURIResolver) {
590 ((StandardURIResolver) resolver).setConfiguration(getConfiguration());
591 }
592 }
593
594 /**
595 * Get the URI resolver. This gets the local URIResolver set in the XPathContext if there
596 * is one; if not, it gets the URIResolver from the Controller (which itself defaults to the
597 * one set in the Configuration).
598 *
599 * @return the user-supplied URI resolver if there is one, or null otherwise.
600 * @since 9.6
601 */
602
603 public URIResolver getURIResolver() {
604 return uriResolver == null ? controller.getURIResolver() : uriResolver;
605 }
606
607 /**
608 * Set the error listener. The ErrorListener is set locally to this XPathContext
609 * object.
610 *
611 * @param listener the ErrorListener to be used
612 * @since 9.6
613 */
614
615 public void setErrorListener(ErrorListener listener) {
616 if (listener instanceof UnfailingErrorListener) {
617 errorListener = (UnfailingErrorListener) listener;
618 } else {
619 errorListener = new DelegatingErrorListener(listener);
620 }
621 }
622
623 /**
624 * Get the error listener. If no ErrorListener
625 * has been set locally, the ErrorListener in the Controller is returned; this in turn defaults
626 * to the ErrorListener set in the Configuration.
627 *
628 * @return the ErrorListener in use. Note that this is not necessarily the ErrorListener that was supplied
629 * to the {@link #setErrorListener(ErrorListener)} method; if that was not an {@link UnfailingErrorListener},
630 * it will have been wrapped in a {@link DelegatingErrorListener}, and it is the DelegatingErrorListener
631 * that this method returns.
632 * @since 9.6
633 */
634
635 public UnfailingErrorListener getErrorListener() {
636 return errorListener == null ? controller.getErrorListener() : errorListener;
637 }
638
639 /**
640 * Set the current exception (in saxon:catch)
641 *
642 * @param exception the current exception
643 */
644
645 public void setCurrentException(XPathException exception) {
646 currentException = exception;
647 }
648
649 /**
650 * Get the current exception (in saxon:catch)
651 *
652 * @return the current exception, or null if there is none defined
653 */
654
655 public XPathException getCurrentException() {
656 return currentException;
657 }
658
659 /**
660 * Get the current component
661 */
662
663 public Component getCurrentComponent() {
664 return currentComponent;
665 }
666
667 /**
668 * Set the current component, that is, the component being evaluated. This is used during the evaluation
669 * to determine the bindings to other components (such as global variables, functions, and templates) referenced
670 * during the evaluation
671 * @param component the current component
672 */
673
674 public void setCurrentComponent(Component component) {
675 //System.err.println("Set current component := " + (component==null ? "null" : component.getCode()));
676 currentComponent = component;
677 }
678
679 /**
680 * Bind a component reference to a component. This is used for binding component references
681 * (such as function calls, global variable references, or xsl:call-template) across package
682 * boundaries. The binding is done dynamically because, in the presence of overridden components,
683 * the choice among different components with the same name depends on which package the caller
684 * is in.
685 *
686 * @param bindingSlot Binding slots are allocated statically to the external component references
687 * in every component: for example, in the case of a template, to all global
688 * variable references, named function calls, and named template calls within
689 * that template. The binding slot therefore identifies the name of the
690 * component that is required; and the selection of an actual component is
691 * done by selection from the binding vector of the component currently being
692 * executed
693 * @return the component to be invoked
694 */
695 public Component getTargetComponent(int bindingSlot) {
696 try {
697 ComponentBinding binding = currentComponent.getComponentBindings().get(bindingSlot);
698 return binding.getTarget();
699 } catch (NullPointerException e) {
700 // Suggests that the current component is null, which would be a bug
701 e.printStackTrace();
702 throw e;
703 } catch (IndexOutOfBoundsException e) {
704 // Suggests that the current component's binding vector is the wrong size, which would be a bug.
705 //System.err.println("Current component = " + currentComponent.getCode());
706 e.printStackTrace();
707 throw e;
708 }
709 }
710 }
711