Debian Codegraph @

net/sf/saxon/expr/TryCatch.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;
9
10 import net.sf.saxon.event.EventBuffer;
11 import net.sf.saxon.event.EventMonitor;
12 import net.sf.saxon.expr.instruct.BreakInstr;
13 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
14 import net.sf.saxon.expr.parser.ExpressionTool;
15 import net.sf.saxon.expr.parser.ExpressionVisitor;
16 import net.sf.saxon.expr.parser.RebindingMap;
17 import net.sf.saxon.lib.NamespaceConstant;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.pattern.QNameTest;
20 import net.sf.saxon.trace.ExpressionPresenter;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.ItemType;
23 import net.sf.saxon.type.Type;
24 import net.sf.saxon.value.Cardinality;
25
26 import javax.xml.transform.ErrorListener;
27 import javax.xml.transform.TransformerException;
28 import java.util.ArrayList;
29 import java.util.List;
30
31
32 /**
33 * This class implements a try/catch expression. It consists of a try expression, and a sequence of Nametest/Catch
34 * expression pairs. If the try expression succeeds, its result is returned; otherwise the error code of the
35 * exception is matched against each of the Nametests in turn, and the first matching catch expression is
36 * evaluated.
37 */
38
39 public class TryCatch extends Expression {
40
41 private Operand tryOp;
42 private List<CatchClause> catchClauses = new ArrayList<>();
43 private boolean rollbackOutput;
44
45 public TryCatch(Expression tryExpr) {
46 this.tryOp = new Operand(this, tryExpr, OperandRole.SAME_FOCUS_ACTION);
47 }
48
49 public void addCatchExpression(QNameTest test, Expression catchExpr) {
50 CatchClause clause = new CatchClause();
51 clause.catchOp = new Operand(this, catchExpr, OperandRole.SAME_FOCUS_ACTION);
52 clause.nameTest = test;
53 catchClauses.add(clause);
54 }
55
56 public void setRollbackOutput(boolean rollback) {
57 this.rollbackOutput = rollback;
58 }
59
60 public boolean isRollbackOutput() {
61 return this.rollbackOutput;
62 }
63
64 /**
65 * Get the "try" operand
66 * @return the primary operand to be evaluated
67 */
68
69 public Operand getTryOperand() {
70 return tryOp;
71 }
72
73 /**
74 * Get the "try" expression
75 *
76 * @return the primary expression to be evaluated
77 */
78 public Expression getTryExpr() {
79 return tryOp.getChildExpression();
80 }
81
82
83 /**
84 * Get the list of catch clauses
85 *
86 * @return the list of catch clauses
87 */
88 public List<CatchClause> getCatchClauses() {
89 return catchClauses;
90 }
91
92 /**
93 * Ask whether this expression is an instruction. In XSLT streamability analysis this
94 * is used to distinguish constructs corresponding to XSLT instructions from other constructs,
95 * typically XPath expressions.
96 *
97 * @return true (if this construct exists at all in an XSLT environment, then it represents an instruction)
98 */
99 @Override
100 public boolean isInstruction() {
101 return true;
102 }
103
104 /**
105 * Ask whether common subexpressions found in the operands of this expression can
106 * be extracted and evaluated outside the expression itself. The result is irrelevant
107 * in the case of operands evaluated with a different focus, which will never be
108 * extracted in this way, even if they have no focus dependency.
109 *
110 * @return false for this kind of expression
111 */
112 @Override
113 public boolean allowExtractingCommonSubexpressions() {
114 return false;
115 }
116
117 /**
118 * Determine the cardinality of the function.
119 */
120
121 public int computeCardinality() {
122 int card = getTryExpr().getCardinality();
123 for (CatchClause catchClause : catchClauses) {
124 card = Cardinality.union(card, catchClause.catchOp.getChildExpression().getCardinality());
125 }
126 return card;
127 }
128
129 /**
130 * Determine the item type of the value returned by the function
131 */
132
133 /*@NotNull*/
134 public ItemType getItemType() {
135 ItemType type = getTryExpr().getItemType();
136 for (CatchClause catchClause : catchClauses) {
137 type = Type.getCommonSuperType(type, catchClause.catchOp.getChildExpression().getItemType());
138 }
139 return type;
140 }
141
142 /**
143 * Get the immediate sub-expressions of this expression, with information about the relationship
144 * of each expression to its parent expression. Default implementation
145 * returns a zero-length array, appropriate for an expression that has no
146 * sub-expressions.
147 *
148 * @return an iterator containing the sub-expressions of this expression
149 */
150 @Override
151 public Iterable<Operand> operands() {
152 List<Operand> list = new ArrayList<>();
153 list.add(tryOp);
154 for (CatchClause cc : catchClauses) {
155 list.add(cc.catchOp);
156 }
157 return list;
158 }
159
160 @Override
161 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
162 optimizeChildren(visitor, contextInfo);
163 Expression e = getParentExpression();
164 while (e != null) {
165 if (e instanceof LetExpression && ExpressionTool.dependsOnVariable(getTryExpr(), new Binding[]{(LetExpression)e})) {
166 ((LetExpression)e).setNeedsEagerEvaluation(true);
167 }
168 e = e.getParentExpression();
169 }
170 return this;
171 }
172
173 /**
174 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
175 * This method indicates which of these methods is provided directly. The other methods will always be available
176 * indirectly, using an implementation that relies on one of the other methods.
177 *
178 * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or
179 * {@link #PROCESS_METHOD}
180 */
181 @Override
182 public int getImplementationMethod() {
183 return ITERATE_METHOD;
184 }
185
186 /**
187 * Is this expression the same as another expression?
188 *
189 * @param other the expression to be compared with this one
190 * @return true if the two expressions are statically equivalent
191 */
192 @Override
193 public boolean equals(Object other) {
194 return other instanceof TryCatch && ((TryCatch)other).tryOp.getChildExpression().isEqual(tryOp.getChildExpression())
195 && ((TryCatch)other).catchClauses.equals(catchClauses);
196 }
197
198 /**
199 * Hashcode supporting equals()
200 */
201
202 public int computeHashCode() {
203 int h = 0x836b12a0;
204 for (int i = 0; i < catchClauses.size(); i++) {
205 h ^= catchClauses.get(i).hashCode()<<i;
206 }
207 return h + tryOp.getChildExpression().hashCode();
208 }
209
210 /**
211 * Copy an expression. This makes a deep copy.
212 *
213 * @return the copy of the original expression
214 * @param rebindings variables that need to be re-bound
215 */
216
217 /*@NotNull*/
218 public Expression copy(RebindingMap rebindings) {
219 TryCatch t2 = new TryCatch(tryOp.getChildExpression().copy(rebindings));
220 for (CatchClause clause : catchClauses) {
221 t2.addCatchExpression(clause.nameTest, clause.catchOp.getChildExpression().copy(rebindings));
222 }
223 t2.setRollbackOutput(rollbackOutput);
224 ExpressionTool.copyLocationInfo(this, t2);
225 return t2;
226 }
227
228 /**
229 * Evaluate as a singleton item
230 *
231 * @param c the dynamic XPath evaluation context
232 */
233
234 public Item evaluateItem(XPathContext c) throws XPathException {
235 XPathContext c1 = c.newMinorContext();
236 try {
237 return ExpressionTool.eagerEvaluate(tryOp.getChildExpression(), c1).head();
238 } catch (XPathException err) {
239 if (err.isGlobalError()) {
240 err.setIsGlobalError(false);
241 } else {
242 StructuredQName code = err.getErrorCodeQName();
243 if (code == null) {
244 code = new StructuredQName("saxon", NamespaceConstant.SAXON, "SXWN9000");
245 }
246 for (CatchClause clause : catchClauses) {
247 if (clause.nameTest.matches(code)) {
248 Expression caught = clause.catchOp.getChildExpression();
249 XPathContextMajor c2 = c.newContext();
250 c2.setCurrentException(err);
251 return caught.evaluateItem(c2);
252 }
253 }
254 }
255 err.setHasBeenReported(false);
256 throw err;
257 }
258 }
259
260 /**
261 * Iterate over the results of the function
262 */
263
264 /*@NotNull*/
265 public SequenceIterator<?> iterate(XPathContext c) throws XPathException {
266 XPathContextMajor c1 = c.newContext();
267 c1.createThreadManager();
268 c1.setErrorListener(new FilteringErrorListener(c.getErrorListener()));
269 try {
270 // Need to do eager iteration of the first argument to flush any errors out
271 Sequence<?> v = ExpressionTool.eagerEvaluate(tryOp.getChildExpression(), c1);
272 c1.waitForChildThreads();
273 // check for xsl:break within xsl:try - test iterate-035
274 TailCallLoop.TailCallInfo tci = c1.getTailCallInfo();
275 if (tci instanceof BreakInstr) {
276 ((BreakInstr)tci).markContext(c);
277 }
278 return v.iterate();
279 } catch (XPathException err) {
280 if (err.isGlobalError()) {
281 err.setIsGlobalError(false);
282 } else {
283 StructuredQName code = err.getErrorCodeQName();
284 for (CatchClause clause : catchClauses) {
285 if (code == null) {
286 code = new StructuredQName("saxon", NamespaceConstant.SAXON, "SXWN9000");
287 }
288 if (clause.nameTest.matches(code)) {
289 Expression caught = clause.catchOp.getChildExpression();
290 XPathContextMajor c2 = c.newContext();
291 c2.setCurrentException(err);
292 // check for xsl:break within xsl:catch - test iterate-036
293 Sequence<?> v = ExpressionTool.eagerEvaluate(caught, c2);
294 TailCallLoop.TailCallInfo tci = c2.getTailCallInfo();
295 if (tci instanceof BreakInstr) {
296 ((BreakInstr) tci).markContext(c);
297 }
298 return v.iterate();
299 }
300 }
301 }
302 err.setHasBeenReported(false);
303 throw err;
304 }
305 }
306
307 @Override
308 public void process(XPathContext context) throws XPathException {
309 XPathContextMajor c1 = context.newContext();
310 c1.createThreadManager();
311 c1.setErrorListener(new FilteringErrorListener(context.getErrorListener()));
312 EventBuffer buffer = null;
313 EventMonitor monitor = null;
314 if (rollbackOutput) {
315 buffer = new EventBuffer(context.getReceiver().getPipelineConfiguration());
316 c1.setReceiver(buffer);
317 } else {
318 monitor = new EventMonitor(context.getReceiver());
319 c1.setReceiver(monitor);
320 }
321 try {
322 tryOp.getChildExpression().process(c1);
323 c1.waitForChildThreads();
324 // check for xsl:break within xsl:try - test iterate-035
325 TailCallLoop.TailCallInfo tci = c1.getTailCallInfo();
326 if (tci instanceof BreakInstr) {
327 ((BreakInstr) tci).markContext(context);
328 }
329 if (rollbackOutput) {
330 buffer.replay(context.getReceiver());
331 }
332 } catch (XPathException err) {
333 if (err.isGlobalError()) {
334 err.setIsGlobalError(false);
335 } else {
336 StructuredQName code = err.getErrorCodeQName();
337 if (code == null) {
338 code = new StructuredQName("saxon", NamespaceConstant.SAXON, "SXWN9000");
339 }
340 for (CatchClause clause : catchClauses) {
341 if (clause.nameTest.matches(code)) {
342 if (monitor != null && monitor.hasBeenWrittenTo()) {
343 // rollback=no was specified, and output has been written, so we cannot recover
344 String message = err.getMessage() +
345 ". The error could not be caught, because rollback-output=no was specified, and output was already written to the result tree";
346 XPathException xe = new XPathException(message, "XTDE3530");
347 xe.setLocation(err.getLocator());
348 xe.setXPathContext(context);
349 throw xe;
350 }
351 Expression caught = clause.catchOp.getChildExpression();
352 XPathContextMajor c2 = context.newContext();
353 c2.setCurrentException(err);
354 // check for xsl:break within xsl:catch - test iterate-036
355 Sequence<?> v = ExpressionTool.eagerEvaluate(caught, c2);
356 TailCallLoop.TailCallInfo tci = c2.getTailCallInfo();
357 if (tci instanceof BreakInstr) {
358 ((BreakInstr) tci).markContext(context);
359 }
360 ((GroundedValue<?>) v).iterate().forEachOrFail(
361 item -> c2.getReceiver().append(item)
362 );
363 return;
364 }
365 }
366 }
367 err.setHasBeenReported(false);
368 throw err;
369
370 }
371
372 }
373
374 /**
375 * Get a name identifying the kind of expression, in terms meaningful to a user.
376 *
377 * @return a name identifying the kind of expression, in terms meaningful to a user.
378 * The name will always be in the form of a lexical XML QName, and should match the name used
379 * in explain() output displaying the expression.
380 */
381 @Override
382 public String getExpressionName() {
383 return "tryCatch"; // used in ExpressionVisitor
384 }
385
386 /**
387 * Diagnostic print of expression structure. The abstract expression tree
388 * is written to the supplied output destination.
389 *
390 * @param out the expression presenter used to display the structure
391 */
392
393 public void export(ExpressionPresenter out) throws XPathException {
394 out.startElement("try", this);
395 if (rollbackOutput) {
396 out.emitAttribute("flags", "r");
397 }
398 tryOp.getChildExpression().export(out);
399 for (CatchClause clause : catchClauses) {
400 out.startElement("catch");
401 out.emitAttribute("err", clause.nameTest.toString());
402 if ("JS".equals(((ExpressionPresenter.ExportOptions) out.getOptions()).target)) {
403 int targetVersion = ((ExpressionPresenter.ExportOptions) out.getOptions()).targetVersion;
404 out.emitAttribute("test", clause.nameTest.generateJavaScriptNameTest(targetVersion));
405 }
406 clause.catchOp.getChildExpression().export(out);
407 out.endElement();
408 }
409 out.endElement();
410 }
411
412 public static class CatchClause {
413 public int slotNumber = -1;
414 public Operand catchOp;
415 public QNameTest nameTest;
416 }
417
418 /**
419 * An error listener that filters out reporting of any errors that are caught be the try/catch
420 */
421
422 private class FilteringErrorListener implements ErrorListener {
423
424 private ErrorListener base;
425
426 FilteringErrorListener(ErrorListener base) {
427 this.base = base;
428 }
429
430 private boolean isCaught(TransformerException err) {
431 if (err instanceof XPathException) {
432 StructuredQName code = ((XPathException) err).getErrorCodeQName();
433 for (CatchClause clause : catchClauses) {
434 if (clause.nameTest.matches(code)) {
435 return true;
436 }
437 }
438 }
439 return false;
440 }
441
442 @Override
443 public void warning(TransformerException exception) throws TransformerException {
444 base.warning(exception);
445 }
446
447 @Override
448 public void error(TransformerException exception) throws TransformerException {
449 if (!isCaught(exception)) {
450 base.error(exception);
451 }
452 }
453
454 @Override
455 public void fatalError(TransformerException exception) throws TransformerException {
456 if (!isCaught(exception)) {
457 base.fatalError(exception);
458 }
459 }
460 }
461
462 /**
463 * Get the (partial) name of a class that supports streaming of this kind of expression
464 *
465 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
466 * or null if there is no such class
467 */
468 @Override
469 public String getStreamerName() {
470 return "TryCatch";
471 }
472 }
473