Debian Codegraph @

net/sf/saxon/functions/KeyFn.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.functions;
9
10 import net.sf.saxon.expr.*;
11 import net.sf.saxon.expr.parser.PathMap;
12 import net.sf.saxon.expr.parser.RetainedStaticContext;
13 import net.sf.saxon.expr.sort.LocalOrderComparer;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.pattern.NodeSetPattern;
16 import net.sf.saxon.pattern.Pattern;
17 import net.sf.saxon.trans.KeyDefinition;
18 import net.sf.saxon.trans.KeyDefinitionSet;
19 import net.sf.saxon.trans.KeyManager;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.tree.iter.EmptyIterator;
22 import net.sf.saxon.tree.util.Navigator;
23 import net.sf.saxon.type.Type;
24 import net.sf.saxon.value.AtomicValue;
25
26
27 public class KeyFn extends SystemFunction {
28
29 private KeyDefinitionSet staticKeySet = null;
30
31 public KeyManager getKeyManager() {
32 return getRetainedStaticContext().getPackageData().getKeyManager();
33 }
34
35 public NamespaceResolver getNamespaceResolver() {
36 return getRetainedStaticContext();
37 }
38
39 /**
40 * Factory method to create an internal call on key() with a known key definition
41 *
42 * @param keySet the set of KeyDefinitions (always a single KeyDefinition)
43 * @param name the name allocated to the key (first argument of the function)
44 * @param value the value being searched for (second argument of the function)
45 * @param doc the document being searched (third argument)
46 * @return a call on the key() function
47 */
48
49 public static Expression internalKeyCall(KeyManager keyManager, KeyDefinitionSet keySet,
50 String name, Expression value, Expression doc,
51 RetainedStaticContext rsc) {
52 KeyFn fn = (KeyFn) SystemFunction.makeFunction("key", rsc, 3);
53 assert fn != null;
54 fn.staticKeySet = keySet;
55 try {
56 fn.fixArguments(new StringLiteral(name), value, doc);
57 } catch (XPathException e) {
58 // ignore the failure
59 }
60 return fn.makeFunctionCall(new StringLiteral(name), value, doc);
61 }
62
63 /**
64 * Get the static properties of this expression (other than its type). The result is
65 * bit-signficant. These properties are used for optimizations. In general, if
66 * a property bit is set, it is true, but if it is unset, the value is unknown.
67 *
68 * @param arguments expressions supplied as arguments in the function call
69 */
70
71 public int getSpecialProperties(Expression[] arguments) {
72 int prop = StaticProperty.ORDERED_NODESET |
73 StaticProperty.SINGLE_DOCUMENT_NODESET |
74 StaticProperty.NO_NODES_NEWLY_CREATED;
75 if ((getArity() == 2) ||
76 (arguments[2].getSpecialProperties() & StaticProperty.CONTEXT_DOCUMENT_NODESET) != 0) {
77 prop |= StaticProperty.CONTEXT_DOCUMENT_NODESET;
78 }
79 return prop;
80 }
81
82 /**
83 * Mapping class to filter nodes that have the origin node as an ancestor-or-self
84 */
85
86 public static class SubtreeFilter implements ItemMappingFunction<NodeInfo, NodeInfo> {
87
88 private NodeInfo origin;
89
90 public SubtreeFilter(NodeInfo origin) {
91 this.origin = origin;
92 }
93
94 public NodeInfo mapItem(NodeInfo item) {
95 if (Navigator.isAncestorOrSelf(origin, item)) {
96 return item;
97 } else {
98 return null;
99 }
100 }
101
102 }
103
104 /**
105 * Allow the function to create an optimized call based on the values of the actual arguments.
106 * This binds the key definition in the common case where the key name is defined statically
107 *
108 * @param arguments the supplied arguments to the function call. Note: modifying the contents
109 * of this array should not be attempted, it is likely to have no effect.
110 * @return either a function call on this function, or an expression that delivers
111 * the same result, or null indicating that no optimization has taken place
112 * @throws XPathException if an error is detected
113 */
114 @Override
115 public Expression fixArguments(final Expression... arguments) throws XPathException {
116 if (arguments[0] instanceof StringLiteral && staticKeySet == null) {
117 KeyManager keyManager = getKeyManager();
118 String keyName = ((StringLiteral) arguments[0]).getStringValue();
119 staticKeySet = getKeyDefinitionSet(keyManager, keyName);
120 }
121 return null;
122 }
123
124 /**
125 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
126 * by an expression in a source tree.
127 * <p>The default implementation of this method assumes that an expression does no navigation other than
128 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
129 * same context as the containing expression. The method must be overridden for any expression
130 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
131 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
132 * functions because they create a new navigation root. Implementations also exist for PathExpression and
133 * FilterExpression because they have subexpressions that are evaluated in a different context from the
134 * calling expression.</p>
135 *
136 * @param pathMap the PathMap to which the expression should be added
137 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
138 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
139 * expression, and that represent possible results of this expression. For an expression that does
140 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
141 * expressions, it is the same as the input pathMapNode.
142 */
143
144 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
145 if (staticKeySet != null) {
146 PathMap.PathMapNodeSet result = new PathMap.PathMapNodeSet();
147 for (KeyDefinition kd : staticKeySet.getKeyDefinitions()) {
148 Pattern pat = kd.getMatch();
149 if (pat instanceof NodeSetPattern) {
150 Expression selector = ((NodeSetPattern) pat).getSelectionExpression();
151 PathMap.PathMapNodeSet selected = selector.addToPathMap(pathMap, pathMapNodeSet);
152 Expression use = kd.getUse();
153 PathMap.PathMapNodeSet used = use.addToPathMap(pathMap, selected);
154 result.addNodeSet(selected);
155 } else {
156 throw new IllegalStateException("Can't add key() call to pathmap");
157 }
158 }
159 return result;
160 } else {
161 throw new IllegalStateException("Can't add dynamic key() call to pathmap");
162 }
163 }
164
165
166 /**
167 * Evaluate the expression
168 *
169 * @param context the dynamic evaluation context
170 * @param arguments the values of the arguments, supplied as Sequences
171 * @return the result of the evaluation, in the form of a Sequence
172 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs during the evaluation of the expression
173 */
174 public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException {
175 NodeInfo origin;
176 if (arguments.length == 3) {
177 origin = (NodeInfo) getOrigin(context, arguments[2]);
178 } else {
179 origin = getContextRoot(context);
180 }
181 if (origin.getRoot().getNodeKind() != Type.DOCUMENT) {
182 throw new XPathException("In the key() function," +
183 " the node supplied in the third argument (or the context node if absent)" +
184 " must be in a tree whose root is a document node", "XTDE1270", context);
185 }
186
187 KeyDefinitionSet selectedKeySet = staticKeySet;
188 KeyManager keyManager = getKeyManager();
189 if (selectedKeySet == null) {
190 selectedKeySet = getKeyDefinitionSet(keyManager, arguments[0].head().getStringValue());
191 }
192 return search(keyManager, context, arguments[1], origin, selectedKeySet);
193
194 }
195
196 private static NodeInfo getContextRoot(XPathContext context) throws XPathException {
197 Item contextItem = context.getContextItem();
198 if (contextItem == null) {
199 throw new XPathException("Cannot call the key() function when there is no context item", "XTDE1270", context);
200 } else if (!(contextItem instanceof NodeInfo)) {
201 throw new XPathException("Cannot call the key() function when the context item is not a node", "XTDE1270", context);
202 }
203 return ((NodeInfo) contextItem).getRoot();
204 }
205
206 private static Item getOrigin(XPathContext context, Sequence<?> argument2) throws XPathException {
207 Item arg2;
208 try {
209 arg2 = argument2.head();
210 } catch (XPathException e) {
211 String code = e.getErrorCodeLocalPart();
212 if ("XPDY0002".equals(code) && argument2 instanceof RootExpression) {
213 throw new XPathException("Cannot call the key() function when there is no context node", "XTDE1270", context);
214 } else if ("XPDY0050".equals(code)) {
215 throw new XPathException("In the key() function," +
216 " the node supplied in the third argument (or the context node if absent)" +
217 " must be in a tree whose root is a document node", "XTDE1270", context);
218 } else if ("XPTY0020".equals(code) || "XPTY0019".equals(code)) {
219 throw new XPathException("Cannot call the key() function when the context item is an atomic value",
220 "XTDE1270", context);
221 }
222 throw e;
223 }
224 return arg2;
225 }
226
227 private KeyDefinitionSet getKeyDefinitionSet(KeyManager keyManager, String keyName) throws XPathException {
228 KeyDefinitionSet selectedKeySet;
229 StructuredQName qName = null;
230 try {
231 qName = StructuredQName.fromLexicalQName(
232 keyName, false, true,
233 getNamespaceResolver());
234 } catch (XPathException err) {
235 throw new XPathException("Invalid key name: " + err.getMessage(), "XTDE1260");
236 }
237 selectedKeySet = keyManager.getKeyDefinitionSet(qName);
238 if (selectedKeySet == null) {
239 throw new XPathException("Key '" + keyName + "' has not been defined", "XTDE1260");
240 }
241 return selectedKeySet;
242 }
243
244 protected static Sequence<NodeInfo> search(
245 final KeyManager keyManager, XPathContext context, Sequence<? extends AtomicValue> sought, NodeInfo origin, KeyDefinitionSet selectedKeySet) throws XPathException {
246
247
248 // if (internal) {
249 // System.err.println("Using key " + fprint + " on doc " + doc);
250 // }
251 NodeInfo doc = origin.getRoot();
252 if (selectedKeySet.isComposite()) {
253 SequenceIterator soughtKey = sought.iterate();
254 SequenceIterator<NodeInfo> all =
255 keyManager.selectByCompositeKey(selectedKeySet, doc.getTreeInfo(), soughtKey, context);
256 if (origin.equals(doc)) {
257 return new LazySequence(all);
258 }
259 return new LazySequence(new ItemMappingIterator(all, new SubtreeFilter(origin)));
260
261 } else {
262 // Changed by bug 2929
263 SequenceIterator<NodeInfo> allResults = null;
264 SequenceIterator<? extends AtomicValue> keys = sought.iterate();
265 AtomicValue keyValue;
266 while ((keyValue = keys.next()) != null) {
267 SequenceIterator<NodeInfo> someResults = keyManager.selectByKey(selectedKeySet, doc.getTreeInfo(), keyValue, context);
268 if (allResults == null) {
269 allResults = someResults;
270 } else {
271 allResults = new UnionEnumeration(allResults, someResults, LocalOrderComparer.getInstance());
272 }
273 }
274 if (allResults == null) {
275 allResults = EmptyIterator.OfNodes.THE_INSTANCE;
276 }
277 if (origin.equals(doc)) {
278 return new LazySequence<>(allResults);
279 }
280 return new LazySequence<>(new ItemMappingIterator<>(allResults, new SubtreeFilter(origin)));
281 }
282 }
283
284 }
285
286