Debian Codegraph @

net/sf/saxon/expr/instruct/ValueOf.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.Controller;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.ContextItemStaticInfo;
15 import net.sf.saxon.expr.parser.ExpressionTool;
16 import net.sf.saxon.expr.parser.ExpressionVisitor;
17 import net.sf.saxon.expr.parser.RebindingMap;
18 import net.sf.saxon.functions.SystemFunction;
19 import net.sf.saxon.om.GroundedValue;
20 import net.sf.saxon.om.Item;
21 import net.sf.saxon.om.NodeInfo;
22 import net.sf.saxon.om.StandardNames;
23 import net.sf.saxon.pattern.NodeKindTest;
24 import net.sf.saxon.trace.ExpressionPresenter;
25 import net.sf.saxon.trans.Err;
26 import net.sf.saxon.trans.XPathException;
27 import net.sf.saxon.tree.util.Orphan;
28 import net.sf.saxon.type.*;
29 import net.sf.saxon.value.Cardinality;
30 import net.sf.saxon.value.StringValue;
31 import net.sf.saxon.value.Whitespace;
32
33 /**
34 * An xsl:value-of element in the stylesheet. <br>
35 * The xsl:value-of element takes attributes:<ul>
36 * <li>a mandatory attribute select="expression".
37 * This must be a valid String expression</li>
38 * <li>an optional disable-output-escaping attribute, value "yes" or "no"</li>
39 * <li>an optional separator attribute. This is handled at compile-time: if the separator attribute
40 * is present, the select expression passed in here will be a call to the string-join() function.</li>
41 * </ul>
42 */
43
44 public final class ValueOf extends SimpleNodeConstructor {
45
46 private int options;
47 private boolean isNumberingInstruction = false; // set to true if generated by xsl:number
48 private boolean noNodeIfEmpty;
49
50 /**
51 * Create a new ValueOf expression
52 *
53 * @param select the select expression
54 * @param disable true if disable-output-escaping is in force
55 * @param noNodeIfEmpty true if the instruction is to return () if the select expression is (),
56 * false if it is to return an empty text node
57 */
58
59 public ValueOf(Expression select, boolean disable, boolean noNodeIfEmpty) {
60 setSelect(select);
61 options = disable ? ReceiverOptions.DISABLE_ESCAPING : 0;
62 this.noNodeIfEmpty = noNodeIfEmpty;
63 adoptChildExpression(select);
64
65 // If value is fixed, test whether there are any special characters that might need to be
66 // escaped when the time comes for serialization
67 if (select instanceof StringLiteral) {
68 boolean special = false;
69 CharSequence val = ((StringLiteral) select).getStringValue();
70 for (int k = 0; k < val.length(); k++) {
71 char c = val.charAt(k);
72 if ((int) c < 33 || (int) c > 126 ||
73 c == '<' || c == '>' || c == '&') {
74 special = true;
75 break;
76 }
77 }
78 if (!special) {
79 options |= ReceiverOptions.NO_SPECIAL_CHARS;
80 }
81 }
82 }
83
84 /**
85 * Indicate that this is really an xsl:nunber instruction
86 */
87
88 public void setIsNumberingInstruction() {
89 isNumberingInstruction = true;
90 }
91
92 /**
93 * Determine whether this is really an xsl:number instruction
94 *
95 * @return true if this derives from xsl:number
96 */
97
98 public boolean isNumberingInstruction() {
99 return isNumberingInstruction;
100 }
101
102 public boolean isNoNodeIfEmpty() {
103 return noNodeIfEmpty;
104 }
105
106 public String toShortString() {
107 if (getSelect() instanceof StringLiteral) {
108 return "text{" + Err.depict(((StringLiteral)getSelect()).getValue()) + "}";
109 } else {
110 return super.toShortString();
111 }
112 }
113 /**
114 * Get the name of this instruction for diagnostic and tracing purposes
115 *
116 * @return the namecode of the instruction name
117 */
118
119 public int getInstructionNameCode() {
120 if (isNumberingInstruction) {
121 return StandardNames.XSL_NUMBER;
122 } else if (getSelect() instanceof StringLiteral) {
123 return StandardNames.XSL_TEXT;
124 } else {
125 return StandardNames.XSL_VALUE_OF;
126 }
127 }
128
129 /**
130 * Test for any special options such as disable-output-escaping
131 *
132 * @return any special options
133 */
134
135 public int getOptions() {
136 return options;
137 }
138
139 /**
140 * Test whether disable-output-escaping was requested
141 *
142 * @return true if disable-output-escaping was requested
143 */
144
145 public boolean isDisableOutputEscaping() {
146 return (options & ReceiverOptions.DISABLE_ESCAPING) != 0;
147 }
148
149 /*@NotNull*/
150 public ItemType getItemType() {
151 return NodeKindTest.TEXT;
152 }
153
154 public int computeCardinality() {
155 if (noNodeIfEmpty) {
156 return StaticProperty.ALLOWS_ZERO_OR_ONE;
157 } else {
158 return StaticProperty.EXACTLY_ONE;
159 }
160 }
161
162 public void localTypeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) {
163 //
164 }
165
166 /**
167 * Determine the intrinsic dependencies of an expression, that is, those which are not derived
168 * from the dependencies of its subexpressions. For example, position() has an intrinsic dependency
169 * on the context position, while (position()+1) does not. The default implementation
170 * of the method returns 0, indicating "no dependencies".
171 *
172 * @return a set of bit-significant flags identifying the "intrinsic"
173 * dependencies. The flags are documented in class net.sf.saxon.value.StaticProperty
174 */
175 @Override
176 public int getIntrinsicDependencies() {
177 int d = super.getIntrinsicDependencies();
178 if (isDisableOutputEscaping()) {
179 // Bug 2312 : prevent extraction of global variables
180 d |= StaticProperty.DEPENDS_ON_ASSIGNABLE_GLOBALS;
181 }
182 return d;
183 }
184
185 /**
186 * Copy an expression. This makes a deep copy.
187 *
188 * @return the copy of the original expression
189 * @param rebindings variables that need to be re-bound
190 */
191
192 /*@NotNull*/
193 public Expression copy(RebindingMap rebindings) {
194 ValueOf exp = new ValueOf(getSelect().copy(rebindings), (options & ReceiverOptions.DISABLE_ESCAPING) != 0, noNodeIfEmpty);
195 ExpressionTool.copyLocationInfo(this, exp);
196 if (isNumberingInstruction) {
197 exp.setIsNumberingInstruction();
198 }
199 return exp;
200 }
201
202 /**
203 * Check statically that the results of the expression are capable of constructing the content
204 * of a given schema type.
205 *
206 * @param parentType The schema type
207 * @param whole true if this expression is to account for the whole value of the type
208 * @throws net.sf.saxon.trans.XPathException
209 * if the expression doesn't match the required content type
210 */
211
212 public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException {
213 // if the expression is a constant value, check that it is valid for the type
214 if (getSelect() instanceof Literal) {
215 GroundedValue selectValue = ((Literal) getSelect()).getValue();
216 SimpleType stype = null;
217 if (parentType instanceof SimpleType && whole) {
218 stype = (SimpleType) parentType;
219 } else if (parentType instanceof ComplexType && ((ComplexType) parentType).isSimpleContent()) {
220 stype = ((ComplexType) parentType).getSimpleContentType();
221 }
222 if (whole && stype != null && !stype.isNamespaceSensitive()) {
223 // Can't validate namespace-sensitive content statically
224 ValidationFailure err = stype.validateContent(
225 selectValue.getStringValue(), null, getConfiguration().getConversionRules());
226 if (err != null) {
227 err.setLocator(getLocation());
228 err.setErrorCode(isXSLT() ? "XTTE1540" : "XQDY0027");
229 throw err.makeException();
230 }
231 return;
232 }
233 if (parentType instanceof ComplexType &&
234 !((ComplexType) parentType).isSimpleContent() &&
235 !((ComplexType) parentType).isMixedContent() &&
236 !Whitespace.isWhite(selectValue.getStringValue())) {
237 XPathException err = new XPathException("The containing element must be of type " + parentType.getDescription() +
238 ", which does not allow text content " +
239 Err.wrap(selectValue.getStringValue()));
240 err.setLocation(getLocation());
241 err.setIsTypeError(true);
242 throw err;
243 }
244 } else {
245 // check that the type allows text nodes. If not, this is a warning condition, since the text
246 // node might turn out to be whitespace
247 // DROPPED because we can't do env.issueWarning
248 // if (parentType instanceof ComplexType &&
249 // !((ComplexType) parentType).isSimpleContent() &&
250 // !((ComplexType) parentType).isMixedContent()) {
251 // env.issueWarning("The containing element must be of type " + parentType.getDescription() +
252 // ", which does not allow text content other than whitespace", this);
253 // }
254 }
255 }
256
257 /**
258 * Convert this value-of instruction to an expression that delivers the string-value of the resulting
259 * text node as an untyped atomic value.
260 *
261 * @return the converted expression
262 */
263
264 public Expression convertToCastAsString() {
265 if (noNodeIfEmpty || !Cardinality.allowsZero(getSelect().getCardinality())) {
266 return new CastExpression(getSelect(), BuiltInAtomicType.UNTYPED_ATOMIC, true);
267 } else {
268 // must return zero-length string rather than () if empty
269 Expression sf = SystemFunction.makeCall("string", getRetainedStaticContext(), getSelect());
270 return new CastExpression(sf, BuiltInAtomicType.UNTYPED_ATOMIC, false);
271 }
272 }
273
274 /**
275 * Process this instruction
276 *
277 * @param context the dynamic context of the transformation
278 * @return a TailCall to be executed by the caller, always null for this instruction
279 */
280
281 /*@Nullable*/
282 public TailCall processLeavingTail(XPathContext context) throws XPathException {
283 if (noNodeIfEmpty) {
284 StringValue value = (StringValue) getSelect().evaluateItem(context);
285 if (value != null) {
286 processValue(value.getStringValueCS(), context);
287 }
288 return null;
289 } else {
290 return super.processLeavingTail(context);
291 }
292 }
293
294 /**
295 * Process the value of the node, to create the new node.
296 *
297 * @param value the string value of the new node
298 * @param context the dynamic evaluation context
299 * @throws XPathException if a dynamic error occurs
300 *
301 */
302
303 public void processValue(CharSequence value, XPathContext context) throws XPathException {
304 Receiver out = context.getReceiver();
305 out.characters(value, getLocation(), options);
306 }
307
308 /**
309 * Evaluate this expression, returning the resulting text node to the caller
310 *
311 * @param context the dynamic evaluation context
312 * @return the parentless text node that results from evaluating this instruction, or null to
313 * represent an empty sequence
314 * @throws XPathException if a dynamic error occurs
315 */
316
317 public NodeInfo evaluateItem(XPathContext context) throws XPathException {
318 try {
319 CharSequence val;
320 Item item = getSelect().evaluateItem(context);
321 if (item == null) {
322 if (noNodeIfEmpty) {
323 return null;
324 } else {
325 val = "";
326 }
327 } else {
328 val = item.getStringValueCS();
329 }
330 Controller controller = context.getController();
331 assert controller != null;
332 Orphan o = new Orphan(controller.getConfiguration());
333 o.setNodeKind(Type.TEXT);
334 o.setStringValue(val);
335 if ((options & ReceiverOptions.DISABLE_ESCAPING) != 0) {
336 o.setDisableOutputEscaping(true);
337 }
338 return o;
339 } catch (XPathException err) {
340 err.maybeSetLocation(getLocation());
341 throw err;
342 }
343 }
344
345
346 /**
347 * Diagnostic print of expression structure. The abstract expression tree
348 * is written to the supplied output destination.
349 */
350
351 public void export(ExpressionPresenter out) throws XPathException {
352 out.startElement("valueOf", this);
353 String flags = "";
354 if ((options & ReceiverOptions.DISABLE_ESCAPING) != 0) {
355 flags += "d";
356 }
357 if ((options & ReceiverOptions.NO_SPECIAL_CHARS) != 0) {
358 flags += "S";
359 }
360 if (noNodeIfEmpty) {
361 flags += "e";
362 }
363 if (isLocal()) {
364 flags += "l";
365 }
366 if (!flags.isEmpty()) {
367 out.emitAttribute("flags", flags);
368 }
369 getSelect().export(out);
370 out.endElement();
371 }
372 }
373