Debian Codegraph @

net/sf/saxon/expr/instruct/DocumentInstr.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.Controller;
12 import net.sf.saxon.event.*;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.ExpressionTool;
15 import net.sf.saxon.expr.parser.RebindingMap;
16 import net.sf.saxon.functions.SystemFunction;
17 import net.sf.saxon.lib.ParseOptions;
18 import net.sf.saxon.lib.Validation;
19 import net.sf.saxon.om.Item;
20 import net.sf.saxon.om.NodeInfo;
21 import net.sf.saxon.om.SequenceIterator;
22 import net.sf.saxon.om.StandardNames;
23 import net.sf.saxon.pattern.NodeKindTest;
24 import net.sf.saxon.pattern.NodeTest;
25 import net.sf.saxon.trace.ExpressionPresenter;
26 import net.sf.saxon.trans.XPathException;
27 import net.sf.saxon.tree.linked.DocumentImpl;
28 import net.sf.saxon.tree.tiny.TinyBuilder;
29 import net.sf.saxon.tree.util.FastStringBuffer;
30 import net.sf.saxon.type.*;
31 import net.sf.saxon.value.StringValue;
32 import net.sf.saxon.value.TextFragmentValue;
33 import net.sf.saxon.value.UntypedAtomicValue;
34
35
36 /**
37 * An instruction to create a document node. This corresponds to the xsl:document-node
38 * instruction in XSLT. It is also used to support the document node constructor
39 * expression in XQuery, and is generated implicitly within an xsl:variable
40 * that constructs a temporary tree.
41 * <p>Conceptually it represents an XSLT instruction xsl:document-node,
42 * with no attributes, whose content is a complex content constructor for the
43 * children of the document node.</p>
44 */
45
46 public class DocumentInstr extends ParentNodeConstructor {
47
48 private boolean textOnly;
49 /*@Nullable*/ private String constantText;
50
51 /**
52 * Create a document constructor instruction
53 *
54 * @param textOnly true if the content contains text nodes only
55 * @param constantText if the content contains text nodes only and the text is known at compile time,
56 * supplies the textual content
57 */
58
59 public DocumentInstr(boolean textOnly,
60 String constantText) {
61 this.textOnly = textOnly;
62 this.constantText = constantText;
63 }
64
65 @Override
66 public Iterable<Operand> operands() {
67 return contentOp;
68 }
69
70 /**
71 * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process().
72 * This method indicates which of these methods is prefered. For instructions this is the process() method.
73 */
74
75 public int getImplementationMethod() {
76 return Expression.EVALUATE_METHOD;
77 }
78
79 /**
80 * Determine whether this is a "text only" document: essentially, an XSLT xsl:variable that contains
81 * a single text node or xsl:value-of instruction.
82 *
83 * @return true if this is a text-only document
84 */
85
86 public boolean isTextOnly() {
87 return textOnly;
88 }
89
90 /**
91 * For a text-only instruction, determine if the text value is fixed and if so return it;
92 * otherwise return null
93 *
94 * @return the fixed text value if appropriate; otherwise null
95 */
96
97 public /*@Nullable*/ CharSequence getConstantText() {
98 return constantText;
99 }
100
101 /**
102 * Check statically that the sequence of child instructions doesn't violate any obvious constraints
103 * on the content of the node
104 *
105 * @param env the static context
106 * @throws XPathException
107 */
108
109 protected void checkContentSequence(StaticContext env) throws XPathException {
110 checkContentSequence(env, getContentOperand(), getValidationOptions());
111 }
112
113 protected static void checkContentSequence(StaticContext env, Operand content, ParseOptions validationOptions)
114 throws XPathException {
115 Operand[] components;
116 if (content.getChildExpression() instanceof Block) {
117 components = ((Block) content.getChildExpression()).getOperanda();
118 } else {
119 components = new Operand[]{content};
120 }
121 int validation = validationOptions == null ? Validation.PRESERVE : validationOptions.getSchemaValidationMode();
122 SchemaType type = validationOptions == null ? null : validationOptions.getTopLevelType();
123 int elementCount = 0;
124 boolean isXSLT = content.getChildExpression().getPackageData().getHostLanguage() == Configuration.XSLT;
125 for (Operand o : components) {
126 Expression component = o.getChildExpression();
127 ItemType it = component.getItemType();
128 if (it instanceof NodeTest) {
129 UType possibleNodeKinds = it.getUType();
130 if (possibleNodeKinds.equals(UType.ATTRIBUTE)) {
131 XPathException de = new XPathException("Cannot create an attribute node whose parent is a document node");
132 de.setErrorCode(isXSLT ? "XTDE0420" : "XPTY0004");
133 de.setLocator(component.getLocation());
134 throw de;
135 } else if (possibleNodeKinds.equals(UType.NAMESPACE)) {
136 XPathException de = new XPathException("Cannot create a namespace node whose parent is a document node");
137 de.setErrorCode(isXSLT ? "XTDE0420" : "XQTY0024");
138 de.setLocator(component.getLocation());
139 throw de;
140 } else if (possibleNodeKinds.equals(UType.ELEMENT)) {
141 elementCount++;
142 if (elementCount > 1 &&
143 (validation == Validation.STRICT || validation == Validation.LAX || type != null)) {
144 XPathException de = new XPathException("A valid document must have only one child element");
145 if (isXSLT) {
146 de.setErrorCode("XTTE1550");
147 } else {
148 de.setErrorCode("XQDY0061");
149 }
150 de.setLocator(component.getLocation());
151 throw de;
152 }
153 if (validation == Validation.STRICT && component instanceof FixedElement) {
154 SchemaDeclaration decl = env.getConfiguration().getElementDeclaration(
155 ((FixedElement) component).getElementName().getFingerprint());
156 if (decl != null) {
157 ((FixedElement) component).getContentExpression().
158 checkPermittedContents(decl.getType(), true);
159 }
160 }
161 }
162 }
163 }
164 }
165
166 /**
167 * Get the static properties of this expression (other than its type). The result is
168 * bit-signficant. These properties are used for optimizations. In general, if
169 * property bit is set, it is true, but if it is unset, the value is unknown.
170 *
171 * @return a set of flags indicating static properties of this expression
172 */
173 @Override
174 public int computeSpecialProperties() {
175 int p = super.computeSpecialProperties();
176 p |= StaticProperty.SINGLE_DOCUMENT_NODESET;
177 if (getValidationAction() == Validation.SKIP) {
178 p |= StaticProperty.ALL_NODES_UNTYPED;
179 }
180 return p;
181 }
182
183 /**
184 * In the case of a text-only instruction (xsl:variable containing a text node or one or more xsl:value-of
185 * instructions), return an expression that evaluates to the textual content as an instance of xs:untypedAtomic
186 *
187 * @return an expression that evaluates to the textual content
188 */
189
190 public Expression getStringValueExpression() {
191 if (textOnly) {
192 if (constantText != null) {
193 return new StringLiteral(new UntypedAtomicValue(constantText));
194 } else if (getContentExpression() instanceof ValueOf) {
195 return ((ValueOf) getContentExpression()).convertToCastAsString();
196 } else {
197 Expression fn = SystemFunction.makeCall(
198 "string-join", getRetainedStaticContext(), getContentExpression(), new StringLiteral(StringValue.EMPTY_STRING));
199 CastExpression cast = new CastExpression(fn, BuiltInAtomicType.UNTYPED_ATOMIC, false);
200 ExpressionTool.copyLocationInfo(this, cast);
201 return cast;
202 }
203 } else {
204 throw new AssertionError("getStringValueExpression() called on non-text-only document instruction");
205 }
206 }
207
208
209 /**
210 * Copy an expression. This makes a deep copy.
211 *
212 * @param rebindings
213 * @return the copy of the original expression
214 */
215
216 /*@NotNull*/
217 public Expression copy(RebindingMap rebindings) {
218 DocumentInstr doc = new DocumentInstr(textOnly, constantText);
219 ExpressionTool.copyLocationInfo(this, doc);
220 doc.setContentExpression(getContentExpression().copy(rebindings));
221 doc.setValidationAction(getValidationAction(), getSchemaType());
222 return doc;
223 }
224
225 /**
226 * Get the item type
227 *
228 * @return the in
229 */
230 /*@NotNull*/
231 public ItemType getItemType() {
232 return NodeKindTest.DOCUMENT;
233 }
234
235 public TailCall processLeavingTail(XPathContext context) throws XPathException {
236 if (preservingTypes && !textOnly) {
237 Receiver out = context.getReceiver();
238 out.startDocument(0);
239 getContentExpression().process(context);
240 out.endDocument();
241 return null;
242 } else {
243 Item item = evaluateItem(context);
244 if (item != null) {
245 Receiver out = context.getReceiver();
246 out.append(item, getLocation(), ReceiverOptions.ALL_NAMESPACES);
247 }
248 return null;
249 }
250 }
251
252 /**
253 * Evaluate as an item.
254 */
255
256 public NodeInfo evaluateItem(XPathContext context) throws XPathException {
257 Controller controller = context.getController();
258 Configuration config = controller.getConfiguration();
259 assert controller != null;
260
261 NodeInfo root;
262 if (textOnly) {
263 CharSequence textValue;
264 if (constantText != null) {
265 textValue = constantText;
266 } else {
267 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
268 SequenceIterator iter = getContentExpression().iterate(context);
269 Item item;
270 while ((item = iter.next()) != null) {
271 sb.append(item.getStringValueCS());
272 }
273 textValue = sb.condense();
274 }
275 if (textValue.length() == 0) {
276 // Create a childless document node: bug 4246
277 DocumentImpl doc = new DocumentImpl();
278 doc.setSystemId(getStaticBaseURIString());
279 doc.setBaseURI(getStaticBaseURIString());
280 doc.setConfiguration(config);
281 root = doc;
282 } else {
283 root = new TextFragmentValue(config, textValue, getStaticBaseURIString());
284 }
285 } else {
286 try {
287 Receiver saved = context.getReceiver();
288 PipelineConfiguration pipe = controller.makePipelineConfiguration();
289 pipe.setXPathContext(context);
290
291 Builder builder;
292 builder = controller.makeBuilder();
293 builder.setUseEventLocation(false);
294
295 if (builder instanceof TinyBuilder) {
296 ((TinyBuilder) builder).setStatistics(config.getTreeStatistics().SOURCE_DOCUMENT_STATISTICS);
297 }
298
299 builder.setBaseURI(getStaticBaseURIString());
300 builder.setTiming(false);
301
302 pipe.setHostLanguage(getPackageData().getHostLanguage());
303 builder.setPipelineConfiguration(pipe);
304
305 Receiver out = ComplexContentOutputter.makeComplexContentReceiver(builder, getValidationOptions());
306 context.setReceiver(out);
307 out.open();
308 out.startDocument(0);
309
310 getContentExpression().process(context);
311
312 out.endDocument();
313 out.close();
314 context.setReceiver(saved);
315 root = builder.getCurrentRoot();
316 } catch (XPathException e) {
317 e.maybeSetLocation(getLocation());
318 e.maybeSetContext(context);
319 throw e;
320 }
321 }
322 return root;
323 }
324
325
326 /**
327 * Get the name of this instruction for diagnostic and tracing purposes
328 * (the string "document-constructor")
329 */
330
331 public int getInstructionNameCode() {
332 return StandardNames.XSL_DOCUMENT;
333 }
334
335 /**
336 * Diagnostic print of expression structure. The abstract expression tree
337 * is written to the supplied output destination.
338 */
339
340 public void export(ExpressionPresenter out) throws XPathException {
341 out.startElement("doc", this);
342 if (!out.isRelocatable()) {
343 out.emitAttribute("base", getStaticBaseURIString());
344 }
345 String flags = "";
346 if (textOnly) {
347 flags += "t";
348 }
349 if (isLocal()) {
350 flags += "l";
351 }
352 if (!flags.isEmpty()) {
353 out.emitAttribute("flags", flags);
354 }
355 if (constantText != null) {
356 out.emitAttribute("text", constantText);
357 }
358 if (getValidationAction() != Validation.SKIP && getValidationAction() != Validation.BY_TYPE) {
359 out.emitAttribute("validation", Validation.toString(getValidationAction()));
360 }
361 final SchemaType schemaType = getSchemaType();
362 if (schemaType != null) {
363 out.emitAttribute("type", schemaType.getStructuredQName());
364 }
365 getContentExpression().export(out);
366 out.endElement();
367 }
368
369 /**
370 * Get the (partial) name of a class that supports streaming of this kind of expression
371 *
372 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
373 * or null if there is no such class
374 */
375 @Override
376 public String getStreamerName() {
377 return "DocumentInstr";
378 }
379 }
380