Debian Codegraph @

net/sf/saxon/trans/Mode.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.trans;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.PipelineConfiguration;
13 import net.sf.saxon.expr.Component;
14 import net.sf.saxon.expr.XPathContext;
15 import net.sf.saxon.expr.XPathContextMajor;
16 import net.sf.saxon.expr.accum.Accumulator;
17 import net.sf.saxon.expr.instruct.Actor;
18 import net.sf.saxon.expr.instruct.ParameterSet;
19 import net.sf.saxon.expr.instruct.TailCall;
20 import net.sf.saxon.expr.instruct.TemplateRule;
21 import net.sf.saxon.expr.parser.Location;
22 import net.sf.saxon.lib.NamespaceConstant;
23 import net.sf.saxon.lib.TraceListener;
24 import net.sf.saxon.lib.TraceListener2;
25 import net.sf.saxon.om.*;
26 import net.sf.saxon.trace.ExpressionPresenter;
27 import net.sf.saxon.trace.ModeTraceListener;
28 import net.sf.saxon.trans.rules.*;
29 import net.sf.saxon.tree.iter.LookaheadIterator;
30 import net.sf.saxon.type.BuiltInAtomicType;
31 import net.sf.saxon.type.SchemaType;
32 import net.sf.saxon.type.Type;
33 import net.sf.saxon.type.Untyped;
34
35 import java.util.Collections;
36 import java.util.Set;
37
38 /**
39 * A Mode is a collection of rules; the selection of a rule to apply to a given element
40 * is determined by a Pattern. A SimpleMode is a mode contained within a single package,
41 * as opposed to a CompoundMode which can combine rules from several packages
42 */
43
44 public abstract class Mode extends Actor {
45
46 public static final StructuredQName OMNI_MODE =
47 new StructuredQName("saxon", NamespaceConstant.SAXON, "_omniMode");
48 public static final StructuredQName UNNAMED_MODE_NAME =
49 new StructuredQName("xsl", NamespaceConstant.XSLT, "unnamed");
50 public static final StructuredQName DEFAULT_MODE_NAME =
51 new StructuredQName("xsl", NamespaceConstant.XSLT, "default");
52
53
54 protected StructuredQName modeName;
55 private boolean streamable;
56 private int recoveryPolicy = Configuration.RECOVER_WITH_WARNINGS; // since 9.2 fixed at compile time
57 public boolean mustBeTyped = false;
58 public boolean mustBeUntyped = false;
59 boolean hasRules = false;
60 boolean bindingSlotsAllocated = false;
61 boolean modeTracing = false;
62
63 private Set<? extends Accumulator> accumulators;
64
65
66 public Mode(StructuredQName modeName) {
67 this.modeName = modeName;
68 }
69
70 @Override
71 public Component.M getDeclaringComponent() {
72 return (Component.M)super.getDeclaringComponent();
73 }
74
75 /**
76 * Get the built-in template rules to be used with this Mode in the case where there is no
77 * explicit template rule
78 *
79 * @return the built-in rule set, defaulting to the TextOnlyCopyRuleSet if no other rule set has
80 * been supplied
81 */
82
83 public abstract BuiltInRuleSet getBuiltInRuleSet();
84
85 /**
86 * Determine if this is the unnamed mode
87 *
88 * @return true if this is the unnamed mode
89 */
90
91 public boolean isUnnamedMode() {
92 return modeName.equals(UNNAMED_MODE_NAME);
93 }
94
95 /**
96 * Get the name of the mode (for diagnostics only)
97 *
98 * @return the mode name. Null for the default (unnamed) mode
99 */
100
101 public StructuredQName getModeName() {
102 return modeName;
103 }
104
105 /**
106 * Get the active component of this mode. For a simple mode this is the mode itself;
107 * for a compound mode it is the "overriding" part
108 */
109
110 public abstract SimpleMode getActivePart();
111
112 /**
113 * Get the maximum precedence of the rules in this mode
114 */
115
116 public abstract int getMaxPrecedence();
117
118 /**
119 * Get the highest rank of the rules in this mode
120 *
121 * @return the highest rank
122 */
123
124 public abstract int getMaxRank();
125
126 /**
127 * Compute a rank for each rule, as a combination of the precedence and priority, to allow
128 * rapid comparison. This method also checks that there are no conflicts for
129 * property values in different xsl:mode declarations
130 *
131 * @param start the lowest rank to use
132 * @throws XPathException if an error occurs processing the rules
133 */
134
135 public abstract void computeRankings(int start) throws XPathException;
136
137 /**
138 * Get a title for the mode: either "Mode mode-name" or "The unnamed mode" as appropriate
139 *
140 * @return a title for the mode
141 */
142
143 public String getModeTitle() {
144 return isUnnamedMode() ? "The unnamed mode" : "Mode " + getModeName().getDisplayName();
145 }
146
147 /**
148 * Switch tracing on or off
149 */
150
151 public void setModeTracing(boolean tracing) {
152 this.modeTracing = tracing;
153 }
154
155 public boolean isModeTracing() {
156 return modeTracing;
157 }
158
159 /**
160 * Get the list of accumulators declared on the xsl:mode/@use-accumulators attribute
161 *
162 * @return the list of accumulators applicable when this is the initial mode
163 */
164 public Set<? extends Accumulator> getAccumulators() {
165 return accumulators == null ? Collections.emptySet() : accumulators;
166 }
167
168 /**
169 * Set the list of accumulators declared on the xsl:mode/@use-accumulators attribute
170 *
171 * @param accumulators the list of accumulators applicable when this is the initial mode
172 */
173
174 public void setAccumulators(Set<? extends Accumulator> accumulators) {
175 this.accumulators = accumulators;
176 }
177
178
179 @Override
180 public int getComponentKind() {
181 return StandardNames.XSL_MODE;
182 }
183
184 @Override
185 public SymbolicName getSymbolicName() {
186 return new SymbolicName(StandardNames.XSL_MODE, getModeName());
187 }
188
189 public int getConstructType() {
190 return StandardNames.XSL_MODE;
191 }
192
193 public StructuredQName getObjectName() {
194 return getModeName();
195 }
196
197 /**
198 * Ask whether there are any template rules in this mode
199 * (a mode could exist merely because it is referenced in apply-templates)
200 *
201 * @return true if no template rules exist in this mode
202 */
203
204 public abstract boolean isEmpty();
205
206 /**
207 * Set the policy for handling recoverable errors. Note that for some errors the decision can be
208 * made at run-time, but for the "ambiguous template match" error, the decision is (since 9.2)
209 * fixed at compile time.
210 *
211 * @param policy the recovery policy to be used. The options are {@link Configuration#RECOVER_SILENTLY},
212 * {@link Configuration#RECOVER_WITH_WARNINGS}, or {@link Configuration#DO_NOT_RECOVER}.
213 */
214
215 public void setRecoveryPolicy(int policy) {
216 recoveryPolicy = policy;
217 }
218
219 public void setHasRules(boolean hasRules) {
220 this.hasRules = hasRules;
221 }
222
223 /**
224 * Get the policy for handling recoverable errors. Note that for some errors the decision can be
225 * made at run-time, but for the "ambiguous template match" error, the decision is (since 9.2)
226 * fixed at compile time.
227 *
228 * @return the current policy.
229 */
230
231 public int getRecoveryPolicy() {
232 return recoveryPolicy;
233 }
234
235 /**
236 * Say that this mode is (or is not) streamable
237 *
238 * @param streamable true if this mode is a streamable mode
239 */
240
241 public void setStreamable(boolean streamable) {
242 this.streamable = streamable;
243 }
244
245 /**
246 * Ask whether this mode is declared to be streamable
247 *
248 * @return true if this mode is declared with the option streamable="yes"
249 */
250
251 public boolean isDeclaredStreamable() {
252 return streamable;
253 }
254
255
256 /**
257 * Get the "explicit namespaces" matched by this mode. Returns a set containing all the namespaces
258 * matched by specific template rules in this mode
259 *
260 * @param pool the NamePool for the configuration
261 * @return the set of all namespace URIs of names explicitly matched by rules in this mode
262 */
263
264 public abstract Set<String> getExplicitNamespaces(NamePool pool);
265
266
267 /**
268 * Walk over all the rules, applying a specified action to each one.
269 *
270 * @param action an action that is to be applied to all the rules in this Mode
271 * @throws XPathException if an error occurs processing any of the rules
272 */
273
274 public abstract void processRules(RuleAction action) throws XPathException;
275
276
277 /**
278 * Make a new XPath context for evaluating patterns if there is any possibility that the
279 * pattern uses local variables
280 *
281 * @param context The existing XPath context
282 * @return a new XPath context
283 */
284
285 public XPathContext makeNewContext(XPathContext context) {
286 XPathContextMajor c2 = context.newContext();
287 c2.setOrigin(context.getController()); // WHY?
288 c2.openStackFrame(getStackFrameSlotsNeeded());
289 if (!(context.getCurrentComponent().getActor() instanceof Accumulator)) {
290 c2.setCurrentComponent(context.getCurrentMode()); // bug 3706
291 }
292 return c2;
293 }
294
295 /**
296 * Get the rule corresponding to a given item, by finding the best pattern match.
297 *
298 * @param item the item to be matched
299 * @param context the XPath dynamic evaluation context
300 * @return the best matching rule, if any (otherwise null).
301 * @throws XPathException if an error occurs matching a pattern
302 */
303
304 public abstract Rule getRule(Item item, XPathContext context) throws XPathException;
305
306 /**
307 * Get the rule corresponding to a given item, by finding the best Pattern match.
308 *
309 * @param item the item to be matched
310 * @param context the XPath dynamic evaluation context
311 * @param filter a filter to select which rules should be considered
312 * @return the best matching rule, if any (otherwise null).
313 * @throws XPathException if an error occurs
314 */
315
316
317 /*@Nullable*/
318 public abstract Rule getRule(Item item, XPathContext context, SimpleMode.RuleFilter filter) throws XPathException;
319
320 /**
321 * Get the rule corresponding to a given Node, by finding the best Pattern match, subject to a minimum
322 * and maximum precedence. (This supports xsl:apply-imports)
323 *
324 * @param item the item to be matched
325 * @param min the minimum import precedence
326 * @param max the maximum import precedence
327 * @param context the XPath dynamic evaluation context
328 * @return the Rule registered for that node, if any (otherwise null).
329 * @throws XPathException if an error occurs evaluating match patterns
330 */
331
332 public Rule getRule(Item item, final int min, final int max, XPathContext context) throws XPathException {
333 RuleFilter filter = r -> {
334 int p = r.getPrecedence();
335 return p >= min && p <= max;
336 };
337 return getRule(item, context, filter);
338 }
339
340 /**
341 * Get the rule corresponding to a given Node, by finding the next-best Pattern match
342 * after the specified object.
343 *
344 * @param item the NodeInfo referring to the node to be matched
345 * @param currentRule the current rule; we are looking for the next match after the current rule
346 * @param context the XPath dynamic evaluation context
347 * @return the object (e.g. a NodeHandler) registered for that element, if any (otherwise null).
348 * @throws XPathException if an error occurs matching a pattern
349 */
350
351 public Rule getNextMatchRule(Item item, final Rule currentRule, XPathContext context) throws XPathException {
352 SimpleMode.RuleFilter filter = r -> {
353 int comp = r.compareRank(currentRule);
354 if (comp < 0) {
355 // the rule has lower precedence or priority than the current rule
356 return true;
357 } else if (comp == 0) {
358 int seqComp = Integer.compare(r.getSequence(), currentRule.getSequence());
359 if (seqComp < 0) {
360 // the rule is before the current rule in declaration order
361 return true;
362 } else if (seqComp == 0) {
363 // we have two branches of the same union pattern; examine the parent pattern to see which is first
364 return r.getPartNumber() < currentRule.getPartNumber();
365 }
366 }
367 return false;
368 };
369 return getRule(item, context, filter);
370 }
371
372 /**
373 * Export all template rules in this mode in a form that can be re-imported.
374 * Note that template rules with union patterns may have been split into multiple
375 * rules. We need to avoid outputting them more than once.
376 *
377 * @param out used to display the expression tree
378 */
379
380 public abstract void exportTemplateRules(ExpressionPresenter out) throws XPathException;
381
382 /**
383 * Explain all template rules in this mode in a form that can be re-imported.
384 * Note that template rules with union patterns may have been split into multiple
385 * rules. We need to avoid outputting them more than once.
386 *
387 * @param out used to display the expression tree
388 */
389
390 public abstract void explainTemplateRules(ExpressionPresenter out) throws XPathException;
391
392
393 /**
394 * Process selected nodes using the template rules registered for this mode.
395 *
396 * @param parameters A ParameterSet containing the parameters to
397 * the handler/template being invoked. Specify null if there are no
398 * parameters.
399 * @param tunnelParameters A ParameterSet containing the parameters to
400 * the handler/template being invoked. Specify null if there are no
401 * parameters.
402 * @param context A newly-created context object (this must be freshly created by the caller,
403 * as it will be modified by this method). The nodes to be processed are those
404 * selected by the currentIterator in this context object. There is also a precondition
405 * that this mode must be the current mode in this context object.
406 * @param locationId location of this apply-templates instruction in the stylesheet
407 * @return a TailCall returned by the last template to be invoked, or null,
408 * indicating that there are no outstanding tail calls.
409 * @throws XPathException if any dynamic error occurs
410 */
411
412 /*@Nullable*/
413 public TailCall applyTemplates(
414 ParameterSet parameters,
415 ParameterSet tunnelParameters,
416 XPathContextMajor context,
417 Location locationId)
418 throws XPathException {
419 Controller controller = context.getController();
420 boolean tracing = modeTracing || controller.isTracing();
421 PipelineConfiguration pipe = context.getReceiver().getPipelineConfiguration();
422 SequenceIterator iterator = context.getCurrentIterator();
423 TailCall tc = null;
424 TraceListener traceListener = null;
425 if (tracing) {
426 traceListener = controller.getTraceListener();
427 if (traceListener == null) {
428 traceListener = new ModeTraceListener();
429 controller.setTraceListener(traceListener);
430 traceListener.open(controller);
431 }
432 }
433
434 // Iterate over this sequence
435
436 boolean lookahead = (iterator.getProperties() & SequenceIterator.LOOKAHEAD) != 0;
437 TemplateRule previousTemplate = null;
438 while (true) {
439
440 // process any tail calls returned from previous nodes. We need to do this before changing
441 // the context. If we have a LookaheadIterator, we can tell whether we're positioned at the
442 // end without changing the current position, and we can then return the last tail call to
443 // the caller and execute it further down the stack, reducing the risk of running out of stack
444 // space. In other cases, we need to execute the outstanding tail calls before moving the iterator
445
446 if (tc != null) {
447 if (lookahead && !((LookaheadIterator) iterator).hasNext()) {
448 break;
449 }
450 do {
451 tc = tc.processLeavingTail();
452 } while (tc != null);
453 }
454
455 Item item = iterator.next();
456 if (item == null) {
457 break;
458 }
459
460 if (mustBeTyped) {
461 if (item instanceof NodeInfo) {
462 int kind = ((NodeInfo) item).getNodeKind();
463 if (kind == Type.ELEMENT || kind == Type.ATTRIBUTE) {
464 SchemaType annotation = ((NodeInfo) item).getSchemaType();
465 if (annotation == Untyped.getInstance() || annotation == BuiltInAtomicType.UNTYPED_ATOMIC) {
466 throw new XPathException(getModeTitle() + " requires typed nodes, but the input is untyped", "XTTE3100");
467 }
468 }
469 }
470 } else if (mustBeUntyped) {
471 if (item instanceof NodeInfo) {
472 int kind = ((NodeInfo) item).getNodeKind();
473 if (kind == Type.ELEMENT || kind == Type.ATTRIBUTE) {
474 SchemaType annotation = ((NodeInfo) item).getSchemaType();
475 if (!(annotation == Untyped.getInstance() || annotation == BuiltInAtomicType.UNTYPED_ATOMIC)) {
476 throw new XPathException(getModeTitle() + " requires untyped nodes, but the input is typed", "XTTE3110");
477 }
478 }
479 }
480 }
481
482 // find the template rule for this node
483
484 if (tracing && traceListener instanceof TraceListener2) {
485 ((TraceListener2)traceListener).startRuleSearch();
486 }
487
488 Rule rule = getRule(item, context);
489 if (tracing && traceListener instanceof TraceListener2) {
490 ((TraceListener2) traceListener).endRuleSearch((rule != null) ? rule : getBuiltInRuleSet(), this, item);
491 }
492
493 if (rule == null) { // Use the default action for the node
494 // No need to open a new stack frame
495 getBuiltInRuleSet().process(item, parameters, tunnelParameters, context, locationId);
496
497 } else {
498
499 TemplateRule template = (TemplateRule) rule.getAction();
500 // if (modeTracing) {
501 // controller.getConfiguration().getLogger().info(
502 // getModeTitle() + " processing " + Err.depict(item) + " using template rule with match=\"" +
503 // rule.getPattern().toShortString() + "\" on line " + template.getLineNumber() + " of " + template.getSystemId()
504 // );
505 // }
506 if (template != previousTemplate) {
507 // Reuse the previous stackframe unless it's a different template rule
508 previousTemplate = template;
509 template.initialize();
510 context.openStackFrame(template.getStackFrameMap());
511 context.setLocalParameters(parameters);
512 context.setTunnelParameters(tunnelParameters);
513 }
514 context.setCurrentTemplateRule(rule);
515 if (tracing) {
516 traceListener.startCurrentItem(item);
517 if (modeTracing) {
518 traceListener.enter(template, context);
519 }
520 tc = template.applyLeavingTail(context);
521 if (tc != null) {
522 // disable tail call optimization while tracing
523 do {
524 tc = tc.processLeavingTail();
525 } while (tc != null);
526 }
527 if (modeTracing) {
528 traceListener.leave(template);
529 }
530 traceListener.endCurrentItem(item);
531 } else {
532 tc = template.applyLeavingTail(context);
533 }
534 }
535 }
536
537 // return the TailCall returned from the last node processed
538 return tc;
539 }
540
541 public abstract int getStackFrameSlotsNeeded();
542
543 /**
544 * Return a code string for a built-in rule set. This can be specialised in subclasses for PE/EE
545 *
546 * @param builtInRuleSet the rule set to get a code
547 * @return a simple string code or "???" if the ruleset is unknown
548 */
549 public String getCodeForBuiltInRuleSet(BuiltInRuleSet builtInRuleSet) {
550 if (builtInRuleSet instanceof ShallowCopyRuleSet) {
551 return "SC";
552 } else if (builtInRuleSet instanceof ShallowSkipRuleSet) {
553 return "SS";
554 } else if (builtInRuleSet instanceof DeepCopyRuleSet) {
555 return "DC";
556 } else if (builtInRuleSet instanceof DeepSkipRuleSet) {
557 return "DS";
558 } else if (builtInRuleSet instanceof FailRuleSet) {
559 return "FF";
560 } else if (builtInRuleSet instanceof TextOnlyCopyRuleSet) {
561 return "TC";
562 } else if (builtInRuleSet instanceof RuleSetWithWarnings) {
563 return getCodeForBuiltInRuleSet(((RuleSetWithWarnings) builtInRuleSet).getBaseRuleSet()) + "+W";
564 } else {
565 return "???";
566 }
567 }
568
569 /**
570 * Return a built-in rule set for a code string.
571 *
572 * @param code the code used in export
573 * @return a suitable ruleset
574 */
575 public BuiltInRuleSet getBuiltInRuleSetForCode(String code) {
576 BuiltInRuleSet base;
577 if (code.startsWith("SC")) {
578 base = ShallowCopyRuleSet.getInstance();
579 } else if (code.startsWith("SS")) {
580 base = ShallowSkipRuleSet.getInstance();
581 } else if (code.startsWith("DC")) {
582 base = DeepCopyRuleSet.getInstance();
583 } else if (code.startsWith("DS")) {
584 base = DeepSkipRuleSet.getInstance();
585 } else if (code.startsWith("FF")) {
586 base = FailRuleSet.getInstance();
587 } else if (code.startsWith("TC")) {
588 base = TextOnlyCopyRuleSet.getInstance();
589 } else {
590 throw new IllegalArgumentException(code);
591 }
592 if (code.endsWith("+W")) {
593 base = new RuleSetWithWarnings(base);
594 }
595 return base;
596 }
597
598 public final void export(ExpressionPresenter presenter) throws XPathException {
599 int s = presenter.startElement("mode");
600 if (!isUnnamedMode()) {
601 presenter.emitAttribute("name", getModeName());
602 }
603 presenter.emitAttribute("onNo", getCodeForBuiltInRuleSet(getBuiltInRuleSet()));
604 String flags = "";
605 if (isDeclaredStreamable()) {
606 flags += "s";
607 }
608 if (isUnnamedMode()) {
609 flags += "d";
610 }
611 if (mustBeTyped) {
612 flags += "t";
613 }
614 if (mustBeUntyped) {
615 flags += "u";
616 }
617 if (recoveryPolicy == Configuration.DO_NOT_RECOVER) {
618 flags += "F";
619 } else if (recoveryPolicy == Configuration.RECOVER_WITH_WARNINGS) {
620 flags += "W";
621 }
622 if (!hasRules) {
623 flags += "e";
624 }
625 if (!flags.isEmpty()) {
626 presenter.emitAttribute("flags", flags);
627 }
628 exportUseAccumulators(presenter);
629 presenter.emitAttribute("patternSlots", getStackFrameSlotsNeeded() + "");
630 exportTemplateRules(presenter);
631 int e = presenter.endElement();
632 if (s != e) {
633 throw new IllegalStateException("Export tree unbalanced for mode " + getModeName());
634 }
635 }
636
637 protected void exportUseAccumulators(ExpressionPresenter presenter){}
638
639 public boolean isMustBeTyped() {
640 return mustBeTyped;
641 }
642
643 public void explain(ExpressionPresenter presenter) throws XPathException {
644 int s = presenter.startElement("mode");
645 if (!isUnnamedMode()) {
646 presenter.emitAttribute("name", getModeName());
647 }
648 presenter.emitAttribute("onNo", getCodeForBuiltInRuleSet(getBuiltInRuleSet()));
649 String flags = "";
650 if (isDeclaredStreamable()) {
651 flags += "s";
652 }
653 if (isUnnamedMode()) {
654 flags += "d";
655 }
656 if (mustBeTyped) {
657 flags += "t";
658 }
659 if (mustBeUntyped) {
660 flags += "u";
661 }
662 if (recoveryPolicy == Configuration.DO_NOT_RECOVER) {
663 flags += "F";
664 } else if (recoveryPolicy == Configuration.RECOVER_WITH_WARNINGS) {
665 flags += "W";
666 }
667 if (!flags.isEmpty()) {
668 presenter.emitAttribute("flags", flags);
669 }
670
671 presenter.emitAttribute("patternSlots", getStackFrameSlotsNeeded() + "");
672 explainTemplateRules(presenter);
673 int e = presenter.endElement();
674 if (s != e) {
675 throw new IllegalStateException("tree unbalanced");
676 }
677 }
678
679 /**
680 * Interface for helper classes used to filter a chain of rules
681 */
682
683 protected interface RuleFilter {
684 /**
685 * Test a rule to see whether it should be included
686 *
687 * @param r the rule to be tested
688 * @return true if the rule qualifies
689 */
690 boolean testRule(Rule r);
691 }
692
693 /**
694 * Interface for helper classes used to process all the rules in the Mode
695 */
696
697 public interface RuleAction {
698 /**
699 * Process a given rule
700 *
701 * @param r the rule to be processed
702 * @throws XPathException if an error occurs, for example a dynamic error in evaluating a pattern
703 */
704 void processRule(Rule r) throws XPathException;
705 }
706
707 }