Debian Codegraph @

net/sf/saxon/expr/instruct/Message.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.*;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.lib.NamespaceConstant;
15 import net.sf.saxon.lib.SerializerFactory;
16 import net.sf.saxon.lib.StandardErrorListener;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.serialize.SerializationProperties;
19 import net.sf.saxon.trace.ExpressionPresenter;
20 import net.sf.saxon.trans.Err;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.trans.XsltController;
23 import net.sf.saxon.type.*;
24 import net.sf.saxon.value.StringValue;
25 import net.sf.saxon.value.Whitespace;
26
27 import javax.xml.transform.OutputKeys;
28
29 /**
30 * An xsl:message element in the stylesheet.
31 */
32
33 public class Message extends Instruction {
34
35 private Operand selectOp;
36 private Operand terminateOp;
37 private Operand errorCodeOp;
38
39 private boolean isAssert;
40
41 /**
42 * Create an xsl:message instruction
43 *
44 * @param select the expression that constructs the message (composite of the select attribute
45 * and the contained sequence constructor)
46 * @param terminate expression that calculates terminate = yes or no.
47 * @param errorCode expression used to compute the error code
48 */
49
50 public Message(Expression select, Expression terminate, Expression errorCode) {
51 if (errorCode == null) {
52 errorCode = new StringLiteral("Q{" + NamespaceConstant.ERR + "}XTMM9000");
53 }
54 selectOp = new Operand(this, select, OperandRole.SINGLE_ATOMIC);
55 terminateOp = new Operand(this, terminate, OperandRole.SINGLE_ATOMIC);
56 errorCodeOp = new Operand(this, errorCode, OperandRole.SINGLE_ATOMIC);
57 }
58
59
60 public Expression getSelect() {
61 return selectOp.getChildExpression();
62 }
63
64 public void setSelect(Expression select) {
65 selectOp.setChildExpression(select);
66 }
67
68 public Expression getTerminate() {
69 return terminateOp.getChildExpression();
70 }
71
72 public void setTerminate(Expression terminate) {
73 terminateOp.setChildExpression(terminate);
74 }
75
76 public Expression getErrorCode() {
77 return errorCodeOp.getChildExpression();
78 }
79
80 public void setErrorCode(Expression errorCode) {
81 errorCodeOp.setChildExpression(errorCode);
82 }
83
84 @Override
85 public Iterable<Operand> operands() {
86 return operandList(selectOp, terminateOp, errorCodeOp);
87 }
88
89
90 /**
91 * Say whether this instruction is implementing xsl:message or xsl:assert
92 *
93 * @param isAssert true if this is xsl:assert; false if it is xsl:message
94 */
95
96 public void setIsAssert(boolean isAssert) {
97 this.isAssert = isAssert;
98 }
99
100 /**
101 * Copy an expression. This makes a deep copy.
102 *
103 * @param rebindings
104 * @return the copy of the original expression
105 */
106
107 /*@NotNull*/
108 public Expression copy(RebindingMap rebindings) {
109 Message exp = new Message(getSelect().copy(rebindings), getTerminate().copy(rebindings), getErrorCode().copy(rebindings));
110 ExpressionTool.copyLocationInfo(this, exp);
111 return exp;
112 }
113
114 /**
115 * Get the name of this instruction for diagnostic and tracing purposes
116 */
117
118 public int getInstructionNameCode() {
119 return isAssert ? StandardNames.XSL_ASSERT : StandardNames.XSL_MESSAGE;
120 }
121
122 /**
123 * Get the item type. To avoid spurious compile-time type errors, we falsely declare that the
124 * instruction can return anything
125 *
126 * @return AnyItemType
127 */
128 /*@NotNull*/
129 public ItemType getItemType() {
130 return AnyItemType.getInstance();
131 }
132
133 /**
134 * Get the static cardinality. To avoid spurious compile-time type errors, we falsely declare that the
135 * instruction returns zero or one items - this is always acceptable
136 *
137 * @return zero or one
138 */
139
140 public int getCardinality() {
141 return StaticProperty.ALLOWS_ZERO_OR_ONE;
142 }
143
144 /**
145 * Determine whether this instruction creates new nodes.
146 * This implementation returns true.
147 */
148
149 public final boolean mayCreateNewNodes() {
150 return true;
151 }
152
153 /**
154 * Perform optimisation of an expression and its subexpressions. This is the third and final
155 * phase of static optimization.
156 * <p>This method is called after all references to functions and variables have been resolved
157 * to the declaration of the function or variable, and after all type checking has been done.</p>
158 *
159 * @param visitor an expression visitor
160 * @param contextInfo the static type of "." at the point where this expression is invoked.
161 * The parameter is set to null if it is known statically that the context item will be undefined.
162 * If the type of the context item is not known statically, the argument is set to
163 * {@link Type#ITEM_TYPE}
164 * @return the original expression, rewritten if appropriate to optimize execution
165 * @throws XPathException if an error is discovered during this phase
166 * (typically a type error)
167 */
168 @Override
169 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
170 Expression e = super.optimize(visitor, contextInfo);
171 if (e != this) {
172 return e;
173 }
174 // if (visitor.isOptimizeForStreaming()) {
175 // DocumentInstr doc = new DocumentInstr(false, null);
176 // doc.setContentExpression(getSelect());
177 // setSelect(doc);
178 // }
179 return this;
180 }
181
182 public TailCall processLeavingTail(XPathContext context) throws XPathException {
183 XsltController controller = (XsltController) context.getController();
184 if (isAssert && !controller.isAssertionsEnabled()) {
185 return null;
186 }
187 Receiver emitter = controller.makeMessageReceiver();
188 PipelineConfiguration pipe = controller.makePipelineConfiguration();
189 pipe.setHostLanguage(Configuration.XSLT);
190 pipe.setXPathContext(context);
191 emitter.setPipelineConfiguration(pipe);
192
193 String code;
194 try {
195 code = getErrorCode().evaluateAsString(context).toString();
196 } catch (XPathException err) {
197 // use the error code of the failure in place of the intended error code
198 code = err.getErrorCodeQName().getEQName();
199 }
200
201 StructuredQName errorCode = null;
202 try {
203 errorCode = StructuredQName.fromLexicalQName(
204 code, false, true, getRetainedStaticContext());
205 } catch (XPathException err) {
206 // The spec says we fall back to XTMM9000
207 errorCode = new StructuredQName("err", NamespaceConstant.ERR, "XTMM9000");
208 }
209
210 controller.incrementMessageCounter(errorCode);
211
212 SequenceReceiver rec = new TreeReceiver(emitter);
213 rec = new MessageAdapter(rec, errorCode.getEQName(), getLocation());
214
215 Receiver saved = context.getReceiver();
216
217 SerializationProperties props = new SerializationProperties();
218 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
219 SerializerFactory sf = context.getConfiguration().getSerializerFactory();
220
221 Receiver receiver = sf.getReceiver(rec, props, pipe);
222 context.setReceiver(receiver);
223
224 boolean abort = false;
225 String term = Whitespace.trim(getTerminate().evaluateAsString(context));
226 switch (term) {
227 case "no":
228 case "false":
229 case "0":
230 // no action
231 break;
232 case "yes":
233 case "true":
234 case "1":
235 abort = true;
236 break;
237 default:
238 XPathException e = new XPathException("The terminate attribute of xsl:message must be yes|no|true|false|1|0");
239 e.setXPathContext(context);
240 e.setErrorCode("XTDE0030");
241 throw e;
242 }
243
244
245 rec.startDocument(abort ? ReceiverOptions.TERMINATE : 0);
246
247 try {
248 SequenceIterator iter = getSelect().iterate(context);
249 Item item;
250 while ((item = iter.next()) != null) {
251 rec.append(item, getLocation(), ReceiverOptions.ALL_NAMESPACES);
252 }
253 } catch (XPathException e) {
254 rec.append(new StringValue("Error " + e.getErrorCodeLocalPart() +
255 " while evaluating xsl:message at line "
256 + getLocation().getLineNumber() + " of " + getLocation().getSystemId() +
257 ": " + e.getMessage()));
258 }
259
260 rec.endDocument();
261 rec.close();
262 context.setReceiver(saved);
263 if (abort) {
264 TerminationException te = new TerminationException(
265 "Processing terminated by " + StandardErrorListener.getInstructionName(this) +
266 " at line " + getLocation().getLineNumber() +
267 " in " + StandardErrorListener.abbreviatePath(getLocation().getSystemId()));
268 te.setLocation(getLocation());
269 te.setErrorCodeQName(errorCode);
270 throw te;
271 }
272 return null;
273
274 }
275
276 /**
277 * Diagnostic print of expression structure. The abstract expression tree
278 * is written to the supplied output destination.
279 */
280
281 public void export(ExpressionPresenter out) throws XPathException {
282 out.startElement("message", this);
283 out.setChildRole("select");
284 getSelect().export(out);
285 out.setChildRole("terminate");
286 getTerminate().export(out);
287 out.setChildRole("error");
288 getErrorCode().export(out);
289 out.endElement();
290 }
291
292
293 /**
294 * The MessageAdapter is a filter applied to the message pipeline which is designed to ensure that outputting an attribute
295 * with no containing element (for example &lt;xsl:message select="@x"/>) is not an error. Such an attribute is wrapped in
296 * a processing instruction so it can exist as a child of a document node.
297 * <p>
298 * The MessageAdapter also inserts (as the first event after startDocument) a processing instruction
299 * containing the error code, in the form &lt;?error-code Q{uri}local?>; the Location object passed
300 * with this processing instruction represents the stylesheet location of the xsl:message instruction.
301 */
302
303 private static class MessageAdapter extends ProxyReceiver {
304 private boolean contentStarted = true;
305 private String errorCode;
306 private Location location;
307
308 public MessageAdapter(SequenceReceiver next, String errorCode, Location location) {
309 super(next);
310 this.errorCode = errorCode;
311 this.location = location;
312 }
313
314 @Override
315 public void startDocument(int properties) throws XPathException {
316 super.startDocument(properties);
317 processingInstruction("error-code", errorCode, location, 0);
318 }
319
320 @Override
321 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
322 contentStarted = false;
323 super.startElement(nameCode, typeCode, location, properties);
324 }
325
326 @Override
327 public void startContent() throws XPathException {
328 contentStarted = true;
329 super.startContent();
330 }
331
332 @Override
333 public void attribute(NodeName attributeName, SimpleType typeCode, CharSequence value, Location locationId, int properties)
334 throws XPathException {
335 if (contentStarted) {
336 String attName = attributeName.getDisplayName();
337 processingInstruction("attribute", "name=\"" + attName + "\" value=\"" + value + "\"", locationId, 0);
338 } else {
339 super.attribute(attributeName, typeCode, value, locationId, properties);
340 }
341 }
342
343 @Override
344 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
345 if (contentStarted) {
346 for (NamespaceBinding ns : namespaceBindings) {
347 String prefix = ns.getPrefix();
348 String uri = ns.getURI();
349 processingInstruction("namespace", "prefix=\"" + prefix + "\" uri=\"" + uri + "\"", ExplicitLocation.UNKNOWN_LOCATION, 0);
350 }
351 } else {
352 super.namespace(namespaceBindings, properties);
353 }
354 }
355
356 @Override
357 public void append(Item item, Location locationId, int copyNamespaces) throws XPathException {
358 if (item instanceof NodeInfo) {
359 int kind = ((NodeInfo) item).getNodeKind();
360 if (kind == Type.ATTRIBUTE || kind == Type.NAMESPACE) {
361 ((NodeInfo) item).copy(this, 0, locationId);
362 return;
363 }
364 } else if (item instanceof Function && !((Function) item).isArray()) {
365 CharSequence representation = ((Function) item).isMap() ? Err.depict(item) : "Function " + Err.depict(item);
366 nextReceiver.characters(representation, locationId, 0);
367 return;
368 }
369 nextReceiver.append(item, locationId, copyNamespaces);
370 }
371 }
372
373 }