Debian Codegraph @

net/sf/saxon/expr/instruct/SourceDocument.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.expr.*;
12 import net.sf.saxon.expr.accum.Accumulator;
13 import net.sf.saxon.expr.parser.*;
14 import net.sf.saxon.functions.DocumentFn;
15 import net.sf.saxon.lib.ParseOptions;
16 import net.sf.saxon.lib.Validation;
17 import net.sf.saxon.om.NodeInfo;
18 import net.sf.saxon.om.SpaceStrippingRule;
19 import net.sf.saxon.pattern.NodeKindTest;
20 import net.sf.saxon.style.StylesheetPackage;
21 import net.sf.saxon.trace.ExpressionPresenter;
22 import net.sf.saxon.trans.QuitParsingException;
23 import net.sf.saxon.trans.SaxonErrorCode;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.trans.XsltController;
26 import net.sf.saxon.tree.iter.ManualIterator;
27 import net.sf.saxon.tree.util.FastStringBuffer;
28 import net.sf.saxon.type.SchemaType;
29 import net.sf.saxon.value.SequenceType;
30
31 import java.util.HashSet;
32 import java.util.Set;
33
34 /**
35 * Non-streamable implementation of the xsl:source-document instruction
36 */
37
38 public class SourceDocument extends Instruction {
39
40 protected Operand hrefOp;
41 protected Operand bodyOp;
42
43 protected ParseOptions parseOptions;
44 protected Set<? extends Accumulator> accumulators = new HashSet<>();
45
46 public SourceDocument(Expression hrefExp, Expression body, ParseOptions options) {
47 hrefOp = new Operand(this, hrefExp, OperandRole.SINGLE_ATOMIC);
48 bodyOp = new Operand(this, body, new OperandRole(OperandRole.HAS_SPECIAL_FOCUS_RULES, OperandUsage.TRANSMISSION));
49 this.parseOptions = options;
50 this.accumulators = options.getApplicableAccumulators();
51 }
52
53
54 /**
55 * Get a name identifying the kind of expression, in terms meaningful to a user.
56 *
57 * @return a name identifying the kind of expression, in terms meaningful to a user.
58 * The name will always be in the form of a lexical XML QName, and should match the name used
59 * in explain() output displaying the expression.
60 */
61 @Override
62 public String getExpressionName() {
63 return "xsl:source-document";
64 }
65
66 public String getExportTag() {
67 return "sourceDoc";
68 }
69
70 public Expression getHref() {
71 return hrefOp.getChildExpression();
72 }
73
74 public void setHref(Expression href) {
75 hrefOp.setChildExpression(href);
76 }
77
78 public Expression getBody() {
79 return bodyOp.getChildExpression();
80 }
81
82 public void setBody(Expression body) {
83 bodyOp.setChildExpression(body);
84 }
85
86 public void setUsedAccumulators(Set<? extends Accumulator> used) {
87 accumulators = used;
88 }
89
90 @Override
91 public Iterable<Operand> operands() {
92 return operandList(hrefOp, bodyOp);
93 }
94
95 /**
96 * Ask whether common subexpressions found in the operands of this expression can
97 * be extracted and evaluated outside the expression itself. The result is irrelevant
98 * in the case of operands evaluated with a different focus, which will never be
99 * extracted in this way, even if they have no focus dependency.
100 *
101 * @return false for this kind of expression
102 */
103 @Override
104 public boolean allowExtractingCommonSubexpressions() {
105 return false;
106 }
107
108 /**
109 * Perform type checking of an expression and its subexpressions. This is the second phase of
110 * static optimization.
111 */
112 @Override
113 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
114 hrefOp.typeCheck(visitor, contextInfo);
115 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "xsl:stream/href", 0);
116 TypeChecker tc = visitor.getConfiguration().getTypeChecker(false);
117 hrefOp.setChildExpression(tc.staticTypeCheck(
118 hrefOp.getChildExpression(), SequenceType.SINGLE_STRING, role, visitor));
119 ContextItemStaticInfo newType =
120 getConfiguration().makeContextItemStaticInfo(NodeKindTest.DOCUMENT, false);
121 newType.setContextPostureStriding();
122 bodyOp.typeCheck(visitor, newType);
123 return this;
124 }
125
126 /**
127 * Perform optimisation of an expression and its subexpressions. This is the third and final
128 * phase of static optimization.
129 * <p>This method is called after all references to functions and variables have been resolved
130 * to the declaration of the function or variable, and after all type checking has been done.</p>
131 *
132 * @param visitor an expression visitor
133 * @param contextItemType the static type of "." at the point where this expression is invoked.
134 * The parameter is set to null if it is known statically that the context item will be undefined.
135 * If the type of the context item is not known statically, the argument is set to
136 * {@link net.sf.saxon.type.Type#ITEM_TYPE}
137 * @return the original expression, rewritten if appropriate to optimize execution
138 * @throws XPathException
139 * if an error is discovered during this phase
140 * (typically a type error)
141 */
142 @Override
143 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
144 ContextItemStaticInfo newType =
145 getConfiguration().makeContextItemStaticInfo(NodeKindTest.DOCUMENT, false);
146 newType.setContextPostureStriding();
147
148 hrefOp.optimize(visitor, contextItemType);
149 bodyOp.optimize(visitor, newType);
150
151 return this;
152 }
153
154 /**
155 * Determine whether this instruction creates new nodes.
156 * This implementation returns a default value of false
157 *
158 * @return true if the instruction creates new nodes (or if it can't be proved that it doesn't)
159 */
160 @Override
161 public boolean mayCreateNewNodes() {
162 return !getBody().hasSpecialProperty(StaticProperty.NO_NODES_NEWLY_CREATED);
163 }
164
165
166 /**
167 * Compute the dependencies of an expression, as the union of the
168 * dependencies of its subexpressions. (This is overridden for path expressions
169 * and filter expressions, where the dependencies of a subexpression are not all
170 * propogated). This method should be called only once, to compute the dependencies;
171 * after that, getDependencies should be used.
172 *
173 * @return the depencies, as a bit-mask
174 */
175
176 public int computeDependencies() {
177 // Focus-dependency in the body is not relevant.
178 int dependencies = 0;
179 dependencies |= getHref().getDependencies();
180 dependencies |= getBody().getDependencies() & ~StaticProperty.DEPENDS_ON_FOCUS;
181 return dependencies;
182 }
183
184 /**
185 * Get the static properties of this expression (other than its type). The result is
186 * bit-signficant. These properties are used for optimizations. In general, if
187 * property bit is set, it is true, but if it is unset, the value is unknown.
188 *
189 * @return a set of flags indicating static properties of this expression
190 */
191 @Override
192 public int computeSpecialProperties() {
193 // Not sure of the general rules here but we'll pick up some special cases which are useful for XQuery streaming
194 // use cases written using saxon:stream() - where the body is always a call on snapshot()
195 Expression body = getBody();
196 if ((body.getSpecialProperties() & StaticProperty.ALL_NODES_NEWLY_CREATED) != 0) {
197 return StaticProperty.ORDERED_NODESET | StaticProperty.PEER_NODESET;
198 }
199 return super.computeSpecialProperties();
200 }
201
202 /**
203 * Diagnostic print of expression structure. The abstract expression tree
204 * is written to the supplied output destination.
205 *
206 * @param out the expression presenter used to display the structure
207 */
208 @Override
209 public void export(ExpressionPresenter out) throws XPathException {
210 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) out.getOptions();
211 if ("JS".equals(options.target) && options.targetVersion == 1) {
212 throw new XPathException("xsl:source-document is not supported in Saxon-JS 1.*", SaxonErrorCode.SXJS0001);
213 }
214 out.startElement(getExportTag(), this);
215 int validation = parseOptions.getSchemaValidationMode();
216 if (validation != Validation.SKIP && validation != Validation.BY_TYPE) {
217 out.emitAttribute("validation", validation+"");
218 }
219 SchemaType schemaType = parseOptions.getTopLevelType();
220 if (schemaType != null) {
221 out.emitAttribute("schemaType", schemaType.getStructuredQName());
222 }
223 SpaceStrippingRule xsltStripSpace = getPackageData() instanceof StylesheetPackage
224 ? ((StylesheetPackage) getPackageData()).getSpaceStrippingRule()
225 : null;
226 if (parseOptions.getSpaceStrippingRule() == xsltStripSpace) {
227 out.emitAttribute("flags", "s");
228 }
229 if (accumulators != null && !accumulators.isEmpty()) {
230 FastStringBuffer fsb = new FastStringBuffer(256);
231 for (Accumulator acc : accumulators) {
232 if (!fsb.isEmpty()) {
233 fsb.append(" ");
234 }
235 fsb.append(acc.getAccumulatorName().getEQName());
236 }
237 out.emitAttribute("accum", fsb.toString());
238 }
239 out.setChildRole("href");
240 getHref().export(out);
241 out.setChildRole("body");
242 getBody().export(out);
243 out.endElement();
244 }
245
246 /**
247 * Copy an expression. This makes a deep copy.
248 *
249 * @return the copy of the original expression
250 * @param rebindings variables that need to be re-bound
251 */
252 @Override
253 public Expression copy(RebindingMap rebindings) {
254 SourceDocument exp = new SourceDocument(getHref().copy(rebindings), getBody().copy(rebindings), parseOptions);
255 exp.setRetainedStaticContext(getRetainedStaticContext());
256 ExpressionTool.copyLocationInfo(this, exp);
257 return exp;
258 }
259
260 /**
261 * ProcessLeavingTail: called to do the real work of this instruction. This method
262 * must be implemented in each subclass. The results of the instruction are written
263 * to the current Receiver, which can be obtained via the Controller.
264 *
265 * @param context The dynamic context of the transformation, giving access to the current node,
266 * the current variables, etc.
267 * @return null if the instruction has completed execution; or a TailCall indicating
268 * a function call or template call that is delegated to the caller, to be made after the stack has
269 * been unwound so as to save stack space.
270 */
271 @Override
272 public TailCall processLeavingTail(XPathContext context) throws XPathException {
273 try {
274 push(context);
275 } catch (QuitParsingException q) {
276 // no action, this is an early exit indicating success
277 //throw q;
278 } catch (XPathException e) {
279 e.maybeSetLocation(getLocation());
280 if (e.getErrorCodeQName() == null) {
281 e.setErrorCode("FODC0002");
282 }
283 throw e;
284 }
285 return null;
286 }
287
288 /**
289 * Evaluate the instruction in push mode
290 * @param context the evaluation context
291 * @throws XPathException in the event of a failure
292 * @throws QuitParsingException if there was an early exit, that is, if the instruction was evaluated
293 * without reading the input to completion
294 */
295
296 public void push(XPathContext context) throws XPathException {
297 String href = hrefOp.getChildExpression().evaluateAsString(context).toString();
298 NodeInfo doc = DocumentFn.makeDoc(href, getStaticBaseURIString(), getPackageData(),
299 parseOptions, context, getLocation(), false);
300 Controller controller = context.getController();
301 if (accumulators != null && controller instanceof XsltController) {
302 ((XsltController) controller).getAccumulatorManager().setApplicableAccumulators(
303 doc.getTreeInfo(), accumulators);
304 }
305 XPathContext c2 = context.newMinorContext();
306 c2.setCurrentIterator(new ManualIterator<>(doc));
307 bodyOp.getChildExpression().process(c2);
308 }
309
310
311 }
312