Debian Codegraph @

net/sf/saxon/trans/SimpleMode.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.expr.ComponentBinding;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.XPathContextMajor;
14 import net.sf.saxon.expr.instruct.SlotManager;
15 import net.sf.saxon.expr.instruct.TemplateRule;
16 import net.sf.saxon.expr.sort.GenericSorter;
17 import net.sf.saxon.expr.sort.Sortable;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.*;
20 import net.sf.saxon.style.StylesheetModule;
21 import net.sf.saxon.style.StylesheetPackage;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trans.rules.*;
24 import net.sf.saxon.tree.util.Navigator;
25 import net.sf.saxon.type.*;
26 import net.sf.saxon.value.AtomicValue;
27 import net.sf.saxon.value.Whitespace;
28 import net.sf.saxon.z.IntHashMap;
29 import net.sf.saxon.z.IntIterator;
30
31 import java.util.*;
32
33 /**
34 * A Mode is a collection of rules; the selection of a rule to apply to a given element
35 * is determined by a Pattern. A SimpleMode is a mode contained within a single package,
36 * as opposed to a CompoundMode which can combine rules from several packages
37 */
38
39 public class SimpleMode extends Mode {
40 // TODO:PERF the data structure does not cater well for a stylesheet making heavy use of
41 // match="schema-element(X)". We should probably expand the substitution group.
42
43 protected final RuleChain genericRuleChain = new RuleChain();
44 protected RuleChain atomicValueRuleChain = new RuleChain();
45 protected RuleChain functionItemRuleChain = new RuleChain();
46 protected RuleChain documentRuleChain = new RuleChain();
47 protected RuleChain textRuleChain = new RuleChain();
48 protected RuleChain commentRuleChain = new RuleChain();
49 protected RuleChain processingInstructionRuleChain = new RuleChain();
50 protected RuleChain namespaceRuleChain = new RuleChain();
51 protected RuleChain unnamedElementRuleChain = new RuleChain();
52 protected RuleChain unnamedAttributeRuleChain = new RuleChain();
53 protected IntHashMap<RuleChain> namedElementRuleChains = new IntHashMap<>(32);
54 protected IntHashMap<RuleChain> namedAttributeRuleChains = new IntHashMap<>(8);
55 protected Map<StructuredQName, RuleChain> qNamedElementRuleChains;
56 protected Map<StructuredQName, RuleChain> qNamedAttributeRuleChains;
57
58 private BuiltInRuleSet builtInRuleSet = TextOnlyCopyRuleSet.getInstance();
59 private Rule mostRecentRule;
60 private int mostRecentModuleHash;
61 private int stackFrameSlotsNeeded = 0;
62 private int highestRank;
63
64
65 private Map<String, Integer> explicitPropertyPrecedences = new HashMap<>();
66 private Map<String, String> explicitPropertyValues = new HashMap<>();
67
68
69
70 /**
71 * Default constructor - creates a Mode containing no rules
72 *
73 * @param modeName the name of the mode
74 */
75
76 public SimpleMode(StructuredQName modeName) {
77 super(modeName);
78 }
79
80 /**
81 * Set the built-in template rules to be used with this Mode in the case where there is no
82 * explicit template rule
83 *
84 * @param defaultRules the built-in rule set
85 */
86
87 public void setBuiltInRuleSet(BuiltInRuleSet defaultRules) {
88 this.builtInRuleSet = defaultRules;
89 hasRules = true; // if mode is explicitly declared, treat it as containing rules
90 }
91
92 /**
93 * Get the built-in template rules to be used with this Mode in the case where there is no
94 * explicit template rule
95 *
96 * @return the built-in rule set, defaulting to the TextOnlyCopyRuleSet if no other rule set has
97 * been supplied
98 */
99
100 public BuiltInRuleSet getBuiltInRuleSet() {
101 return this.builtInRuleSet;
102 }
103
104 /**
105 * Get the active component of this mode. For a simple mode this is the mode itself;
106 * for a compound mode it is the "overriding" part
107 */
108 @Override
109 public SimpleMode getActivePart() {
110 return this;
111 }
112
113 /**
114 * Check that the mode does not contain conflicting property values
115 *
116 * @throws XPathException if there are conflicts
117 */
118
119 public void checkForConflictingProperties() throws XPathException {
120 for (Map.Entry<String, String> entry : getActivePart().explicitPropertyValues.entrySet()) {
121 String prop = entry.getKey();
122 String value = entry.getValue();
123 if (value.equals("##conflict##")) {
124 throw new XPathException(
125 "For " + getLabel() +
126 ", there are conflicting values for xsl:mode/@" +
127 prop +
128 " at the same import precedence", "XTSE0545");
129 }
130 if (prop.equals("typed")) {
131 mustBeTyped = "yes".equals(value) || "strict".equals(value) || "lax".equals(value);
132 mustBeUntyped = "no".equals(value);
133 } else if (prop.equals("on-no-match")) {
134 BuiltInRuleSet base = null;
135 switch (value) {
136 case "text-only-copy":
137 base = TextOnlyCopyRuleSet.getInstance();
138 break;
139 case "shallow-copy":
140 base = ShallowCopyRuleSet.getInstance();
141 break;
142 case "deep-copy":
143 base = DeepCopyRuleSet.getInstance();
144 break;
145 case "shallow-skip":
146 base = ShallowSkipRuleSet.getInstance();
147 break;
148 case "deep-skip":
149 base = DeepSkipRuleSet.getInstance();
150 break;
151 case "fail":
152 base = FailRuleSet.getInstance();
153 break;
154 default:
155 // already validated
156 break;
157 }
158 if ("yes".equals(explicitPropertyValues.get("warning-on-no-match"))) {
159 base = new RuleSetWithWarnings(base);
160 }
161 setBuiltInRuleSet(base);
162 }
163 }
164 }
165
166 /**
167 * Get an identifier for the mode for use in error messages
168 * @return either the string "the unnamed mode" or the string "mode NNNN" where "NNNN"
169 * is the display form of the mode's name.
170 */
171 public String getLabel() {
172 return isUnnamedMode() ?
173 "the unnamed mode" :
174 "mode " + modeName.getDisplayName();
175 }
176
177 /**
178 * Construct a new Mode, copying the contents of an existing Mode
179 *
180 * @param from the existing mode.
181 * @param to the name of the new mode to be created
182 */
183
184 public static void copyRules(final SimpleMode from, final SimpleMode to) {
185 try {
186 from.processRules(r -> {
187 Rule r2 = r.copy(false);
188 to.addRule(r2.getPattern(), r2);
189 });
190 } catch (XPathException e) {
191 throw new AssertionError(e);
192 }
193
194 to.mostRecentRule = from.mostRecentRule;
195 to.mostRecentModuleHash = from.mostRecentModuleHash;
196 }
197
198 /**
199 * Generate a search state for processing a given node
200 *
201 * @return a new object capable of holding the state of a search for a rule
202 */
203 protected RuleSearchState makeRuleSearchState(RuleChain chain, XPathContext context) {
204 return new RuleSearchState();
205 }
206
207 /**
208 * Ask whether there are any template rules in this mode
209 * (a mode could exist merely because it is referenced in apply-templates)
210 *
211 * @return true if no template rules exist in this mode
212 */
213
214 @Override
215 public boolean isEmpty() {
216 return !hasRules;
217 }
218
219 /**
220 * Set an explicit property at a particular precedence. Used for detecting conflicts
221 *
222 * @param name the name of the property
223 * @param value the value of the property
224 * @param precedence the import precedence of this property value
225 */
226
227 public void setExplicitProperty(String name, String value, int precedence) {
228 Integer p = explicitPropertyPrecedences.get(name);
229 if (p != null) {
230 if (p < precedence) {
231 explicitPropertyPrecedences.put(name, precedence);
232 explicitPropertyValues.put(name, value);
233 } else if (p == precedence) {
234 String v = explicitPropertyValues.get(name);
235 if (v != null & !v.equals(value)) {
236 // We don't throw an exception, because the conflict is an error only if this
237 // is the highest-precedence declaration of this mode
238 explicitPropertyValues.put(name, "##conflict##");
239 }
240 } else {
241 // no action
242 }
243 } else {
244 explicitPropertyPrecedences.put(name, precedence);
245 explicitPropertyValues.put(name, value);
246 }
247
248 final String typed = explicitPropertyValues.get("typed");
249 mustBeTyped = "yes".equals(typed) || "strict".equals(typed) || "lax".equals(typed);
250 mustBeUntyped = "no".equals(typed);
251
252 }
253
254 /**
255 * Get the value of a property of this mode, e.g. the "typed" property
256 *
257 * @param name the property name, e.g. "typed"
258 * @return the property value
259 */
260
261 public String getPropertyValue(String name) {
262 return explicitPropertyValues.get(name);
263 }
264
265
266 /**
267 * Get the "explicit namespaces" matched by this mode. Returns a set containing all the namespaces
268 * matched by specific template rules in this mode
269 *
270 * @param pool the NamePool for the configuration
271 * @return the set of all namespace URIs of names explicitly matched by rules in this mode
272 */
273
274 @Override
275 public Set<String> getExplicitNamespaces(NamePool pool) {
276 Set<String> namespaces = new HashSet<>();
277 IntIterator ii = namedElementRuleChains.keyIterator();
278 while (ii.hasNext()) {
279 int fp = ii.next();
280 namespaces.add(pool.getURI(fp));
281 }
282 return namespaces;
283 }
284
285 /**
286 * Add a rule to the Mode.
287 * @param pattern a Pattern
288 * @param action the Object to return from getRule() when the supplied node matches this Pattern
289 * @param module the stylesheet module containing the rule
290 * @param precedence the import precedence of the rule
291 * @param priority the priority of the rule
292 * @param position the relative position of the rule in declaration order. If two rules have the same
293 * position in declaration order, this indicates that they were formed by splitting
294 * a single rule whose pattern is a union pattern
295 * @param part the relative position of a rule within a family of rules created by splitting a
296 * single rule governed by a union pattern. This is used where the splitting of the
297 * rule was mandated by the XSLT specification, that is, where there is no explicit
298 * priority specified. In cases where Saxon splits a rule for optimization reasons,
299 * the subrules will all have the same subsequence number.
300 */
301
302 public void addRule(Pattern pattern, RuleTarget action,
303 StylesheetModule module, int precedence, double priority, int position, int part) {
304
305 hasRules = true;
306
307 // Ignore a pattern that will never match, e.g. "@comment"
308
309 if (pattern.getItemType() instanceof ErrorType) {
310 return;
311 }
312
313 // for fast lookup, we maintain one list for each element name for patterns that can only
314 // match elements of a given name, one list for each node type for patterns that can only
315 // match one kind of non-element node, and one generic list.
316 // Each list is sorted in precedence/priority order so we find the highest-priority rule first
317
318 // This logic is designed to ensure that when a UnionPattern contains multiple branches
319 // with the same priority, next-match doesn't select the same template twice (next-match-024)
320 int moduleHash = module.hashCode();
321 // int sequence;
322 // if (mostRecentRule == null) {
323 // sequence = 0;
324 // } else if (action == mostRecentRule.getAction() && moduleHash == mostRecentModuleHash) {
325 // sequence = mostRecentRule.getSequence();
326 // } else {
327 // sequence = mostRecentRule.getSequence() + 1;
328 // }
329 //int precedence = module.getPrecedence();
330 int minImportPrecedence = module.getMinImportPrecedence();
331
332 Rule newRule = makeRule(pattern, action, precedence, minImportPrecedence, priority, position, part);
333
334 if (pattern instanceof NodeTestPattern) {
335 ItemType test = pattern.getItemType();
336 if (test instanceof AnyNodeTest) {
337 newRule.setAlwaysMatches(true);
338 } else if (test instanceof NodeKindTest) {
339 newRule.setAlwaysMatches(true);
340 } else if (test instanceof NameTest) {
341 int kind = test.getPrimitiveType();
342 if (kind == Type.ELEMENT || kind == Type.ATTRIBUTE) {
343 newRule.setAlwaysMatches(true);
344 }
345 }
346 }
347 mostRecentRule = newRule;
348 mostRecentModuleHash = moduleHash;
349
350 addRule(pattern, newRule);
351
352 }
353
354 /**
355 * Generate a new rule - so it can be overridden to make more specialist rules
356 *
357 * @param pattern the pattern that this rule matches
358 * @param action the object invoked by this rule (usually a Template)
359 * @param precedence the precedence of the rule
360 * @param minImportPrecedence the minimum import precedence for xsl:apply-imports
361 * @param priority the priority of the rule
362 * @param sequence a sequence number for ordering of rules
363 * @param part distinguishes rules formed by splitting a rule on a union pattern
364 * @return the newly created rule
365 */
366 public Rule makeRule(/*@NotNull*/ Pattern pattern, /*@NotNull*/ RuleTarget action,
367 int precedence, int minImportPrecedence, double priority, int sequence, int part) {
368 return new Rule(pattern, action, precedence, minImportPrecedence, priority, sequence, part);
369 }
370
371 public void addRule(Pattern pattern, Rule newRule) {
372 UType uType = pattern.getUType();
373 if (uType.equals(UType.ELEMENT)) {
374 int fp = pattern.getFingerprint();
375 addRuleToNamedOrUnnamedChain(
376 newRule, fp, unnamedElementRuleChain, namedElementRuleChains);
377 } else if (uType.equals(UType.ATTRIBUTE)) {
378 int fp = pattern.getFingerprint();
379 addRuleToNamedOrUnnamedChain(
380 newRule, fp, unnamedAttributeRuleChain, namedAttributeRuleChains);
381 } else if (uType.equals(UType.DOCUMENT)) {
382 addRuleToList(newRule, documentRuleChain);
383 } else if (uType.equals(UType.TEXT)) {
384 addRuleToList(newRule, textRuleChain);
385 } else if (uType.equals(UType.COMMENT)) {
386 addRuleToList(newRule, commentRuleChain);
387 } else if (uType.equals(UType.PI)) {
388 addRuleToList(newRule, processingInstructionRuleChain);
389 } else if (uType.equals(UType.NAMESPACE)) {
390 addRuleToList(newRule, namespaceRuleChain);
391 } else if (UType.ANY_ATOMIC.subsumes(uType)) {
392 addRuleToList(newRule, atomicValueRuleChain);
393 } else if (UType.FUNCTION.subsumes(uType)) {
394 addRuleToList(newRule, functionItemRuleChain);
395 } else {
396 addRuleToList(newRule, genericRuleChain);
397 }
398 }
399
400 protected void addRuleToNamedOrUnnamedChain(
401 Rule newRule, int fp, RuleChain unnamedRuleChain, IntHashMap<RuleChain> namedRuleChains) {
402 if (fp == -1) {
403 addRuleToList(newRule, unnamedRuleChain);
404 } else {
405 RuleChain chain = namedRuleChains.get(fp);
406 if (chain == null) {
407 chain = new RuleChain(newRule);
408 namedRuleChains.put(fp, chain);
409 } else {
410 addRuleToList(newRule, chain);
411 }
412 }
413 }
414
415 /**
416 * Insert a new rule into this list before others of the same precedence/priority
417 *
418 * @param newRule the new rule to be added into the list
419 * @param list the Rule at the head of the list, or null if the list is empty
420 */
421
422
423 private void addRuleToList(Rule newRule, RuleChain list) {
424 if (list.head() == null) {
425 list.setHead(newRule);
426 } else {
427 int precedence = newRule.getPrecedence();
428 double priority = newRule.getPriority();
429 Rule rule = list.head();
430 Rule prev = null;
431 while (rule != null) {
432 if ((rule.getPrecedence() < precedence) ||
433 (rule.getPrecedence() == precedence && rule.getPriority() <= priority)) {
434 newRule.setNext(rule);
435 if (prev == null) {
436 list.setHead(newRule);
437 } else {
438 prev.setNext(newRule);
439 }
440 break;
441 } else {
442 prev = rule;
443 rule = rule.getNext();
444 }
445 }
446 if (rule == null) {
447 assert prev != null;
448 prev.setNext(newRule);
449 newRule.setNext(null);
450 }
451 }
452 }
453
454 /**
455 * Specify how many slots for local variables are required by a particular pattern
456 *
457 * @param slots the number of slots needed
458 */
459
460 public void allocatePatternSlots(int slots) {
461 stackFrameSlotsNeeded = Math.max(stackFrameSlotsNeeded, slots);
462 }
463
464 /**
465 * Get the rule corresponding to a given item, by finding the best pattern match.
466 *
467 * @param item the item to be matched
468 * @param context the XPath dynamic evaluation context
469 * @return the best matching rule, if any (otherwise null).
470 * @throws XPathException if an error occurs matching a pattern
471 */
472
473 @Override
474 public Rule getRule(Item item, XPathContext context) throws XPathException {
475
476 // If there are match patterns in the stylesheet that use local variables, we need to allocate
477 // a new stack frame for evaluating the match patterns. We base this on the match pattern with
478 // the highest number of range variables, so we can reuse the same stack frame for all rules
479 // that we test against. If no patterns use range variables, we don't bother allocating a new
480 // stack frame.
481
482 // Note, this method isn't functionally necessary; we could call the 3-argument version
483 // with a filter that always returns true. But this is the common path for apply-templates,
484 // and we want to squeeze every drop of performance from it.
485
486 if (stackFrameSlotsNeeded > 0) {
487 context = makeNewContext(context);
488 }
489
490 // search the specific list for this node type / node name
491
492 RuleChain unnamedNodeChain;
493 Rule bestRule = null;
494
495 if (item instanceof NodeInfo) {
496 NodeInfo node = (NodeInfo) item;
497 switch (node.getNodeKind()) {
498 case Type.DOCUMENT:
499 unnamedNodeChain = documentRuleChain;
500 break;
501
502 case Type.ELEMENT: {
503 unnamedNodeChain = unnamedElementRuleChain;
504 RuleChain namedNodeChain;
505 if (node.hasFingerprint()) {
506 namedNodeChain = namedElementRuleChains.get(node.getFingerprint());
507 } else {
508 namedNodeChain = getNamedRuleChain(context, Type.ELEMENT, node.getURI(), node.getLocalPart());
509 }
510 if (namedNodeChain != null) {
511 bestRule = searchRuleChain(node, context, null, namedNodeChain);
512 }
513 break;
514 }
515 case Type.ATTRIBUTE: {
516 unnamedNodeChain = unnamedAttributeRuleChain;
517 RuleChain namedNodeChain;
518 if (node.hasFingerprint()) {
519 namedNodeChain = namedAttributeRuleChains.get(node.getFingerprint());
520 } else {
521 namedNodeChain = getNamedRuleChain(context, Type.ATTRIBUTE, node.getURI(), node.getLocalPart());
522 }
523 if (namedNodeChain != null) {
524 bestRule = searchRuleChain(node, context, null, namedNodeChain);
525 }
526 break;
527 }
528 case Type.TEXT:
529 unnamedNodeChain = textRuleChain;
530 break;
531 case Type.COMMENT:
532 unnamedNodeChain = commentRuleChain;
533 break;
534 case Type.PROCESSING_INSTRUCTION:
535 unnamedNodeChain = processingInstructionRuleChain;
536 break;
537 case Type.NAMESPACE:
538 unnamedNodeChain = namespaceRuleChain;
539 break;
540 default:
541 throw new AssertionError("Unknown node kind");
542 }
543
544 // search the list for unnamed nodes of a particular kind
545
546 if (unnamedNodeChain != null) {
547 bestRule = searchRuleChain(node, context, bestRule, unnamedNodeChain);
548 }
549
550 // Search the list for rules for nodes of unknown node kind
551
552 bestRule = searchRuleChain(node, context, bestRule, genericRuleChain);
553
554 } else if (item instanceof AtomicValue) {
555 if (atomicValueRuleChain != null) {
556 bestRule = searchRuleChain(item, context, bestRule, atomicValueRuleChain);
557 }
558 bestRule = searchRuleChain(item, context, bestRule, genericRuleChain);
559
560 } else if (item instanceof Function) {
561 if (functionItemRuleChain != null) {
562 bestRule = searchRuleChain(item, context, bestRule, functionItemRuleChain);
563 }
564 bestRule = searchRuleChain(item, context, bestRule, genericRuleChain);
565 }
566
567 return bestRule;
568 }
569
570
571 /**
572 * Get a rule chain for a particular node name without allocating a fingerprint from the name pool
573 *
574 * @param kind the kind of node (element or attribute)
575 * @param uri the namespace URI of the node
576 * @param local the local name of the node
577 * @return the Rule at the head of the rule chain for nodes of this name, or null if there are no rules
578 * to consider
579 */
580
581 protected RuleChain getNamedRuleChain(XPathContext c, int kind, String uri, String local) {
582 // If this is the first attempt to match a non-fingerprinted node, build indexes
583 // to the rule chains based on StructuredQName rather than fingerprint
584 synchronized(this) {
585 if (qNamedElementRuleChains == null) {
586 qNamedElementRuleChains = new HashMap<>(namedElementRuleChains.size());
587 qNamedAttributeRuleChains = new HashMap<>(namedAttributeRuleChains.size());
588 NamePool pool = c.getNamePool();
589 indexByQName(pool, namedElementRuleChains, qNamedElementRuleChains);
590 indexByQName(pool, namedAttributeRuleChains, qNamedAttributeRuleChains);
591 }
592 }
593 return (kind == Type.ELEMENT ? qNamedElementRuleChains : qNamedAttributeRuleChains)
594 .get(new StructuredQName("", uri, local));
595 }
596
597 private static void indexByQName(NamePool pool, IntHashMap<RuleChain> indexByFP, Map<StructuredQName, RuleChain> indexByQN) {
598 IntIterator ii = indexByFP.keyIterator();
599 while (ii.hasNext()) {
600 int fp = ii.next();
601 RuleChain eChain = indexByFP.get(fp);
602 StructuredQName name = pool.getStructuredQName(fp);
603 indexByQN.put(name, eChain);
604 }
605 }
606
607 /**
608 * Search a chain of rules
609 *
610 * @param item the item being matched
611 * @param context XPath dynamic context
612 * @param bestRule the best rule so far in terms of precedence and priority (may be null)
613 * @param chain the chain to be searched
614 * @return the best match rule found in the chain, or the previous best rule, or null
615 * @throws XPathException if an error occurs matching a pattern
616 */
617
618 protected Rule searchRuleChain(Item item, XPathContext context, /*@Nullable*/ Rule bestRule, RuleChain chain) throws XPathException {
619
620 while (!(context instanceof XPathContextMajor)) {
621 context = context.getCaller();
622 }
623
624 // Get the rule search state object - this could be reusable within a rule chain.
625 RuleSearchState ruleSearchState = makeRuleSearchState(chain, context);
626
627 Rule head = chain == null ? null : chain.head();
628 while (head != null) {
629 if (bestRule != null) {
630 int rank = head.compareRank(bestRule);
631 if (rank < 0) {
632 // if we already have a match, and the precedence or priority of this
633 // rule is lower, quit the search
634 break;
635 } else if (rank == 0) {
636 // this rule has the same precedence and priority as the matching rule already found
637 if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
638 if (head.getSequence() != bestRule.getSequence()) {
639 reportAmbiguity(item, bestRule, head, context);
640 }
641 // choose whichever one comes last (assuming the error wasn't fatal)
642 int seqComp = Integer.compare(bestRule.getSequence(), head.getSequence());
643 if (seqComp > 0) {
644 return bestRule;
645 } else if (seqComp < 0) {
646 return head;
647 } else {
648 // we're dealing with two rules formed by partitioning a union pattern
649 bestRule = bestRule.getPartNumber() > head.getPartNumber() ? bestRule : head;
650 }
651 break;
652 } else {
653 // keep searching other rules of the same precedence and priority
654 }
655 } else {
656 // this rule has higher rank than the matching rule already found
657 if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
658 bestRule = head;
659 }
660 }
661 } else if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
662 bestRule = head;
663 if (getRecoveryPolicy() == Configuration.RECOVER_SILENTLY) {
664 //ruleSearchState.count();
665 break; // choose the first match; rules within a chain are in order of rank
666 }
667 }
668 //ruleSearchState.count();// Keep tab of the number of checks
669 head = head.getNext();
670 }
671
672 return bestRule;
673 }
674
675 /**
676 * Does this rule match the given item? Can be overridden
677 *
678 * @param r the rule to check
679 * @param item the context item
680 * @param context the static context for evaluation
681 * @param pre An appropriate matcher for preconditions in this mode
682 * @return true if this rule does match
683 * @throws XPathException if a dynamic error occurs while matching the pattern
684 */
685
686 protected boolean ruleMatches(Rule r, Item item, XPathContextMajor context, RuleSearchState pre) throws XPathException {
687 return r.isAlwaysMatches() || r.matches(item, context);
688 }
689
690 /**
691 * Get the rule corresponding to a given item, by finding the best Pattern match.
692 *
693 * @param item the item to be matched
694 * @param context the XPath dynamic evaluation context
695 * @param filter a filter to select which rules should be considered
696 * @return the best matching rule, if any (otherwise null).
697 * @throws XPathException if an error occurs
698 */
699
700
701 /*@Nullable*/
702 @Override
703 public Rule getRule(Item item, XPathContext context, RuleFilter filter) throws XPathException {
704
705 // If there are match patterns in the stylesheet that use local variables, we need to allocate
706 // a new stack frame for evaluating the match patterns. We base this on the match pattern with
707 // the highest number of range variables, so we can reuse the same stack frame for all rules
708 // that we test against. If no patterns use range variables, we don't bother allocating a new
709 // stack frame.
710
711 if (stackFrameSlotsNeeded > 0) {
712 context = makeNewContext(context);
713 }
714
715 // Get the rule search state object
716 RuleSearchState ruleSearchState;
717
718 // search the specific list for this node type / node name
719
720 Rule bestRule = null;
721 RuleChain unnamedNodeChain;
722
723
724 // Search the list for unnamed nodes of a particular kind
725
726 if (item instanceof NodeInfo) {
727 NodeInfo node = (NodeInfo) item;
728 switch (node.getNodeKind()) {
729 case Type.DOCUMENT:
730 unnamedNodeChain = documentRuleChain;
731 break;
732 case Type.ELEMENT: {
733 unnamedNodeChain = unnamedElementRuleChain;
734 RuleChain namedNodeChain;
735 if (node.hasFingerprint()) {
736 namedNodeChain = namedElementRuleChains.get(node.getFingerprint());
737 } else {
738 namedNodeChain = getNamedRuleChain(context, Type.ELEMENT, node.getURI(), node.getLocalPart());
739 }
740 if (namedNodeChain != null) {
741 ruleSearchState = makeRuleSearchState(namedNodeChain, context);
742 bestRule = searchRuleChain(item, context, null, namedNodeChain, ruleSearchState, filter);
743 }
744 break;
745 }
746 case Type.ATTRIBUTE: {
747 unnamedNodeChain = unnamedAttributeRuleChain;
748 RuleChain namedNodeChain;
749 if (node.hasFingerprint()) {
750 namedNodeChain = namedAttributeRuleChains.get(node.getFingerprint());
751 } else {
752 namedNodeChain = getNamedRuleChain(context, Type.ATTRIBUTE, node.getURI(), node.getLocalPart());
753 }
754 if (namedNodeChain != null) {
755 ruleSearchState = makeRuleSearchState(namedNodeChain, context);
756 bestRule = searchRuleChain(item, context, null, namedNodeChain, ruleSearchState, filter);
757 }
758 break;
759 }
760 case Type.TEXT:
761 unnamedNodeChain = textRuleChain;
762 break;
763 case Type.COMMENT:
764 unnamedNodeChain = commentRuleChain;
765 break;
766 case Type.PROCESSING_INSTRUCTION:
767 unnamedNodeChain = processingInstructionRuleChain;
768 break;
769 case Type.NAMESPACE:
770 unnamedNodeChain = namespaceRuleChain;
771 break;
772 default:
773 throw new AssertionError("Unknown node kind");
774 }
775
776 ruleSearchState = makeRuleSearchState(unnamedNodeChain, context);
777 bestRule = searchRuleChain(item, context, bestRule, unnamedNodeChain, ruleSearchState, filter);
778
779 // Search the list for rules for nodes of unknown node kind
780
781 ruleSearchState = makeRuleSearchState(genericRuleChain, context);
782 return searchRuleChain(item, context, bestRule, genericRuleChain, ruleSearchState, filter);
783
784 } else if (item instanceof AtomicValue) {
785 if (atomicValueRuleChain != null) {
786 ruleSearchState = makeRuleSearchState(atomicValueRuleChain, context);
787 bestRule = searchRuleChain(item, context, bestRule, atomicValueRuleChain, ruleSearchState, filter);
788 }
789 ruleSearchState = makeRuleSearchState(genericRuleChain, context);
790 bestRule = searchRuleChain(item, context, bestRule, genericRuleChain, ruleSearchState, filter);
791 return bestRule;
792
793 } else if (item instanceof Function) {
794 if (functionItemRuleChain != null) {
795 ruleSearchState = makeRuleSearchState(functionItemRuleChain, context);
796 bestRule = searchRuleChain(item, context, bestRule, functionItemRuleChain, ruleSearchState, filter);
797 }
798 ruleSearchState = makeRuleSearchState(genericRuleChain, context);
799 bestRule = searchRuleChain(item, context, bestRule, genericRuleChain, ruleSearchState, filter);
800 return bestRule;
801
802 } else {
803 return null;
804 }
805
806 }
807
808 /**
809 * Search a chain of rules
810 *
811 * @param item the item being matched
812 * @param context XPath dynamic context
813 * @param bestRule the best rule so far in terms of precedence and priority (may be null)
814 * @param chain the chain to be searched
815 * @param ruleSearchState An appropriate ruleState in this mode
816 * @param filter filter used to select which rules are candidates to be searched
817 * @return the best match rule found in the chain, or the previous best rule, or null
818 * @throws XPathException if an error occurs while matching a pattern
819 */
820
821 protected Rule searchRuleChain(Item item, XPathContext context,
822 Rule/*@Nullable*/ bestRule, RuleChain chain, RuleSearchState ruleSearchState, RuleFilter filter) throws XPathException {
823 Rule head = chain == null ? null : chain.head();
824 while (!(context instanceof XPathContextMajor)) {
825 context = context.getCaller();
826 }
827 while (head != null) {
828 if (filter == null || filter.testRule(head)) {
829 if (bestRule != null) {
830 int rank = head.compareRank(bestRule);
831 if (rank < 0) {
832 // if we already have a match, and the precedence or priority of this
833 // rule is lower, quit the search
834 break;
835 } else if (rank == 0) {
836 // this rule has the same precedence and priority as the matching rule already found
837 if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
838 reportAmbiguity(item, bestRule, head, context);
839 // choose whichever one comes last (assuming the error wasn't fatal)
840 bestRule = bestRule.getSequence() > head.getSequence() ? bestRule : head;
841 break;
842 } else {
843 // keep searching other rules of the same precedence and priority
844 }
845 } else {
846 // this rule has higher rank than the matching rule already found
847 if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
848 bestRule = head;
849 }
850 }
851 } else if (ruleMatches(head, item, (XPathContextMajor) context, ruleSearchState)) {
852 bestRule = head;
853 if (getRecoveryPolicy() == Configuration.RECOVER_SILENTLY) {
854 break; // choose the first match; rules within a chain are in order of rank
855 }
856 }
857 }
858 head = head.getNext();
859 }
860 return bestRule;
861 }
862
863
864 /**
865 * Report an ambiguity, that is, the situation where two rules of the same
866 * precedence and priority match the same node
867 *
868 * @param item The item that matches two or more rules
869 * @param r1 The first rule that the node matches
870 * @param r2 The second rule that the node matches
871 * @param c The context for the transformation
872 * @throws XPathException if the system is configured to treat ambiguous template matching as a
873 * non-recoverable error
874 */
875
876 protected void reportAmbiguity(Item item, Rule r1, Rule r2, XPathContext c)
877 throws XPathException {
878 // don't report an error if the conflict is between two branches of the same Union pattern
879 if (r1.getAction() == r2.getAction() && r1.getSequence() == r2.getSequence()) {
880 return;
881 }
882 String path;
883 String errorCode = "XTDE0540";
884
885 if (item instanceof NodeInfo) {
886 path = Navigator.getPath((NodeInfo) item);
887 } else {
888 path = item.toShortString();
889 }
890
891 Pattern pat1 = r1.getPattern();
892 Pattern pat2 = r2.getPattern();
893
894 String message;
895 if (r1.getAction() == r2.getAction()) {
896 message = "Ambiguous rule match for " + path + ". " +
897 "Matches \"" + showPattern(pat1) + "\" on line " + pat1.getLocation().getLineNumber() +
898 " of " + pat1.getLocation().getSystemId() +
899 ", a rule which appears in the stylesheet more than once, because the containing module was included more than once";
900 } else {
901 message = "Ambiguous rule match for " + path + '\n' +
902 "Matches both \"" + showPattern(pat1) + "\" on line " + pat1.getLocation().getLineNumber() +
903 " of " + pat1.getLocation().getSystemId() +
904 "\nand \"" + showPattern(pat2) + "\" on line " + pat2.getLocation().getLineNumber() +
905 " of " + pat2.getLocation().getSystemId();
906 }
907
908 XPathException err = new XPathException(message, errorCode);
909 if (getRecoveryPolicy() == Configuration.DO_NOT_RECOVER) {
910 throw err;
911 } else {
912 c.getController().recoverableError(err);
913 }
914 }
915
916 private static String showPattern(Pattern p) {
917 // Complex patterns can be laid out with lots of whitespace, which looks messy in the error message
918 return Whitespace.collapseWhitespace(p.toString()).toString();
919 }
920
921 /**
922 * Prepare for possible streamability - null here, but can be subclassed
923 *
924 * @throws XPathException if a failure occurs
925 */
926 public void prepareStreamability() throws XPathException {
927 }
928
929
930 /**
931 * Allocate slot numbers to all the external component references in this component
932 *
933 * @param pack the containing package
934 */
935
936 public void allocateAllBindingSlots(final StylesheetPackage pack) {
937 if (getDeclaringComponent().getDeclaringPackage() == pack && !bindingSlotsAllocated) {
938 forceAllocateAllBindingSlots(pack, this, getDeclaringComponent().getComponentBindings());
939 bindingSlotsAllocated = true;
940 }
941 }
942
943 public static void forceAllocateAllBindingSlots(
944 final StylesheetPackage pack, final SimpleMode mode, final List<ComponentBinding> bindings) {
945 final Set<TemplateRule> rulesProcessed = new HashSet<>();
946 final IdentityHashMap<Pattern, Boolean> patternsProcessed = new IdentityHashMap<>();
947 try {
948 mode.processRules(r -> {
949 // A rule can appear twice, for example at different import precedences or
950 // because the match pattern is a union pattern; only allocate slots once
951 Pattern pattern = r.getPattern();
952 if (!patternsProcessed.containsKey(pattern)) {
953 allocateBindingSlotsRecursive(pack, mode, pattern, bindings);
954 patternsProcessed.put(pattern, true);
955 }
956 TemplateRule tr = (TemplateRule) r.getAction();
957 if (tr.getBody() != null && !rulesProcessed.contains(tr)) {
958 allocateBindingSlotsRecursive(pack, mode, tr.getBody(), bindings);
959 rulesProcessed.add(tr);
960 }
961 });
962 } catch (XPathException e) {
963 throw new AssertionError(e);
964 }
965 }
966
967 /**
968 * Compute the streamability of all template rules. No action in Saxon-HE.
969 */
970
971 public void computeStreamability() throws XPathException {
972 // Implemented in Saxon-EE
973 }
974
975 /**
976 * For a streamable mode, invert all the templates to generate streamable code.
977 * No action in Saxon-HE.
978 *
979 * @throws XPathException if there is a non-streamable template in the mode
980 */
981
982 public void invertStreamableTemplates() throws XPathException {
983 // Implemented in Saxon-EE
984 }
985
986 /**
987 * Explain all template rules in this mode by showing their
988 * expression tree represented in XML. Note that this produces more information
989 * than the simpler exportTemplateRules() method: this method is intended for
990 * the human reader wanting diagnostic explanations, whereas exportTemplateRules()
991 * is designed to produce a package that can be re-imported.
992 *
993 * @param out used to display the expression tree
994 */
995
996 public void explainTemplateRules(final ExpressionPresenter out) throws XPathException {
997 RuleAction action = r -> r.export(out, isDeclaredStreamable());
998 RuleGroupAction group = new RuleGroupAction() {
999 String type;
1000
1001 public void start() {
1002 out.startElement("ruleSet");
1003 out.emitAttribute("type", type);
1004 }
1005
1006 public void setString(String type) {
1007 this.type = type;
1008 }
1009
1010 public void start(int i) {
1011 out.startElement("ruleChain");
1012 out.emitAttribute("key", out.getNamePool().getClarkName(i));
1013 }
1014
1015 public void end() {
1016 out.endElement();
1017 }
1018 };
1019 try {
1020 processRules(action, group);
1021 } catch (XPathException err) {
1022 // can't happen, and doesn't matter if it does
1023 }
1024
1025 }
1026
1027 /**
1028 * Export all template rules in this mode in a form that can be re-imported.
1029 * Note that template rules with union patterns may have been split into multiple
1030 * rules. We need to avoid outputting them more than once.
1031 *
1032 * @param out used to display the expression tree
1033 */
1034
1035 @Override
1036 public void exportTemplateRules(final ExpressionPresenter out) throws XPathException {
1037 //final Set<RuleTarget> processedRules = new HashSet<RuleTarget>();
1038 // TODO: if two rules share the same template, avoid duplicate output. This can happen with union patterns, and also
1039 // when a template is present in more than one mode.
1040 RuleAction action = r -> {
1041 // if (processedRules.add(r.getAction())) {
1042 r.export(out, isDeclaredStreamable());
1043 // }
1044 };
1045
1046 processRules(action);
1047
1048 }
1049
1050 /**
1051 * Walk over all the rules, applying a specified action to each one.
1052 *
1053 * @param action an action that is to be applied to all the rules in this Mode
1054 * @throws XPathException if an error occurs processing any of the rules
1055 */
1056 public void processRules(RuleAction action) throws XPathException {
1057 processRules(action, null);
1058 }
1059
1060 /**
1061 * Walk over all the rules, applying a specified action to each one.
1062 *
1063 * @param action an action that is to be applied to all the rules in this Mode
1064 * @param group - actions to be performed at group start and group end
1065 * @throws XPathException if an error occurs processing any of the rules
1066 */
1067 public void processRules(RuleAction action, RuleGroupAction group) throws XPathException {
1068 processRuleChain(documentRuleChain, action, setGroup(group, "document-node()"));
1069 processRuleChain(unnamedElementRuleChain, action, setGroup(group, "element()"));
1070 processRuleChains(namedElementRuleChains, action, setGroup(group, "namedElements"));
1071 processRuleChain(unnamedAttributeRuleChain, action, setGroup(group, "attribute()"));
1072 processRuleChains(namedAttributeRuleChains, action, setGroup(group, "namedAttributes"));
1073 processRuleChain(textRuleChain, action, setGroup(group, "text()"));
1074 processRuleChain(commentRuleChain, action, setGroup(group, "comment()"));
1075 processRuleChain(processingInstructionRuleChain, action, setGroup(group, "processing-instruction()"));
1076 processRuleChain(namespaceRuleChain, action, setGroup(group, "namespace()"));
1077 processRuleChain(genericRuleChain, action, setGroup(group, "node()"));
1078 processRuleChain(atomicValueRuleChain, action, setGroup(group, "atomicValue"));
1079 processRuleChain(functionItemRuleChain, action, setGroup(group, "function()"));
1080 }
1081
1082 /**
1083 * Set the string associated with a rule group
1084 *
1085 * @param group the group action object
1086 * @param type the type of the rule group
1087 * @return modified rulegroup action
1088 */
1089 protected RuleGroupAction setGroup(RuleGroupAction group, String type) {
1090 if (group != null) {
1091 group.setString(type);
1092 }
1093 return group;
1094 }
1095
1096
1097 public void processRuleChains(IntHashMap<RuleChain> chains, RuleAction action, RuleGroupAction group) throws XPathException {
1098 if (chains.size() > 0) {
1099 if (group != null) {
1100 group.start();
1101 }
1102 IntIterator ii = chains.keyIterator();
1103 while (ii.hasNext()) {
1104 int i = ii.next();
1105 if (group != null) {
1106 group.start(i);
1107 }
1108 RuleChain r = chains.get(i);
1109 processRuleChain(r, action, null);
1110 if (group != null) {
1111 group.end();
1112 }
1113 }
1114 if (group != null) {
1115 group.end();
1116 }
1117 }
1118 }
1119
1120 /**
1121 * Walk over all the rules, applying a specified action to each one.
1122 *
1123 * @param action an action that is to be applied to all the rules in this Mode
1124 * @throws XPathException if an error occurs processing any of the rules
1125 */
1126 public void processRuleChain(RuleChain chain, RuleAction action) throws XPathException {
1127 Rule r = chain == null ? null : chain.head();
1128 while (r != null) {
1129 action.processRule(r);
1130 r = r.getNext();
1131 }
1132 }
1133
1134
1135 public void processRuleChain(RuleChain chain, RuleAction action, RuleGroupAction group) throws XPathException {
1136 Rule r = chain == null ? null : chain.head();
1137 if (r != null) {
1138 if (group != null) {
1139 group.start();
1140 }
1141 while (r != null) {
1142 action.processRule(r);
1143 r = r.getNext();
1144 }
1145 if (group != null) {
1146 group.end();
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Perform optimization on the complete set of rules comprising this Mode. This is a null operation
1153 * in Saxon-HE.
1154 */
1155
1156 public void optimizeRules() {
1157 }
1158
1159 public int getMaxPrecedence() {
1160 try {
1161 MaxPrecedenceAction action = new MaxPrecedenceAction();
1162 processRules(action);
1163 return action.max;
1164 } catch (XPathException e) {
1165 throw new AssertionError(e);
1166 }
1167 }
1168
1169 private static class MaxPrecedenceAction implements RuleAction {
1170 public int max = 0;
1171
1172 public void processRule(Rule r) {
1173 if (r.getPrecedence() > max) {
1174 max = r.getPrecedence();
1175 }
1176 }
1177 }
1178
1179 /**
1180 * Compute a rank for each rule, as a combination of the precedence and priority, to allow
1181 * rapid comparison. This method also checks that there are no conflicts for
1182 * property values in different xsl:mode declarations
1183 *
1184 * @param start the lowest rank to use
1185 * @throws XPathException if an error occurs processing the rules
1186 */
1187
1188 public void computeRankings(int start) throws XPathException {
1189 // Now sort the rules into ranking order
1190 final RuleSorter sorter = new RuleSorter(start);
1191 // add all the rules in this Mode to the sorter
1192 processRules(sorter::addRule);
1193 // now allocate ranks to all the rules in this Mode
1194 sorter.allocateRanks();
1195 highestRank = start + sorter.getNumberOfRules();
1196 }
1197
1198 public int getMaxRank() {
1199 return highestRank;
1200 }
1201
1202 /**
1203 * Supporting class used at compile time to sort all the rules into precedence/priority
1204 * order and allocate a rank to each one, so that at run-time, comparing two rules to see
1205 * which has higher precedence/priority is a simple integer subtraction.
1206 */
1207
1208 private static class RuleSorter implements Sortable {
1209 public ArrayList<Rule> rules = new ArrayList<>(100);
1210 private int start;
1211
1212 public RuleSorter(int start) {
1213 this.start = start;
1214 }
1215
1216 public void addRule(Rule rule) {
1217 rules.add(rule);
1218 }
1219
1220 public int compare(int a, int b) {
1221 return rules.get(a).compareComputedRank(rules.get(b));
1222 }
1223
1224 public void swap(int a, int b) {
1225 Rule temp = rules.get(a);
1226 rules.set(a, rules.get(b));
1227 rules.set(b, temp);
1228 }
1229
1230 public void allocateRanks() {
1231 GenericSorter.quickSort(0, rules.size(), this);
1232 int rank = start;
1233 for (int i = 0; i < rules.size(); i++) {
1234 if (i > 0 && rules.get(i - 1).compareComputedRank(rules.get(i)) != 0) {
1235 rank++;
1236 }
1237 rules.get(i).setRank(rank);
1238 }
1239 }
1240
1241 public int getNumberOfRules() {
1242 return rules.size();
1243 }
1244 }
1245
1246
1247 /**
1248 * Interface used around a group of rules - principally at the
1249 * group start and the group end
1250 */
1251 public interface RuleGroupAction {
1252 /**
1253 * Set some string parameter for the group
1254 *
1255 * @param s a string value to be used for the group
1256 */
1257 void setString(String s);
1258
1259 /**
1260 * Start of a generic group
1261 */
1262 void start();
1263
1264 /**
1265 * Start of a group characterised by some integer parameter
1266 * @param i characteristic of this group
1267 */
1268 void start(int i);
1269
1270 /**
1271 * Invoked at the end of a group
1272 */
1273 void end();
1274
1275 }
1276
1277 /**
1278 * Allocate slots for local variables in all patterns used by the rules in this mode.
1279 * Currently used only for accumulator rules
1280 */
1281
1282 public void allocateAllPatternSlots() {
1283 final List<Integer> count = new ArrayList<>(1); // used to allow inner class to have side-effects
1284 count.add(0);
1285 final SlotManager slotManager = new SlotManager(); // TODO: allocate this via the Configuration
1286 final RuleAction slotAllocator = r -> {
1287 int slots = r.getPattern().allocateSlots(slotManager, 0);
1288 int max = Math.max(count.get(0), slots);
1289 count.set(0, max);
1290 };
1291 try {
1292 processRules(slotAllocator);
1293 } catch (XPathException e) {
1294 throw new AssertionError(e);
1295 }
1296 stackFrameSlotsNeeded = count.get(0);
1297 }
1298
1299 @Override
1300 public int getStackFrameSlotsNeeded() {
1301 return stackFrameSlotsNeeded;
1302 }
1303
1304 public void setStackFrameSlotsNeeded(int slots) {
1305 this.stackFrameSlotsNeeded = slots;
1306 }
1307
1308
1309 }
1310