Debian Codegraph @

net/sf/saxon/om/SelectedElementsSpaceStrippingRule.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.om;
9
10
11 import net.sf.saxon.event.ProxyReceiver;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.event.Stripper;
14 import net.sf.saxon.pattern.*;
15 import net.sf.saxon.style.StylesheetModule;
16 import net.sf.saxon.trace.ExpressionPresenter;
17 import net.sf.saxon.trans.rules.Rule;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.type.SchemaType;
21 import net.sf.saxon.type.Type;
22
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.TreeMap;
26
27 /**
28 * A whitespace stripping rule that strips elected elements unless xml:space indicates that whitespace
29 * should be preserved.
30 */
31
32 public class SelectedElementsSpaceStrippingRule implements SpaceStrippingRule {
33
34 // This is a cut-down version of the Mode class, which until 9.3 was used for the job, even though
35 // it is over-engineered for the task.
36
37 private Rule anyElementRule = null;
38 private Rule unnamedElementRuleChain = null;
39 private HashMap<NodeName, Rule> namedElementRules = new HashMap<NodeName, Rule>(32);
40 private int sequence = 0;
41 private boolean rejectDuplicates; // in XSLT 3.0, duplicate conflicting rules are a static error
42
43 /**
44 * Create the ruleset
45 */
46
47 public SelectedElementsSpaceStrippingRule(boolean rejectDuplicates) {
48 this.rejectDuplicates = rejectDuplicates;
49 }
50
51 /**
52 * Decide whether an element is in the set of white-space preserving element names
53 *
54 * @param fingerprint Identifies the name of the element whose whitespace is to
55 * be preserved
56 * @param schemaType
57 * @return ALWAYS_PRESERVE if the element is in the set of white-space preserving
58 * element types, ALWAYS_STRIP if the element is to be stripped regardless of the
59 * xml:space setting, and STRIP_DEFAULT otherwise
60 */
61
62 public int isSpacePreserving(NodeName fingerprint, SchemaType schemaType) throws XPathException {
63
64 Rule rule = getRule(fingerprint);
65
66 if (rule == null) {
67 return Stripper.ALWAYS_PRESERVE;
68 }
69
70 return rule.getAction() == Stripper.PRESERVE ? Stripper.ALWAYS_PRESERVE : Stripper.STRIP_DEFAULT;
71
72 }
73
74 /**
75 * Add a rule
76 *
77 * @param test a NodeTest (*, *:local, prefix:*, or QName)
78 * @param action StripRuleTarget.STRIP or StripRuleTarget.PRESERVE
79 * @param module the stylesheet module containing the rule
80 * @param lineNumber the line where the strip-space or preserve-space instruction appears
81 * @throws XPathException if this rule is a conflicting duplicate
82 */
83
84 public void addRule(NodeTest test, Stripper.StripRuleTarget action,
85 StylesheetModule module, int lineNumber) throws XPathException {
86
87 // for fast lookup, we maintain one list for each element name for patterns that can only
88 // match elements of a given name, one list for each node type for patterns that can only
89 // match one kind of non-element node, and one generic list.
90 // Each list is sorted in precedence/priority order so we find the highest-priority rule first
91
92 int precedence = module.getPrecedence();
93 int minImportPrecedence = module.getMinImportPrecedence();
94
95 NodeTestPattern pattern = new NodeTestPattern(test);
96 //pattern.setSystemId(module.getRootElement().getSystemId());
97 //pattern.setLineNumber(lineNumber);
98 addRule(pattern, action, precedence, minImportPrecedence);
99 }
100
101 public void addRule(NodeTestPattern pattern, Stripper.StripRuleTarget action, int precedence, int minImportPrecedence)
102 throws XPathException {
103 NodeTest test = pattern.getNodeTest();
104 double priority = test.getDefaultPriority();
105 Rule newRule = new Rule(pattern, action, precedence, minImportPrecedence, priority, sequence++, 0);
106 int prio = priority == 0 ? 2 : priority == -0.25 ? 1 : 0;
107 newRule.setRank((precedence << 18) + (prio << 16) + sequence);
108 if (test instanceof NodeKindTest) {
109 newRule.setAlwaysMatches(true);
110 anyElementRule = addRuleToList(newRule, anyElementRule, true);
111 } else if (test instanceof NameTest) {
112 newRule.setAlwaysMatches(true);
113 int fp = test.getFingerprint();
114 NamePool pool = ((NameTest) test).getNamePool();
115 FingerprintedQName key = new FingerprintedQName(pool.getUnprefixedQName(fp), pool);
116 Rule chain = namedElementRules.get(key);
117 namedElementRules.put(key, addRuleToList(newRule, chain, true));
118 } else {
119 unnamedElementRuleChain = addRuleToList(newRule, unnamedElementRuleChain, false);
120 }
121 }
122
123 /**
124 * Insert a new rule into this list before others of the same precedence
125 * (we rely on the fact that all rules in a list have the same priority)
126 *
127 * @param newRule the new rule to be added into the list
128 * @param list the Rule at the head of the list, or null if the list is empty
129 * @param dropRemainder if only one rule needs to be retained
130 * @return the new head of the list (which might be the old head, or the new rule if it
131 * was inserted at the start)
132 */
133
134
135 private Rule addRuleToList(Rule newRule, Rule list, boolean dropRemainder) throws XPathException {
136 if (list == null) {
137 return newRule;
138 }
139 int precedence = newRule.getPrecedence();
140 Rule rule = list;
141 Rule prev = null;
142 while (rule != null) {
143 if (rule.getPrecedence() <= precedence) {
144 if (rejectDuplicates && rule.getPrecedence() == precedence && !rule.getAction().equals(newRule.getAction())) {
145 throw new XPathException(
146 "There are conflicting xsl:strip-space and xsl:preserve-space declarations for " +
147 rule.getPattern() + " at the same import precedence", "XTSE0270");
148 }
149 newRule.setNext(dropRemainder ? null : rule);
150 if (prev == null) {
151 return newRule;
152 } else {
153 prev.setNext(newRule);
154 }
155 break;
156 } else {
157 prev = rule;
158 rule = rule.getNext();
159 }
160 }
161 if (rule == null) {
162 prev.setNext(newRule);
163 newRule.setNext(null);
164 }
165 return list;
166 }
167
168 /**
169 * Get the rule corresponding to a given element node, by finding the best pattern match.
170 *
171 * @param nodeName the name of the element node to be matched
172 * @return the best matching rule, if any (otherwise null).
173 */
174
175
176 /*@Nullable*/
177 public Rule getRule(NodeName nodeName) {
178
179 // search the specific list for this node type / node name
180
181 Rule bestRule = namedElementRules.get(nodeName);
182
183 // search the list for *:local and prefix:* node tests
184
185 if (unnamedElementRuleChain != null) {
186 bestRule = searchRuleChain(nodeName, bestRule, unnamedElementRuleChain);
187 }
188
189 // See if there is a "*" rule matching all elements
190
191 if (anyElementRule != null) {
192 bestRule = searchRuleChain(nodeName, bestRule, anyElementRule);
193 }
194
195 return bestRule;
196 }
197
198 /**
199 * Search a chain of rules
200 *
201 * @param nodeName the name of the element node being matched
202 * @param bestRule the best rule so far in terms of precedence and priority (may be null)
203 * @param head the rule at the head of the chain to be searched
204 * @return the best match rule found in the chain, or the previous best rule, or null
205 */
206
207 private Rule searchRuleChain(NodeName nodeName, Rule bestRule, Rule head) {
208 while (head != null) {
209 if (bestRule != null) {
210 int rank = head.compareRank(bestRule);
211 if (rank < 0) {
212 // if we already have a match, and the precedence or priority of this
213 // rule is lower, quit the search
214 break;
215 } else if (rank == 0) {
216 // this rule has the same precedence and priority as the matching rule already found
217 if (head.isAlwaysMatches() ||
218 ((NodeTest) head.getPattern().getItemType()).matches(Type.ELEMENT, nodeName, null)) {
219 // reportAmbiguity(bestRule, head);
220 // We no longer report the recoverable error XTRE0270, we always
221 // take the recovery action.
222 // choose whichever one comes last (assuming the error wasn't fatal)
223 bestRule = head;
224 break;
225 } else {
226 // keep searching other rules of the same precedence and priority
227 }
228 } else {
229 // this rule has higher rank than the matching rule already found
230 if (head.isAlwaysMatches() ||
231 ((NodeTest) head.getPattern().getItemType()).matches(Type.ELEMENT, nodeName, null)) {
232 bestRule = head;
233 }
234 }
235 } else if (head.isAlwaysMatches() ||
236 ((NodeTest) head.getPattern().getItemType()).matches(Type.ELEMENT, nodeName, null)) {
237 bestRule = head;
238 break;
239 }
240 head = head.getNext();
241 }
242 return bestRule;
243 }
244
245 /**
246 * Get all the rules in rank order, highest-ranking rules first
247 * @return the rules in rank order
248 */
249 public Iterator<Rule> getRankedRules() {
250 TreeMap<Integer, Rule> treeMap = new TreeMap<Integer, Rule>();
251 Rule rule = anyElementRule;
252 while (rule != null) {
253 treeMap.put(-rule.getRank(), rule);
254 rule = rule.getNext();
255 }
256 rule = unnamedElementRuleChain;
257 while (rule != null) {
258 treeMap.put(-rule.getRank(), rule);
259 rule = rule.getNext();
260 }
261 for (Rule r : namedElementRules.values()) {
262 treeMap.put(-r.getRank(), r);
263 }
264 return treeMap.values().iterator();
265 }
266
267 /**
268 * Make a filter to implement these space-stripping rules, or null if no filtering
269 * is necessary
270 *
271 * @return a filter in the form of a ProxyReceiver, or null
272 */
273 @Override
274 public ProxyReceiver makeStripper(Receiver next) {
275 return new Stripper(this, next);
276 }
277
278 /**
279 * Export this rule as part of an exported stylesheet
280 *
281 * @param presenter the output handler
282 */
283 public void export(ExpressionPresenter presenter) throws XPathException {
284 presenter.startElement("strip");
285 Rule rule = anyElementRule;
286 while (rule != null) {
287 exportRule(rule, presenter);
288 rule = rule.getNext();
289 }
290 rule = unnamedElementRuleChain;
291 while (rule != null) {
292 exportRule(rule, presenter);
293 rule = rule.getNext();
294 }
295 for (Rule r : namedElementRules.values()) {
296 exportRule(r, presenter);
297 }
298 presenter.endElement();
299
300 FastStringBuffer fsb = null;
301 boolean foundCatchAll = false;
302 if ("JS".equals(((ExpressionPresenter.ExportOptions) presenter.getOptions()).target)) {
303 presenter.startElement("stripJS");
304 fsb = new FastStringBuffer(256);
305 Iterator<Rule> iter = getRankedRules();
306 foundCatchAll = false;
307 while (iter.hasNext()) {
308 rule = iter.next();
309 exportRuleJS(rule, fsb);
310 if (rule.getPattern().getItemType() instanceof NodeKindTest) {
311 foundCatchAll = true;
312 break;
313 }
314 }
315
316 if (!foundCatchAll) {
317 fsb.append(" return false;");
318 }
319 //System.err.println(fsb.toString());
320 presenter.emitAttribute("test", fsb.toString());
321 presenter.endElement();
322 }
323 }
324
325 private static void exportRule(Rule rule, ExpressionPresenter presenter) {
326 String which = rule.getAction() == Stripper.STRIP ? "s" : "p";
327 presenter.startElement(which);
328 presenter.emitAttribute("test", rule.getPattern().getItemType().toExportString());
329 presenter.emitAttribute("prec", rule.getPrecedence()+"");
330 presenter.endElement();
331 }
332
333 private static void exportRuleJS(Rule rule, FastStringBuffer fsb) {
334 String which = rule.getAction() == Stripper.STRIP ? "true" : "false";
335 NodeTest test = (NodeTest)rule.getPattern().getItemType();
336 if (test instanceof NodeKindTest) {
337 // elements="*"
338 fsb.append("return " + which + ";");
339 } else if (test instanceof NameTest) {
340 fsb.append("if (uri=='" + test.getMatchingNodeName().getURI() +
341 "' && local=='" + test.getMatchingNodeName().getLocalPart() +
342 "') return " + which + ";" );
343 } else if (test instanceof NamespaceTest) {
344 fsb.append("if (uri=='" + ((NamespaceTest)test).getNamespaceURI() + "') return " + which + ";");
345 } else if (test instanceof LocalNameTest) {
346 fsb.append("if (local=='" + ((LocalNameTest) test).getLocalName() + "') return " + which + ";");
347 } else {
348 throw new IllegalStateException("Cannot export " + test.getClass());
349 }
350 }
351 }
352