Debian Codegraph @

net/sf/saxon/pattern/Pattern.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.pattern;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.SlotManager;
13 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
14 import net.sf.saxon.expr.parser.ExpressionVisitor;
15 import net.sf.saxon.expr.parser.RebindingMap;
16 import net.sf.saxon.expr.parser.XPathParser;
17 import net.sf.saxon.functions.Current;
18 import net.sf.saxon.lib.Feature;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.style.ExpressionContext;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.iter.*;
24 import net.sf.saxon.type.ItemType;
25 import net.sf.saxon.type.UType;
26
27 /**
28 * A Pattern represents the result of parsing an XSLT pattern string. <p>
29 * Patterns are created by calling the static method Pattern.make(string). <p>
30 * The pattern is used to test a particular node by calling match().
31 */
32
33 public abstract class Pattern extends PseudoExpression {
34
35 private double priority = 0.5;
36 private boolean recoverable = true;
37
38 /**
39 * Static factory method to make a Pattern by parsing a String. <br>
40 *
41 * @param pattern The pattern text as a String
42 * @param env An object defining the compile-time context for the expression
43 * @param packageData The package containing this pattern
44 * @return The pattern object
45 * @throws net.sf.saxon.trans.XPathException if the pattern is invalid
46 */
47
48 public static Pattern make(String pattern, StaticContext env, PackageData packageData) throws XPathException {
49
50 int languageLevel = env.getConfiguration().getConfigurationProperty(Feature.XPATH_VERSION_FOR_XSLT);
51 if (languageLevel == 30) {
52 languageLevel = 305; // XPath 3.0 + XSLT extensions
53 }
54 int lineNumber = env instanceof ExpressionContext ? ((ExpressionContext) env).getStyleElement().getLineNumber() : -1;
55 PatternParser parser = (PatternParser) env.getConfiguration().newExpressionParser("PATTERN", false, languageLevel);
56 ((XPathParser) parser).setLanguage(XPathParser.XSLT_PATTERN, 30);
57 Pattern pat = parser.parsePattern(pattern, env);
58 pat.setRetainedStaticContext(env.makeRetainedStaticContext());
59 // System.err.println("Simplified [" + pattern + "] to " + pat.getClass() + " default prio = " + pat.getDefaultPriority());
60 pat = pat.simplify();
61 return pat;
62 }
63
64 /**
65 * Replace any call to current() within a contained expression by a reference to a variable
66 * @param exp the expression in which the replacement is to take place (which must not itself be
67 * a call to current())
68 * @param binding the binding for the variable reference
69 */
70
71 protected static void replaceCurrent(Expression exp, LocalBinding binding) {
72 for (Operand o : exp.operands()) {
73 Expression child = o.getChildExpression();
74 if (child.isCallOn(Current.class)) {
75 LocalVariableReference ref = new LocalVariableReference(binding);
76 o.setChildExpression(ref);
77 } else {
78 replaceCurrent(child, binding);
79 }
80 }
81 }
82
83 /**
84 * Ask whether a pattern has dependencies on local variables
85 * @param pattern the pattern (typically a pattern in an xsl:number or xsl:for-each-group); or null
86 * @return true if the pattern is non-null and has dependencies on local variables
87 */
88
89 public static boolean patternContainsVariable (Pattern pattern) {
90 return pattern != null &&
91 (pattern.getDependencies() & StaticProperty.DEPENDS_ON_LOCAL_VARIABLES) != 0;
92 }
93
94 /**
95 * Ask whether the expression can be lifted out of a loop, assuming it has no dependencies
96 * on the controlling variable/focus of the loop
97 * @param forStreaming true if we are generating code for streaming
98 */
99
100 public boolean isLiftable(boolean forStreaming) {
101 return false;
102 }
103
104 /**
105 * Replace any calls on current() by a variable reference bound to the supplied binding
106 */
107
108 public void bindCurrent(LocalBinding binding) {
109 // default: no action
110 }
111
112 /**
113 * Ask whether the pattern is anchored on a call on current-group()
114 * @return true if calls on matchesBeneathAnchor should test with all nodes in the
115 * current group as anchor nodes. If false, only the first node in a group is
116 * treated as the anchor node
117 */
118
119 public boolean matchesCurrentGroup() {
120 return false;
121 }
122
123 /**
124 * Set the original text of the pattern for use in diagnostics
125 *
126 * @param text the original text of the pattern
127 */
128
129 public void setOriginalText(String text) {
130 /*originalText = text;*/
131 }
132
133 /**
134 * Ask whether dynamic errors in evaluating the pattern should be recovered. This is the default
135 * for normal XSLT patterns, but patterns used internally to represent scannable streaming expressions
136 * are non-recoverable
137 * @return true if dynamic errors in pattern evaluation should be treated as recoverable (if an error
138 * occurs, the pattern is treated as non-matching; a warning is sent to the ErrorListener).
139 */
140 public boolean isRecoverable() {
141 return recoverable;
142 }
143
144 /**
145 * Aay whether dynamic errors in evaluating the pattern should be recovered. This is the default
146 * for normal XSLT patterns, but patterns used internally to represent scannable streaming expressions
147 * are non-recoverable
148 *
149 * @param recoverable true if dynamic errors in pattern evaluation should be treated as recoverable (if an error
150 * occurs, the pattern is treated as non-matching; a warning is sent to the ErrorListener).
151 */
152
153 public void setRecoverable(boolean recoverable) {
154 this.recoverable = recoverable;
155 }
156
157 /**
158 * Handle a dynamic error occurring in the course of pattern evaluation. The effect depends on (a) whether
159 * the error is a circularity error, and (b) whether the pattern is marked as recoverable or not
160 * @param ex the exception
161 * @param context the evaluation context
162 * @throws XPathException if the error is found to be non-recoverable
163 */
164
165 protected void handleDynamicError(XPathException ex, XPathContext context) throws XPathException {
166 if ("XTDE0640".equals(ex.getErrorCodeLocalPart())) {
167 // Treat circularity error as fatal (test error213)
168 throw ex;
169 }
170 if (!isRecoverable()) {
171 // Typically happens when this is a pseudo-pattern used for scannable expressions when streaming
172 throw ex;
173 }
174 XPathException err = new XPathException("An error occurred matching pattern {" + this + "}: ", ex);
175 err.setXPathContext(context);
176 err.setErrorCodeQName(ex.getErrorCodeQName());
177 err.setLocation(getLocation());
178 context.getController().recoverableError(err);
179 }
180
181
182 /**
183 * Simplify the pattern by applying any context-independent optimisations.
184 * Default implementation does nothing.
185 *
186 */
187
188 public Pattern simplify() throws XPathException {
189 return this;
190 }
191
192 /**
193 * Type-check the pattern.
194 *
195 * @param visitor the expression visitor
196 * @param contextInfo the type of the context item at the point where the pattern
197 * is defined. Set to null if it is known that the context item is undefined.
198 * @return the optimised Pattern
199 */
200
201 public Pattern typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
202 typeCheckChildren(visitor, contextInfo);
203 return this;
204 }
205
206 /**
207 * Get the dependencies of the pattern. The only interesting dependencies for a pattern are
208 * dependencies on local variables or on user-defined functions. These are analyzed in those
209 * patterns containing predicates.
210 *
211 * @return the dependencies, as a bit-significant mask
212 */
213
214 public int getDependencies() {
215 return 0;
216 }
217
218 /**
219 * Allocate slots to any variables used within the pattern
220 *
221 * @param slotManager the slot manager representing the stack frame for local variables
222 * @param nextFree the next slot that is free to be allocated
223 * @return the next slot that is free to be allocated
224 */
225
226 public int allocateSlots(SlotManager slotManager, int nextFree) {
227 return nextFree;
228 }
229
230 /**
231 * Test whether a pattern is motionless, that is, whether it can be evaluated against a node
232 * without repositioning the input stream. This is a necessary condition for patterns used
233 * as the match pattern of a streamed template rule.
234 *
235 * @return true if the pattern is motionless, that is, if it can be evaluated against a streamed
236 * node without changing the position in the streamed input file
237 */
238
239 public boolean isMotionless() {
240 // default implementation for subclasses
241 return true;
242 }
243
244 /**
245 * Evaluate a pattern as a boolean expression, returning true if the context item matches the pattern
246 * @param context the evaluation context
247 * @return true if the context item matches the pattern
248 * @throws XPathException if an error occurs during pattern matching
249 */
250
251 public final boolean effectiveBooleanValue(XPathContext context) throws XPathException {
252 return matches(context.getContextItem(), context);
253 }
254
255 /**
256 * Determine whether this Pattern matches the given item. This is the main external interface
257 * for matching patterns: it sets current() to the node being tested
258 *
259 * @param item The item to be tested against the Pattern
260 * @param context The dynamic context.
261 * @return true if the node matches the Pattern, false otherwise
262 * @throws XPathException if an error occurs while matching the pattern (the caller will usually
263 * treat this the same as a false result)
264 */
265
266 public abstract boolean matches(Item<?> item, XPathContext context) throws XPathException;
267
268 /**
269 * Determine whether this pattern matches a given Node within the subtree rooted at a given
270 * anchor node. This method is used when the pattern is used for streaming.
271 *
272 * @param node The NodeInfo representing the Element or other node to be tested against the Pattern
273 * @param anchor The anchor node, which must match any AnchorPattern subpattern
274 * @param context The dynamic context. Only relevant if the pattern
275 * uses variables, or contains calls on functions such as document() or key().
276 * @return true if the node matches the Pattern, false otherwise
277 * @throws XPathException if an error occurs while matching the pattern (the caller will usually
278 * treat this the same as a false result)
279 */
280
281 public boolean matchesBeneathAnchor(NodeInfo node, NodeInfo anchor, XPathContext context) throws XPathException {
282 // default implementation ignores the anchor node
283 return matches(node, context);
284 }
285
286 /**
287 * Select all nodes in a document that match this pattern.
288 *
289 * @param document the document
290 * @param context the dynamic evaluation context
291 * @return an iterator over the selected nodes in the document.
292 */
293
294 public SequenceIterator<? extends NodeInfo> selectNodes(TreeInfo document, final XPathContext context) throws XPathException {
295 NodeInfo doc = document.getRootNode();
296 final UType uType = getUType();
297 if (UType.DOCUMENT.subsumes(uType)) {
298 if (matches(doc, context)) {
299 return SingletonIterator.makeIterator(doc);
300 } else {
301 return new EmptyIterator.OfNodes();
302 }
303 } else if (UType.ATTRIBUTE.subsumes(uType)) {
304 AxisIterator allElements = doc.iterateAxis(AxisInfo.DESCENDANT, NodeKindTest.ELEMENT);
305 MappingFunction<NodeInfo, NodeInfo> atts = item -> item.iterateAxis(AxisInfo.ATTRIBUTE);
306 SequenceIterator<NodeInfo> allAttributes = new MappingIterator<>(allElements, atts);
307 return new ItemMappingIterator<>(allAttributes, item -> matches(item, context) ? item : null);
308 } else if (UType.NAMESPACE.subsumes(uType)) {
309 AxisIterator allElements = doc.iterateAxis(AxisInfo.DESCENDANT, NodeKindTest.ELEMENT);
310 MappingFunction<NodeInfo, NodeInfo> atts = item -> item.iterateAxis(AxisInfo.NAMESPACE);
311 SequenceIterator<NodeInfo> allNamespaces = new MappingIterator<>(allElements, atts);
312 return new ItemMappingIterator<>(allNamespaces, item -> matches(item, context) ? item : null);
313
314 } else if (UType.CHILD_NODE_KINDS.subsumes(uType)) {
315 NodeTest nodeTest;
316 if (uType.equals(UType.ELEMENT)) {
317 nodeTest = NodeKindTest.ELEMENT; // common case, enables use of getAllElements()
318 } else {
319 nodeTest = new MultipleNodeKindTest(uType);
320 }
321 AxisIterator allChildren = doc.iterateAxis(AxisInfo.DESCENDANT, nodeTest);
322 return new ItemMappingIterator<>(allChildren, item -> matches(item, context) ? item : null);
323 } else {
324 byte axis = uType.subsumes(UType.DOCUMENT) ? AxisInfo.DESCENDANT_OR_SELF : AxisInfo.DESCENDANT;
325 AxisIterator allChildren = doc.iterateAxis(axis);
326 MappingFunction<NodeInfo, NodeInfo> processElement = item -> {
327 AxisIterator mapper = SingleNodeIterator.makeIterator(item);
328 if (uType.subsumes(UType.NAMESPACE)) {
329 mapper = new ConcatenatingAxisIterator(mapper, item.iterateAxis(AxisInfo.NAMESPACE));
330 }
331 if (uType.subsumes(UType.ATTRIBUTE)) {
332 mapper = new ConcatenatingAxisIterator(mapper, item.iterateAxis(AxisInfo.ATTRIBUTE));
333 }
334 return mapper;
335 };
336 SequenceIterator<NodeInfo> attributesOrSelf = new MappingIterator<>(allChildren, processElement);
337 ItemMappingFunction<NodeInfo, NodeInfo> test = item -> {
338 if (matches(item, context)) {
339 return item;
340 } else {
341 return null;
342 }
343 };
344 return new ItemMappingIterator<>(attributesOrSelf, test);
345
346 }
347 }
348
349 /**
350 * Get a UType indicating which kinds of items this Pattern can match.
351 *
352 * @return a UType indicating all the primitive types of item that the pattern can match.
353 */
354
355 public abstract UType getUType();
356
357
358 /**
359 * Determine the name fingerprint of nodes to which this pattern applies. Used for
360 * optimisation.
361 *
362 * @return A fingerprint that the nodes must match, or -1 if it can match multiple fingerprints,
363 * or it if matches atomic values
364 */
365
366 public int getFingerprint() {
367 return -1;
368 }
369
370 /**
371 * Get an ItemType that all the items matching this pattern must satisfy
372 *
373 * @return an ItemType, as specific as possible, which all the matching items satisfy
374 */
375
376 public abstract ItemType getItemType();
377
378 /**
379 * Set a priority to override the default priority. This is used when the pattern is written in a complex
380 * form such as a[true()] justifying a priority of 0.5, but then simplifies down to an NodeTestPattern
381 *
382 * @param priority the priority to be used if no explicit priority is given in the template rule
383 */
384
385 public void setPriority(double priority) {
386 this.priority = priority;
387 }
388
389 /**
390 * Determine the default priority to use if this pattern appears as a match pattern
391 * for a template with no explicit priority attribute.
392 *
393 * @return the default priority for the pattern
394 */
395
396 public double getDefaultPriority() {
397 return priority;
398 }
399
400 /**
401 * Get a string representation of the pattern. This will be in a form similar to the
402 * original pattern text, but not necessarily identical. It is not guaranteed to be
403 * in legal pattern syntax.
404 */
405
406 public String toString() {
407 return "pattern matching " + getItemType();
408 }
409
410 /**
411 * Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
412 *
413 * @return typically {@link net.sf.saxon.Configuration#XSLT} or {@link net.sf.saxon.Configuration#XQUERY}
414 */
415
416 public int getHostLanguage() {
417 return Configuration.XSLT;
418 }
419
420 /**
421 * Convert the pattern to a typed pattern, in which an element name is treated as
422 * schema-element(N)
423 *
424 * @param val either "strict" or "lax" depending on the value of xsl:mode/@typed
425 * @return either the original pattern unchanged, or a new pattern as the result of the
426 * conversion
427 * @throws XPathException if the pattern cannot be converted
428 */
429
430 public Pattern convertToTypedPattern(String val) throws XPathException {
431 return null;
432 }
433
434 public abstract void export(ExpressionPresenter presenter) throws XPathException;
435
436 // /**
437 // * Copy location information (the line number, priority and references to package) from one pattern
438 // * to another
439 // *
440 // * @param from the pattern containing the location information
441 // * @param to the pattern to which the information is to be copied
442 // */
443
444 // public static void copyLocationInfo(Pattern from, Pattern to) {
445 // if (from != null && to != null) {
446 // to.setSystemId(from.getSystemId());
447 // to.setLineNumber(from.getLineNumber());
448 // to.setPackageData(from.getPackageData());
449 // to.setOriginalText(from.getOriginalText());
450 // to.setPriority(from.getDefaultPriority());
451 // }
452 // }
453
454 public abstract Pattern copy(RebindingMap rebindings);
455
456 /**
457 * Perform optimisation of an expression and its subexpressions. This is the third and final
458 * phase of static optimization.
459 * <p>This method is called after all references to functions and variables have been resolved
460 * to the declaration of the function or variable, and after all type checking has been done.</p>
461 *
462 * @param visitor an expression visitor
463 * @param contextInfo the static type of "." at the point where this expression is invoked.
464 * The parameter is set to null if it is known statically that the context item will be undefined.
465 * If the type of the context item is not known statically, the argument is set to
466 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
467 * @return the original expression, rewritten if appropriate to optimize execution
468 * @throws net.sf.saxon.trans.XPathException if an error is discovered during this phase
469 * (typically a type error)
470 */
471 @Override
472 public Pattern optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
473 return this;
474 }
475
476
477 @Override
478 public String toShortString() {
479 return toString();
480 }
481
482 // //#ifdefined STREAM
483 //
484 // @Override
485 // public PostureAndSweep getStreamability(ContextItemStaticInfo contextInfo, List<String> reasons) {
486 // if (contextInfo.getContextItemPosture() == Posture.GROUNDED || isMotionless()) {
487 // return PostureAndSweep.GROUNDED_AND_MOTIONLESS;
488 // } else {
489 // if (reasons != null) {
490 // reasons.add("The pattern " + toShortString() + " is not motionless");
491 // }
492 // return PostureAndSweep.ROAMING_AND_FREE_RANGING;
493 // }
494 // }
495 //
496 // //#endif
497
498
499 }
500