Debian Codegraph @

net/sf/saxon/expr/instruct/AnalyzeString.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.instruct;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.om.FocusIterator;
15 import net.sf.saxon.om.Item;
16 import net.sf.saxon.om.SequenceIterator;
17 import net.sf.saxon.om.StandardNames;
18 import net.sf.saxon.regex.RegexIterator;
19 import net.sf.saxon.regex.RegularExpression;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.*;
23 import net.sf.saxon.value.SequenceType;
24 import net.sf.saxon.value.StringValue;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 /**
30 * An xsl:analyze-string element in the stylesheet. New at XSLT 2.0
31 */
32
33 public class AnalyzeString extends Instruction implements ContextOriginator {
34
35 private Operand selectOp;
36 private Operand regexOp;
37 private Operand flagsOp;
38 private Operand matchingOp;
39 private Operand nonMatchingOp;
40
41 private final static OperandRole ACTION =
42 new OperandRole(OperandRole.USES_NEW_FOCUS | OperandRole.HIGHER_ORDER, OperandUsage.NAVIGATION);
43 private final static OperandRole SELECT =
44 new OperandRole(OperandRole.SETS_NEW_FOCUS, OperandUsage.ABSORPTION, SequenceType.SINGLE_STRING);
45
46 private RegularExpression pattern;
47
48 /**
49 * Construct an AnalyzeString instruction
50 *
51 * @param select the expression containing the input string
52 * @param regex the regular expression
53 * @param flags the flags parameter
54 * @param matching actions to be applied to a matching substring. May be null.
55 * @param nonMatching actions to be applied to a non-matching substring. May be null.
56 * @param pattern the compiled regular expression, if it was known statically
57 */
58 public AnalyzeString(Expression select,
59 Expression regex,
60 Expression flags,
61 Expression matching,
62 Expression nonMatching,
63 RegularExpression pattern) {
64 selectOp = new Operand(this, select, SELECT);
65 regexOp = new Operand(this, regex, OperandRole.SINGLE_ATOMIC);
66 flagsOp = new Operand(this, flags, OperandRole.SINGLE_ATOMIC);
67 if (matching != null) {
68 matchingOp = new Operand(this, matching, ACTION);
69 }
70 if (nonMatching != null) {
71 nonMatchingOp = new Operand(this, nonMatching, ACTION);
72 }
73 this.pattern = pattern;
74 }
75
76 public Expression getSelect() {
77 return selectOp.getChildExpression();
78 }
79
80 public void setSelect(Expression select) {
81 selectOp.setChildExpression(select);
82 }
83
84 public Expression getRegex() {
85 return regexOp.getChildExpression();
86 }
87
88 public void setRegex(Expression regex) {
89 regexOp.setChildExpression(regex);
90 }
91
92 public Expression getFlags() {
93 return flagsOp.getChildExpression();
94 }
95
96 public void setFlags(Expression flags) {
97 flagsOp.setChildExpression(flags);
98 }
99
100 public Expression getMatching() {
101 return matchingOp == null ? null : matchingOp.getChildExpression();
102 }
103
104 public void setMatching(Expression matching) {
105 if (matchingOp != null) {
106 matchingOp.setChildExpression(matching);
107 } else {
108 matchingOp = new Operand(this, matching, ACTION);
109 }
110 }
111
112 public Expression getNonMatching() {
113 return nonMatchingOp == null ? null : nonMatchingOp.getChildExpression();
114 }
115
116 public void setNonMatching(Expression nonMatching) {
117 if (nonMatchingOp != null) {
118 nonMatchingOp.setChildExpression(nonMatching);
119 } else {
120 nonMatchingOp = new Operand(this, nonMatching, ACTION);
121 }
122 }
123
124 public int getInstructionNameCode() {
125 return StandardNames.XSL_ANALYZE_STRING;
126 }
127
128 @Override
129 public Iterable<Operand> operands() {
130 return operandSparseList(selectOp, regexOp, flagsOp, matchingOp, nonMatchingOp);
131 }
132
133 /**
134 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
135 * This method indicates which of these methods is prefered.
136 */
137
138 public int getImplementationMethod() {
139 return Expression.PROCESS_METHOD | Expression.ITERATE_METHOD;
140 }
141
142 /**
143 * @return the compiled regular expression, if it was known statically
144 */
145 public RegularExpression getPatternExpression() {
146 return pattern;
147 }
148
149 /**
150 * Ask whether common subexpressions found in the operands of this expression can
151 * be extracted and evaluated outside the expression itself. The result is irrelevant
152 * in the case of operands evaluated with a different focus, which will never be
153 * extracted in this way, even if they have no focus dependency.
154 *
155 * @return false for this kind of expression
156 */
157 @Override
158 public boolean allowExtractingCommonSubexpressions() {
159 return false;
160 }
161
162 /*@NotNull*/
163 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
164
165 Configuration config = visitor.getConfiguration();
166 selectOp.typeCheck(visitor, contextInfo);
167 regexOp.typeCheck(visitor, contextInfo);
168 flagsOp.typeCheck(visitor, contextInfo);
169
170 if (matchingOp != null) {
171 matchingOp.typeCheck(visitor, config.makeContextItemStaticInfo(BuiltInAtomicType.STRING, false));
172 }
173 if (nonMatchingOp != null) {
174 nonMatchingOp.typeCheck(visitor, config.makeContextItemStaticInfo(BuiltInAtomicType.STRING, false));
175 }
176
177 TypeChecker tc = visitor.getConfiguration().getTypeChecker(false);
178
179 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "analyze-string/select", 0);
180 SequenceType required = SequenceType.OPTIONAL_STRING;
181 // see bug 7976
182 setSelect(tc.staticTypeCheck(getSelect(), required, role, visitor));
183
184 role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "analyze-string/regex", 0);
185 setRegex(tc.staticTypeCheck(getRegex(), SequenceType.SINGLE_STRING, role, visitor));
186
187 role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "analyze-string/flags", 0);
188 setFlags(tc.staticTypeCheck(getFlags(), SequenceType.SINGLE_STRING, role, visitor));
189
190 return this;
191 }
192
193
194 /*@NotNull*/
195 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
196
197 Configuration config = visitor.getConfiguration();
198 selectOp.optimize(visitor, contextInfo);
199 regexOp.optimize(visitor, contextInfo);
200 flagsOp.optimize(visitor, contextInfo);
201
202 if (matchingOp != null) {
203 matchingOp.optimize(visitor, config.makeContextItemStaticInfo(BuiltInAtomicType.STRING, false));
204 }
205 if (nonMatchingOp != null) {
206 nonMatchingOp.optimize(visitor, config.makeContextItemStaticInfo(BuiltInAtomicType.STRING, false));
207 }
208
209 List<String> warnings = new ArrayList<>();
210 precomputeRegex(config, warnings);
211 for (String w : warnings) {
212 visitor.getStaticContext().issueWarning(w, getLocation());
213 }
214
215 return this;
216 }
217
218 public void precomputeRegex(Configuration config, List<String> warnings) throws XPathException {
219 if (pattern == null && getRegex() instanceof StringLiteral && getFlags() instanceof StringLiteral) {
220 try {
221 final CharSequence regex = ((StringLiteral) this.getRegex()).getStringValue();
222 final CharSequence flagstr = ((StringLiteral) getFlags()).getStringValue();
223
224 String hostLang = "XP30";
225 pattern = config.compileRegularExpression(regex, flagstr.toString(), hostLang, warnings);
226
227 } catch (XPathException err) {
228 if ("XTDE1150".equals(err.getErrorCodeLocalPart())) {
229 throw err;
230 }
231 if ("FORX0001".equals(err.getErrorCodeLocalPart())) {
232 invalidRegex("Error in regular expression flags: " + err, "FORX0001");
233 } else {
234 invalidRegex("Error in regular expression: " + err, err.getErrorCodeLocalPart());
235 }
236 }
237 }
238 }
239
240 private void invalidRegex(String message, String errorCode) throws XPathException {
241 pattern = null;
242 XPathException err = new XPathException(message, errorCode);
243 err.setLocation(getLocation());
244 throw err;
245 }
246
247 /**
248 * Copy an expression. This makes a deep copy.
249 *
250 * @return the copy of the original expression
251 * @param rm the rebinding map
252 */
253
254 /*@NotNull*/
255 public Expression copy(RebindingMap rm) {
256 AnalyzeString a2 = new AnalyzeString(
257 copy(getSelect(), rm), copy(getRegex(), rm), copy(getFlags(), rm), copy(getMatching(), rm), copy(getNonMatching(), rm), pattern);
258 ExpressionTool.copyLocationInfo(this, a2);
259 return a2;
260 }
261
262 private Expression copy(Expression exp, RebindingMap rebindings) {
263 return exp == null ? null : exp.copy(rebindings);
264 }
265
266
267 /**
268 * Check that any elements and attributes constructed or returned by this expression are acceptable
269 * in the content model of a given complex type. It's always OK to say yes, since the check will be
270 * repeated at run-time. The process of checking element and attribute constructors against the content
271 * model of a complex type also registers the type of content expected of those constructors, so the
272 * static validation can continue recursively.
273 */
274
275 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
276 if (getMatching() != null) {
277 getMatching().checkPermittedContents(parentType, false);
278 }
279 if (getNonMatching() != null) {
280 getNonMatching().checkPermittedContents(parentType, false);
281 }
282 }
283
284 /**
285 * Get the item type of the items returned by evaluating this instruction
286 *
287 * @return the static item type of the instruction
288 */
289
290 /*@NotNull*/
291 public ItemType getItemType() {
292 if (getMatching() != null) {
293 if (getNonMatching() != null) {
294 TypeHierarchy th = getConfiguration().getTypeHierarchy();
295 return Type.getCommonSuperType(getMatching().getItemType(), getNonMatching().getItemType(), th);
296 } else {
297 return getMatching().getItemType();
298 }
299 } else {
300 if (getNonMatching() != null) {
301 return getNonMatching().getItemType();
302 } else {
303 return ErrorType.getInstance();
304 }
305 }
306 }
307
308 /**
309 * Compute the dependencies of an expression, as the union of the
310 * dependencies of its subexpressions. (This is overridden for path expressions
311 * and filter expressions, where the dependencies of a subexpression are not all
312 * propogated). This method should be called only once, to compute the dependencies;
313 * after that, getDependencies should be used.
314 *
315 * @return the depencies, as a bit-mask
316 */
317
318 public int computeDependencies() {
319 // some of the dependencies in the "action" part and in the grouping and sort keys aren't relevant,
320 // because they don't depend on values set outside the for-each-group expression
321 int dependencies = 0;
322 dependencies |= getSelect().getDependencies();
323 dependencies |= getRegex().getDependencies();
324 dependencies |= getFlags().getDependencies();
325 if (getMatching() != null) {
326 dependencies |= getMatching().getDependencies() & ~
327 (StaticProperty.DEPENDS_ON_FOCUS | StaticProperty.DEPENDS_ON_REGEX_GROUP);
328 }
329 if (getNonMatching() != null) {
330 dependencies |= getNonMatching().getDependencies() & ~
331 (StaticProperty.DEPENDS_ON_FOCUS | StaticProperty.DEPENDS_ON_REGEX_GROUP);
332 }
333 return dependencies;
334 }
335
336
337 /**
338 * ProcessLeavingTail: called to do the real work of this instruction. This method
339 * must be implemented in each subclass. The results of the instruction are written
340 * to the current Receiver, which can be obtained via the Controller.
341 *
342 * @param context The dynamic context of the transformation, giving access to the current node,
343 * the current variables, etc.
344 * @return null if the instruction has completed execution; or a TailCall indicating
345 * a function call or template call that is delegated to the caller, to be made after the stack has
346 * been unwound so as to save stack space.
347 */
348
349 public TailCall processLeavingTail(XPathContext context) throws XPathException {
350 RegexIterator iter = getRegexIterator(context);
351 XPathContextMajor c2 = context.newContext();
352 c2.setOrigin(this);
353 FocusIterator focusIter = c2.trackFocus(iter);
354 c2.setCurrentRegexIterator(iter);
355
356 PipelineConfiguration pipe = c2.getReceiver().getPipelineConfiguration();
357 pipe.setXPathContext(c2);
358
359 Item it;
360 while ((it = focusIter.next()) != null) {
361 if (iter.isMatching()) {
362 if (getMatching() != null) {
363 getMatching().process(c2);
364 }
365 } else {
366 if (getNonMatching() != null) {
367 getNonMatching().process(c2);
368 }
369 }
370 }
371
372 pipe.setXPathContext(context);
373 return null;
374
375 }
376
377 /**
378 * Get an iterator over the substrings defined by the regular expression
379 *
380 * @param context the evaluation context
381 * @return an iterator that returns matching and nonmatching substrings
382 * @throws XPathException if evaluation fails with a dynamic error
383 */
384
385 private RegexIterator getRegexIterator(XPathContext context) throws XPathException {
386 CharSequence input = getSelect().evaluateAsString(context);
387
388 RegularExpression re = pattern;
389 if (re == null) {
390 String flagstr = getFlags().evaluateAsString(context).toString();
391 StringValue regexString = (StringValue)getRegex().evaluateItem(context);
392 re = context.getConfiguration().compileRegularExpression(
393 getRegex().evaluateAsString(context), flagstr, "XP30", null);
394 }
395
396 return re.analyze(input);
397 }
398
399 /**
400 * Return an Iterator to iterate over the values of a sequence. The value of every
401 * expression can be regarded as a sequence, so this method is supported for all
402 * expressions. This default implementation handles iteration for expressions that
403 * return singleton values: for non-singleton expressions, the subclass must
404 * provide its own implementation.
405 *
406 * @param context supplies the context for evaluation
407 * @return a SequenceIterator that can be used to iterate over the result
408 * of the expression
409 * @throws net.sf.saxon.trans.XPathException
410 * if any dynamic error occurs evaluating the
411 * expression
412 */
413
414 /*@NotNull*/
415 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
416 RegexIterator iter = getRegexIterator(context);
417 XPathContextMajor c2 = context.newContext();
418 c2.setOrigin(this);
419 c2.trackFocus(iter);
420 c2.setCurrentRegexIterator(iter);
421
422 AnalyzeMappingFunction fn = new AnalyzeMappingFunction(iter, c2, getNonMatching(), getMatching());
423 return new ContextMappingIterator<>(fn, c2);
424 }
425
426 /**
427 * Get a name identifying the kind of expression, in terms meaningful to a user.
428 *
429 * @return a name identifying the kind of expression, in terms meaningful to a user.
430 * The name will always be in the form of a lexical XML QName, and should match the name used
431 * in explain() output displaying the expression.
432 */
433 @Override
434 public String getExpressionName() {
435 return "analyzeString";
436 }
437
438 /**
439 * Diagnostic print of expression structure. The abstract expression tree
440 * is written to the supplied output destination.
441 */
442
443 public void export(ExpressionPresenter out) throws XPathException {
444 out.startElement("analyzeString", this);
445 out.setChildRole("select");
446 getSelect().export(out);
447 out.setChildRole("regex");
448 getRegex().export(out);
449 out.setChildRole("flags");
450 getFlags().export(out);
451 if (getMatching() != null) {
452 out.setChildRole("matching");
453 getMatching().export(out);
454 }
455 if (getNonMatching() != null) {
456 out.setChildRole("nonMatching");
457 getNonMatching().export(out);
458 }
459 out.endElement();
460 }
461
462
463 }
464