Debian Codegraph @

net/sf/saxon/style/XSLKey.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.style;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Version;
12 import net.sf.saxon.expr.*;
13 import net.sf.saxon.expr.instruct.Actor;
14 import net.sf.saxon.expr.instruct.ApplyTemplates;
15 import net.sf.saxon.expr.instruct.CallTemplate;
16 import net.sf.saxon.expr.instruct.SlotManager;
17 import net.sf.saxon.expr.parser.*;
18 import net.sf.saxon.expr.sort.CodepointCollator;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.lib.StringCollator;
21 import net.sf.saxon.om.AttributeCollection;
22 import net.sf.saxon.om.StandardNames;
23 import net.sf.saxon.om.StructuredQName;
24 import net.sf.saxon.pattern.NodeTestPattern;
25 import net.sf.saxon.pattern.Pattern;
26 import net.sf.saxon.trans.*;
27 import net.sf.saxon.type.BuiltInAtomicType;
28 import net.sf.saxon.type.ErrorType;
29 import net.sf.saxon.type.ItemType;
30 import net.sf.saxon.value.SequenceType;
31 import net.sf.saxon.value.Whitespace;
32
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.function.Predicate;
36
37 /**
38 * Handler for xsl:key elements in stylesheet. <br>
39 */
40
41 public class XSLKey extends StyleElement implements StylesheetComponent {
42
43 private Pattern match;
44 private Expression use;
45 private String collationName;
46 private StructuredQName keyName;
47 SlotManager stackFrameMap;
48 private boolean rangeKey;
49 private boolean composite = false;
50
51
52 /**
53 * Get the corresponding Actor object that results from the compilation of this
54 * StylesheetComponent
55 *
56 * @return the compiled ComponentCode
57 * @throws UnsupportedOperationException for second-class components such as keys that support outwards references
58 * but not inwards references
59 */
60 public Actor getActor() {
61 throw new UnsupportedOperationException();
62 }
63
64 public SymbolicName getSymbolicName() {
65 return null;
66 }
67
68 public void checkCompatibility(Component component) {
69 // no action: keys cannot be overridden
70 }
71
72 @Override
73 public boolean isDeclaration() {
74 return true;
75 }
76
77 /**
78 * Determine whether this type of element is allowed to contain a sequence constructor
79 *
80 * @return true: yes, it may contain a sequence constructor
81 */
82
83 public boolean mayContainSequenceConstructor() {
84 return true;
85 }
86
87 /**
88 * Get the Procedure object that looks after any local variables declared in the content constructor
89 */
90
91 public SlotManager getSlotManager() {
92 return stackFrameMap;
93 }
94
95 public void prepareAttributes() throws XPathException {
96
97 String nameAtt = null;
98 String matchAtt = null;
99 String useAtt = null;
100
101 AttributeCollection atts = getAttributeList();
102
103 for (int a = 0; a < atts.getLength(); a++) {
104 String uri = atts.getURI(a);
105 String local = atts.getLocalName(a);
106 if ("".equals(uri)) {
107 switch (local) {
108 case "name":
109 nameAtt = Whitespace.trim(atts.getValue(a));
110 break;
111 case "use":
112 useAtt = atts.getValue(a);
113 use = makeExpression(useAtt, a);
114 break;
115 case "match":
116 matchAtt = atts.getValue(a);
117 break;
118 case "collation":
119 collationName = Whitespace.trim(atts.getValue(a));
120 break;
121 case "composite":
122 composite = processBooleanAttribute("composite", atts.getValue(a));
123 break;
124 default:
125 checkUnknownAttribute(atts.getNodeName(a));
126 break;
127 }
128 } else if (local.equals("range-key") && uri.equals(NamespaceConstant.SAXON)) {
129 rangeKey = processBooleanAttribute("range-key", atts.getValue(a));
130 } else {
131 checkUnknownAttribute(atts.getNodeName(a));
132 }
133 }
134
135 if (nameAtt == null) {
136 reportAbsence("name");
137 nameAtt = "_dummy_key_name";
138 }
139 try {
140 keyName = makeQName(nameAtt);
141 setObjectName(keyName);
142 } catch (XPathException err) {
143 compileErrorInAttribute(err.getMessage(), err.getErrorCodeLocalPart(), "name");
144 }
145
146 if (matchAtt == null) {
147 reportAbsence("match");
148 matchAtt = "*";
149 }
150 match = makePattern(matchAtt, "match");
151 if (match == null) {
152 // error has been reported
153 match = new NodeTestPattern(ErrorType.getInstance());
154 }
155
156 }
157
158 public StructuredQName getKeyName() {
159 //We use null to mean "not yet evaluated"
160 try {
161 if (getObjectName() == null) {
162 // allow for forwards references
163 String nameAtt = getAttributeValue("", "name");
164 if (nameAtt != null) {
165 setObjectName(makeQName(nameAtt));
166 }
167 }
168 return getObjectName();
169 } catch (XPathException err) {
170 return null; // the errors will be picked up later
171 }
172 }
173
174 public void validate(ComponentDeclaration decl) throws XPathException {
175
176 Configuration config = getConfiguration();
177 stackFrameMap = config.makeSlotManager();
178
179 checkTopLevel("XTSE0010", false);
180 if (use != null) {
181 // the value can be supplied as a content constructor in place of a use expression
182 if (hasChildNodes()) {
183 compileError("An xsl:key element with a @use attribute must be empty", "XTSE1205");
184 }
185 try {
186 RoleDiagnostic role =
187 new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "xsl:key/use", 0);
188 //role.setSourceLocator(new ExpressionLocation(this));
189 use = config.getTypeChecker(false).staticTypeCheck(
190 use,
191 SequenceType.ATOMIC_SEQUENCE,
192 role, makeExpressionVisitor());
193 } catch (XPathException err) {
194 compileError(err);
195 }
196 } else {
197 if (!hasChildNodes()) {
198 compileError("An xsl:key element must either have a @use attribute or have content", "XTSE1205");
199 }
200 }
201 use = typeCheck("use", use);
202 match = typeCheck("match", match);
203
204 // Do a further check that the use expression makes sense in the context of the match pattern
205 if (use != null) {
206 use = use.typeCheck(makeExpressionVisitor(), config.makeContextItemStaticInfo(match.getItemType(), false));
207 }
208
209 if (collationName != null) {
210 URI collationURI;
211 try {
212 collationURI = new URI(collationName);
213 if (!collationURI.isAbsolute()) {
214 URI base = new URI(getBaseURI());
215 collationURI = base.resolve(collationURI);
216 collationName = collationURI.toString();
217 }
218 } catch (URISyntaxException err) {
219 compileError("Collation name '" + collationName + "' is not a valid URI");
220 //collationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
221 }
222 } else {
223 collationName = getDefaultCollationName();
224 }
225
226 }
227
228 private static class ContainsGlobalVariable implements Predicate<Expression> {
229 public boolean test(Expression e) {
230 return e instanceof GlobalVariableReference ||
231 e instanceof UserFunctionCall ||
232 e instanceof CallTemplate ||
233 e instanceof ApplyTemplates;
234 }
235 }
236
237 private static ContainsGlobalVariable containsGlobalVariable = new ContainsGlobalVariable();
238
239 public void index(ComponentDeclaration decl, PrincipalStylesheetModule top) {
240 StructuredQName keyName = getKeyName();
241 if (keyName != null) {
242 top.getKeyManager().preRegisterKeyDefinition(keyName);
243 }
244 }
245
246 public void compileDeclaration(Compilation compilation, ComponentDeclaration decl) throws XPathException {
247 StaticContext env = getStaticContext();
248 Configuration config = env.getConfiguration();
249 StringCollator collator = null;
250 if (collationName != null) {
251 collator = findCollation(collationName, getBaseURI());
252 if (collator == null) {
253 compileError("The collation name " + Err.wrap(collationName, Err.URI) + " is not recognized", "XTSE1210");
254 collator = CodepointCollator.getInstance();
255 }
256 if (collator instanceof CodepointCollator) {
257 // if the user explicitly asks for the codepoint collation, treat it as if they hadn't asked
258 collator = null;
259 collationName = null;
260
261 } else if (!Version.platform.canReturnCollationKeys(collator)) {
262 compileError("The collation used for xsl:key must be capable of generating collation keys", "XTSE1210");
263 }
264 }
265
266 if (use == null) {
267 Expression body = compileSequenceConstructor(compilation, decl, true);
268
269 try {
270 use = Atomizer.makeAtomizer(body, null);
271 use = use.simplify();
272 } catch (XPathException e) {
273 compileError(e);
274 }
275
276 try {
277 RoleDiagnostic role =
278 new RoleDiagnostic(RoleDiagnostic.INSTRUCTION, "xsl:key/use", 0);
279 //role.setSourceLocator(new ExpressionLocation(this));
280 use = config.getTypeChecker(false).staticTypeCheck(
281 use,
282 SequenceType.ATOMIC_SEQUENCE,
283 role, makeExpressionVisitor());
284 // Do a further check that the use expression makes sense in the context of the match pattern
285 assert match != null;
286 use = use.typeCheck(makeExpressionVisitor(), config.makeContextItemStaticInfo(match.getItemType(), false));
287
288
289 } catch (XPathException err) {
290 compileError(err);
291 }
292 }
293
294 ExpressionVisitor visitor = makeExpressionVisitor();
295 ContextItemStaticInfo contextItemType = getConfiguration().makeContextItemStaticInfo(match.getItemType(), false);
296 use = use.optimize(visitor, contextItemType);
297 ItemType useItemType = use.getItemType();
298 if (useItemType == ErrorType.getInstance()) {
299 useItemType = BuiltInAtomicType.STRING; // corner case, prevents crashing
300 }
301 BuiltInAtomicType useType = (BuiltInAtomicType) useItemType.getPrimitiveItemType();
302 if (xPath10ModeIsEnabled()) {
303 if (!useType.equals(BuiltInAtomicType.STRING) && !useType.equals(BuiltInAtomicType.UNTYPED_ATOMIC)) {
304 use = new AtomicSequenceConverter(use, BuiltInAtomicType.STRING);
305 ((AtomicSequenceConverter) use).allocateConverter(config, false);
306 useType = BuiltInAtomicType.STRING;
307 }
308 }
309 allocateLocalSlots(use);
310 // first slot in pattern is reserved for current()
311 int nextFree = 0;
312 if ((match.getDependencies() & StaticProperty.DEPENDS_ON_CURRENT_ITEM) != 0) {
313 nextFree = 1;
314 }
315 int slots = match.allocateSlots(stackFrameMap, nextFree);
316
317 // If either the match pattern or the use expression references a global variable or parameter,
318 // or a call on a function or template that might reference one, then
319 // the key indexes cannot be reused across multiple transformations. See Saxon bug 1968.
320
321 boolean sensitive =
322 ExpressionTool.contains(use, false, containsGlobalVariable) ||
323 ExpressionTool.contains(match, false, containsGlobalVariable);
324
325
326 KeyManager km = getCompilation().getPrincipalStylesheetModule().getKeyManager();
327 SymbolicName symbolicName = new SymbolicName(StandardNames.XSL_KEY, keyName);
328 KeyDefinition keydef = new KeyDefinition(symbolicName, match, use, collationName, collator);
329 keydef.setPackageData(getCompilation().getPackageData());
330 keydef.setRangeKey(rangeKey);
331 keydef.setIndexedItemType(useType);
332 keydef.setStackFrameMap(stackFrameMap);
333 keydef.setLocation(getSystemId(), getLineNumber());
334 keydef.setBackwardsCompatible(xPath10ModeIsEnabled());
335 keydef.setComposite(composite);
336 keydef.obtainDeclaringComponent(this);
337 try {
338 km.addKeyDefinition(keyName, keydef, !sensitive, compilation.getConfiguration());
339 } catch (XPathException err) {
340 compileError(err);
341 }
342 }
343
344 /**
345 * Optimize the stylesheet construct
346 *
347 * @param declaration this xsl:key declaration
348 */
349
350 public void optimize(ComponentDeclaration declaration) throws XPathException {
351 // already done earlier
352 }
353
354
355 /**
356 * Generate byte code if appropriate
357 *
358 * @param opt the optimizer
359 */
360 public void generateByteCode(Optimizer opt) {}
361 }