Debian Codegraph @

net/sf/saxon/testdriver/Xslt30TestSuiteDriverHE.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.testdriver;
9
10
11 import net.sf.saxon.Configuration;
12 import net.sf.saxon.Query;
13 import net.sf.saxon.expr.instruct.GlobalParameterSet;
14 import net.sf.saxon.functions.ResolveQName;
15 import net.sf.saxon.lib.*;
16 import net.sf.saxon.om.GroundedValue;
17 import net.sf.saxon.om.StructuredQName;
18 import net.sf.saxon.s9api.*;
19 import net.sf.saxon.s9api.streams.Step;
20 import net.sf.saxon.trace.XSLTTraceListener;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.trans.XsltController;
23 import net.sf.saxon.value.AtomicValue;
24 import net.sf.saxon.value.QNameValue;
25
26 import javax.xml.transform.Result;
27 import javax.xml.transform.Source;
28 import javax.xml.transform.SourceLocator;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.stream.StreamResult;
31 import javax.xml.transform.stream.StreamSource;
32 import java.io.*;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.*;
36 import java.util.function.Predicate;
37
38 import static net.sf.saxon.s9api.streams.Predicates.*;
39 import static net.sf.saxon.s9api.streams.Steps.*;
40
41 /**
42 * This class runs the W3C XSLT Test Suite, driven from the test catalog.
43 */
44 public class Xslt30TestSuiteDriverHE extends TestDriver {
45
46
47 public Xslt30TestSuiteDriverHE() {
48 spec = Spec.XT30;
49 setDependencyData();
50 }
51
52
53 public static void main(String[] args) throws Exception {
54 if (args.length == 0 || args[0].equals("-?")) {
55 usage();
56 }
57 new Xslt30TestSuiteDriverHE().go(args);
58 }
59
60 protected static void usage() {
61 System.err.println("java com.saxonica.testdriver.Xslt30TestSuiteDriver[HE] testsuiteDir catalog [-o:resultsdir] [-s:testSetName]" +
62 " [-t:testNamePattern] [-bytecode:on|off|debug] [-export] [-tree] [-lang] [-save] [-streaming:off|std|ext]" +
63 " [-xt30:on] [-T] [-js] [-XX:compiler-location]");
64 }
65
66 @Override
67 public String catalogNamespace() {
68 return "http://www.w3.org/2012/10/xslt-test-catalog";
69 }
70
71
72 @Override
73 public void processSpec(String specStr) {
74 switch (specStr) {
75 case "XT10":
76 spec = Spec.XT10;
77 break;
78 case "XT20":
79 spec = Spec.XT20;
80 break;
81 case "XT30":
82 spec = Spec.XT30;
83 break;
84 default:
85 throw new IllegalArgumentException("Unknown spec " + specStr);
86 }
87 resultsDoc = new Xslt30TestReport(this, spec);
88 }
89
90 @Override
91 protected void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc) throws SaxonApiException {
92 for (XdmNode env : catalog.select(descendant("environment")).asListOfNodes()) {
93 Environment.processEnvironment(
94 this, xpc, env, globalEnvironments, localEnvironments.get("default"));
95 }
96 }
97
98 protected boolean isSlow(String testName) {
99 //return false;
100 return testName.startsWith("regex-classes")
101 || testName.equals("normalize-unicode-008")
102 || (testName.equals("function-1031") && driverProc.getSaxonEdition().equals("HE"));
103 // || testName.equals("catalog-005");
104 }
105
106 protected static Predicate<XdmItem> isTrue(String attName) {
107 return element -> {
108 if (element instanceof XdmNode) {
109 String attVal = ((XdmNode) element).attribute(attName);
110 if (attVal != null) {
111 attVal = attVal.trim();
112 return "yes".equals(attVal) || "1".equals(attVal) || "true".equals(attVal);
113 }
114 }
115 return false;
116 };
117 }
118
119 @Override
120 protected void runTestCase(XdmNode testCase, XPathCompiler xpath) throws SaxonApiException {
121
122 final TestOutcome outcome = new TestOutcome(this);
123 String testName = testCase.attribute("name");
124 String testSetName = testCase.getParent().attribute("name");
125
126 if (exceptionsMap.containsKey("$" + testSetName)) {
127 notrun++;
128 XdmNode exceptionElement = exceptionsMap.get("$" + testSetName);
129 resultsDoc.writeTestcaseElement(testName, exceptionElement.attribute("report"),
130 exceptionElement.axisIterator(Axis.CHILD, new QName("reason")).next().getStringValue());
131 return;
132 }
133
134 if (exceptionsMap.containsKey(testName)) {
135 notrun++;
136 XdmNode exceptionElement = exceptionsMap.get(testName);
137 resultsDoc.writeTestcaseElement(testName, exceptionElement.attribute("report"),
138 exceptionElement.axisIterator(Axis.CHILD, new QName("reason")).next().getStringValue());
139 return;
140 }
141
142 if (isSlow(testName)) {
143 notrun++;
144 resultsDoc.writeTestcaseElement(testName, "tooBig", "requires excessive resources");
145 return;
146 }
147
148 Step<XdmNode> testSetDependencies = root().then(child("test-set").then(child("dependencies")));
149 Step<XdmNode> testCaseDependencies = child("dependencies");
150 XdmValue allDependencies = testCase.select(testSetDependencies.cat(testCaseDependencies)).asXdmValue();
151
152 Optional<XdmNode> lastSpecValue = allDependencies.select(path("spec", "@value")).last().asOptionalNode();
153 String specAtt = lastSpecValue.isPresent() ? lastSpecValue.get().getStringValue() : "XSLT10+";
154
155 final Environment env = getEnvironment(testCase, xpath);
156 if (env == null) {
157 resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
158 notrun++;
159 return;
160 }
161
162 for (XdmNode dep : allDependencies.select(child(isElement())).asListOfNodes()) {
163 if (!ensureDependencySatisfied(dep, env)) {
164 notrun++;
165 String type = dep.getNodeName().getLocalName();
166 String value = dep.attribute("value");
167 if (value == null) {
168 value = type;
169 } else {
170 value = type + ":" + value;
171 }
172 if ("false".equals(dep.attribute("satisfied"))) {
173 value = "!" + value;
174 }
175 String message = "dependency not satisfied: " + value;
176 if (value.startsWith("feature:")) {
177 message = "requires optional " + value;
178 }
179 resultsDoc.writeTestcaseElement(testName, "n/a", message);
180 return;
181 }
182 }
183
184 if (env.failedToBuild) {
185 resultsDoc.writeTestcaseElement(testName, "fail", "unable to build environment");
186 noteFailure(testSetName, testName);
187 return;
188 }
189
190 if (!env.usable) {
191 resultsDoc.writeTestcaseElement(testName, "n/a", "environment dependencies not satisfied");
192 notrun++;
193 return;
194 }
195
196
197 if (testName.contains("environment-variable")) {
198 EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
199 public Set<String> getAvailableEnvironmentVariables() {
200 Set<String> strings = new HashSet<>();
201 strings.add("QTTEST");
202 strings.add("QTTEST2");
203 strings.add("QTTESTEMPTY");
204 return strings;
205 }
206
207 public String getEnvironmentVariable(String name) {
208 switch (name) {
209 case "QTTEST":
210 return "42";
211 case "QTTEST2":
212 return "other";
213 case "QTTESTEMPTY":
214 return "";
215 default:
216 return null;
217 }
218 }
219 };
220 env.processor.setConfigurationProperty(Feature.ENVIRONMENT_VARIABLE_RESOLVER, resolver);
221 }
222
223 if (testName.contains("load-xquery-module")) {
224 env.processor.getUnderlyingConfiguration().setModuleURIResolver(
225 (moduleURI, baseURI, locations) -> {
226 File file = queryModules.get(moduleURI);
227 if (file == null) {
228 return null;
229 }
230 try {
231 StreamSource ss = new StreamSource(new FileInputStream(file), baseURI);
232 return new StreamSource[]{ss};
233 } catch (FileNotFoundException e) {
234 throw new XPathException(e);
235 }
236 });
237 }
238 XdmNode testInput = testCase.select(child("test")).asNode();
239 Optional<XdmNode> stylesheet = testInput.select(
240 child("stylesheet").where(not(attributeEq("role", "secondary")))).asOptionalNode();
241 Optional<XdmNode> postureAndSweep = testInput.select(
242 child("posture-and-sweep")).asOptionalNode();
243 Optional<XdmNode> principalPackage = testInput.select(
244 child("package").where(attributeEq("role", "principal"))).asOptionalNode();
245 List<XdmNode> usedPackages = testInput.select(
246 child("package").where(attributeEq("role", "secondary"))).asList();
247
248 XsltExecutable sheet = env.xsltExecutable;
249 ErrorCollector collector = new ErrorCollector();
250 if (quiet) {
251 collector.setLogger(new Logger() {
252 @Override
253 public void println(String message, int severity) {
254 // no action
255 }
256
257 @Override
258 public StreamResult asStreamResult() {
259 return null;
260 }
261 });
262 }
263 String xsltLanguageVersion = specAtt.contains("XSLT30") || specAtt.contains("XSLT20+") ? "3.0" : "2.0";
264
265 if (postureAndSweep.isPresent()) {
266 if (runPostureAndSweepTests) {
267 runStreamabilityTests(xpath, testCase);
268 }
269 return;
270 }
271
272 boolean strictStreamability = testCase.select(
273 child("result").then(descendant("error"))
274 .where(attributeEq("code", "XTSE3430"))).exists();
275 if (strictStreamability) {
276 env.processor.setConfigurationProperty(Feature.STRICT_STREAMABILITY, true);
277 env.resetActions.add(new Environment.ResetAction() {
278 @Override
279 public void reset(Environment env) {
280 env.processor.setConfigurationProperty(Feature.STRICT_STREAMABILITY, false);
281 }
282 });
283 }
284
285 Predicate<XdmItem> isStaticError = item -> item.getStringValue().startsWith("XTSE");
286 boolean staticError = testCase.select(
287 path("result", "//", "error", "@code").where(isStaticError)).exists();
288 //boolean staticError = xpath.evaluate("result//error[starts-with(@code, 'XTSE')]", testCase).size() > 0;
289 if (staticError && jitFlag) {
290 env.xsltCompiler.setJustInTimeCompilation(false);
291 env.resetActions.add(new Environment.ResetAction() {
292 @Override
293 public void reset(Environment env) {
294 env.xsltCompiler.setJustInTimeCompilation(true);
295 }
296 });
297 }
298
299 if (stylesheet.isPresent()) {
300 String fileName = stylesheet.get().attribute("file");
301
302 Source styleSource = new StreamSource(testCase.getBaseURI().resolve(fileName).toString());
303
304 XsltCompiler compiler = env.xsltCompiler;
305 compiler.setErrorListener(collector);
306 initPatternOptimization(compiler);
307 compiler.clearParameters();
308 //compiler.getUnderlyingCompilerInfo().setRuleOptimization(optimizeRules);
309 //compiler.getUnderlyingCompilerInfo().setRulePreconditions(preconditionsRules);
310 prepareForSQL(compiler.getProcessor());
311
312 List<XdmNode> params = testInput.select(child("param").where(isTrue("static"))).asListOfNodes();
313 for (XdmNode param : params) {
314 String name = param.attribute("name");
315 String select = param.attribute("select");
316 XdmValue value;
317 try {
318 value = xpath.evaluate(select, null);
319 } catch (SaxonApiException e) {
320 System.err.println("*** Error evaluating parameter " + name + ": " + e.getMessage());
321 throw e;
322 }
323 compiler.setParameter(new QName(name), value);
324 }
325 for (XdmNode pack : usedPackages) {
326 String fileName2 = pack.attribute("file");
327 Source styleSource2 = new StreamSource(testCase.getBaseURI().resolve(fileName2).toString());
328 XsltPackage xpack = compiler.compilePackage(styleSource2);
329 xpack = exportImportPackage(testName, testSetName, outcome, compiler, xpack, collector);
330 compiler.importPackage(xpack);
331 // Following needed for dynamic loading of packages using fn:transform()
332 env.processor.getUnderlyingConfiguration().getDefaultXsltCompilerInfo().getPackageLibrary().addPackage(xpack.getUnderlyingPreparedPackage());
333 }
334 sheet = exportImport(testName, testSetName, outcome, compiler, sheet, collector, styleSource);
335
336
337 String optimizationAssertion = optimizationAssertions.get(testName);
338 if (optimizationAssertion != null && sheet != null) {
339 try {
340 assertOptimization(sheet, optimizationAssertion);
341 System.err.println("Optimization OK: " + optimizationAssertion);
342 } catch (SaxonApiException e) {
343 System.err.println("Optimization assertion failed: " + optimizationAssertion);
344 }
345 }
346 } else if (principalPackage.isPresent()) {
347 XsltCompiler compiler = env.xsltCompiler;
348 //compiler.setXsltLanguageVersion(xsltLanguageVersion);
349 compiler.setErrorListener(collector);
350 compiler.clearParameters();
351 testInput.select(child("param").where(isTrue("static"))).forEach(param -> {
352 String name = param.attribute("name");
353 String select = param.attribute("select");
354 XdmValue value;
355 try {
356 value = xpath.evaluate(select, null);
357 } catch (SaxonApiException e) {
358 System.err.println("*** Error evaluating parameter " + name + ": " + e.getMessage());
359 throw new SaxonApiUncheckedException(e);
360 }
361 compiler.setParameter(new QName(name), value);
362 });
363
364 for (XdmNode pack : usedPackages) {
365 String fileName = pack.attribute("file");
366 Source styleSource = new StreamSource(testCase.getBaseURI().resolve(fileName).toString());
367 XsltPackage xpack = compiler.compilePackage(styleSource);
368 compiler.importPackage(xpack);
369 }
370 String fileName = principalPackage.get().attribute("file");
371 Source styleSource = new StreamSource(testCase.getBaseURI().resolve(fileName).toString());
372
373 try {
374 XsltPackage xpack = compiler.compilePackage(styleSource);
375 sheet = xpack.link();
376 } catch (SaxonApiException err) {
377 System.err.println(err.getMessage());
378 outcome.setException(err);
379 outcome.setErrorsReported(collector.getErrorCodes());
380 } catch (Exception err) {
381 err.printStackTrace();
382 System.err.println(err.getMessage());
383 outcome.setException(new SaxonApiException(err));
384 outcome.setErrorsReported(collector.getErrorCodes());
385 }
386
387 sheet = exportImport(testName, testSetName, outcome, compiler, sheet, collector, styleSource);
388
389 }
390 if (runWithNodeJS && !outcome.isException()) {
391 /* TODO - add case where expecting a static error but compiled OK */
392 URI r = new File(resultsDir).toURI();
393 if (env.exportedStylesheet != null) {
394 URI s = env.exportedStylesheet.toURI();
395 s = r.relativize(s);
396 resultsDoc.writeTestcaseElement(testName, "deferred", s.toString());
397 } else {
398 resultsDoc.writeTestcaseElement(testName, "deferred", "export/" + testSetName + "/" + testName + ".sef.json");
399 }
400 return;
401 }
402
403 XdmValue initialMatchSelection = null;
404 Optional<XdmNode> initialMode = testInput.select(child("initial-mode")).asOptionalNode();
405 Optional<XdmNode> initialFunction = testInput.select(child("initial-function")).asOptionalNode();
406 Optional<XdmNode> initialTemplate = testInput.select(child("initial-template")).asOptionalNode();
407
408 QName initialModeName = null;
409 if (initialMode.isPresent()) {
410 initialModeName = getQNameAttribute(xpath, initialMode.get(), attribute("name"));
411 String select = initialMode.get().attribute("select");
412 if (select != null) {
413 initialMatchSelection = env.xpathCompiler.evaluate(select, null);
414 if (runWithJS) {
415 resultsDoc.writeTestcaseElement(testName, "n/a", "Test driver limitation: cannot set initial match selection");
416 notrun++;
417 return;
418 }
419 }
420 }
421
422 QName initialTemplateName = getQNameAttribute(xpath, testInput, path("initial-template", "@name"));
423 QName initialFunctionName = getQNameAttribute(xpath, testInput, path("initial-function", "@name"));
424
425 if (runWithJS && !outcome.isException()) {
426 Optional<String> wellFormed = testInput.select(path("output", "@well-formed")).asOptionalString();
427 if (wellFormed.equals(Optional.of("no"))) {
428 outcome.getPrincipalResultDoc().wellFormed = false;
429 }
430
431 clearGlobalParameters();
432 Map<QName, XdmValue> caseGlobalParams = getNamedParameters(xpath, testInput, false, false);
433 for (Map.Entry<QName, XdmValue> entry : caseGlobalParams.entrySet()) {
434 setGlobalParameter(entry.getKey(), entry.getValue());
435 }
436 if (initialFunctionName != null) {
437 clearInitialFunctionArguments();
438 XdmNode iniFunc = testInput.select(child("initial-function")).asNode();
439 XdmValue[] args = getParameters(xpath, iniFunc);
440 for (XdmValue val : args) {
441 addInitialFunctionArgument(val);
442 }
443 }
444 URI baseOut = new File(resultsDir + "/results/output.xml").toURI();
445 try {
446 outcome.setBaseOutputUri(baseOut.toASCIIString());
447 runJSTransform(env, outcome, initialTemplateName, initialModeName, initialFunctionName, baseOut);
448 } catch (StackOverflowError e) {
449 notrun++;
450 resultsDoc.writeTestcaseElement(testName, "tooBig", "Stack Overflow");
451 return;
452 }
453 if ("*notJS*".equals(outcome.getComment())) {
454 return;
455 }
456 }
457
458 if (sheet != null && !runWithJS) {
459 XdmItem contextItem = env.contextItem;
460
461 Optional<String> outputUri = testInput.select(path("output", "@file")).asOptionalString();
462
463 URI baseOut = new File(resultsDir + "/results/output.xml").toURI();
464 String baseOutputURI = new File(resultsDir + "/results/output.xml").toURI().toString();
465 if (outputUri.isPresent() && !outputUri.get().equals("")) {
466 baseOutputURI = baseOut.resolve(outputUri.get()).toString();
467 }
468 outcome.setBaseOutputUri(baseOutputURI);
469
470 boolean failure;
471 try {
472 if (useXslt30Transformer) {
473 failure = runWithXslt30Transformer(testCase, xpath, outcome, testName,
474 testSetName, env, testInput, sheet, collector,
475 xsltLanguageVersion, contextItem, initialMode.orElse(null),
476 initialFunction.orElse(null), initialTemplate.orElse(null), initialModeName,
477 initialMatchSelection, initialTemplateName, baseOutputURI);
478 } else {
479 failure = runWithXsltTransformer(xpath, outcome, testName, testSetName, env, testInput,
480 sheet, collector, contextItem, initialMode.orElse(null), initialModeName,
481 initialTemplateName, baseOutputURI);
482 }
483 if (failure) {
484 return;
485 }
486 } catch (Throwable e) {
487 e.printStackTrace();
488 // and continue
489 }
490 }
491
492 for (Environment.ResetAction action : env.resetActions) {
493 action.reset(env);
494 }
495 env.resetActions.clear();
496
497 Optional<String> earlyExit = testCase.select(
498 path(child("result"), attribute("early-exit-possible"))).asOptionalString();
499 boolean expectEarlyExit = earlyExit.equals(Optional.of("true"));
500 if (expectEarlyExit != collector.isMadeEarlyExit()) {
501 outcome.setComment(expectEarlyExit ? "Failed to make early exit" : "Unexpected early exit");
502 }
503
504 Optional<XdmNode> assertion = testCase.select(
505 path(child("result"), child().where(isElement()))).asOptionalNode();
506 if (!assertion.isPresent()) {
507 noteFailure(testSetName, testName);
508 resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
509 return;
510 }
511 XPathCompiler assertionXPath = env.processor.newXPathCompiler();
512 assertionXPath.setSchemaAware(env.processor.isSchemaAware());
513 assertionXPath.setBaseURI(assertion.get().getBaseURI());
514 copySchemaNamespaces(env, assertionXPath); // ensure environment has schema namespaces
515 boolean success = outcome.testAssertion(assertion.get(), outcome, outcome.getPrincipalResultDoc(), assertionXPath, xpath, debug);
516 if (success) {
517 successes++;
518 resultsDoc.writeTestcaseElement(testName, "pass", outcome.getComment());
519 } else {
520 if (outcome.getWrongErrorMessage() != null) {
521 outcome.setComment(outcome.getWrongErrorMessage());
522 wrongErrorResults++;
523 successes++;
524 resultsDoc.writeTestcaseElement(testName, "wrongError", outcome.getComment());
525 } else {
526 noteFailure(testSetName, testName);
527 // MHK: Nov 2015 - temporary diagnostics
528 if (outcome.getException() != null && outcome.getComment() == null) {
529 outcome.setComment(outcome.getException().getMessage());
530 }
531 resultsDoc.writeTestcaseElement(testName, "fail", outcome.getComment());
532 }
533 }
534 }
535
536 public void runJSTransform(Environment env, TestOutcome outcome, QName initialTemplateName,
537 QName initialModeName, QName initialFunctionName,
538 URI baseOutputURI) {
539 // exists to be overridden
540 }
541
542 private boolean runWithXsltTransformer(XPathCompiler xpath, final TestOutcome outcome, String testName,
543 String testSetName, Environment env, XdmNode testInput,
544 XsltExecutable sheet, ErrorCollector collector,
545 XdmItem contextItem, XdmNode initialMode, QName initialModeName,
546 QName initialTemplateName, String baseOutputURI) {
547 try {
548 XsltTransformer transformer = sheet.load();
549 transformer.setURIResolver(env);
550 transformer.setBaseOutputURI(baseOutputURI);
551 if (env.unparsedTextResolver != null) {
552 transformer.getUnderlyingController().setUnparsedTextURIResolver(env.unparsedTextResolver);
553 }
554 if (initialTemplateName != null) {
555 transformer.setInitialTemplate(initialTemplateName);
556 }
557 if (initialMode != null) {
558 try {
559 transformer.setInitialMode(initialModeName);
560 } catch (IllegalArgumentException e) {
561 if (e.getCause() instanceof XPathException) {
562 collector.fatalError((XPathException) e.getCause());
563 throw new SaxonApiException(e.getCause());
564 } else {
565 throw e;
566 }
567 }
568 }
569 testInput.select(child("param").where(not(isTrue("static")))).forEach(param -> {
570 String name = param.attribute("name");
571 String select = param.attribute("select");
572 XdmValue value;
573 try {
574 value = xpath.evaluate(select, null);
575 } catch (SaxonApiException e) {
576 System.err.println("*** Error evaluating parameter " + name + ": " + e.getMessage());
577 throw new SaxonApiUncheckedException(e);
578 }
579 transformer.setParameter(new QName(name), value);
580 setGlobalParameter(new QName(name), value);
581 });
582 if (contextItem != null) {
583 transformer.setInitialContextNode((XdmNode) contextItem);
584 }
585 if (env.streamedFile != null) {
586 transformer.setSource(new StreamSource(env.streamedFile));
587 } else if (env.streamedContent != null) {
588 transformer.setSource(new StreamSource(new StringReader(env.streamedContent), "inlineDoc"));
589 }
590 for (QName varName : env.params.keySet()) {
591 transformer.setParameter(varName, env.params.get(varName));
592 setGlobalParameter(varName, env.params.get(varName));
593 }
594 transformer.setErrorListener(collector);
595 /* if (outputUri != null) {
596 transformer.setBaseOutputURI(testInput.getBaseURI().resolve(outputUri).toString());
597 } else {
598 transformer.setBaseOutputURI(new File(resultsDir + "/results/output.xml").toURI().toString());
599 }*/
600 transformer.setMessageListener((content, terminate, locator) -> {
601 outcome.addXslMessage(content);
602 System.err.println(content.getStringValue());
603 });
604
605
606 // Run the transformation twice, once for serialized results, once for a tree.
607 // TODO: we could be smarter about this and capture both
608
609 // run with serialization
610 StringWriter sw = new StringWriter();
611 Serializer serializer = env.processor.newSerializer(sw);
612 transformer.setDestination(serializer);
613 transformer.getUnderlyingController().setOutputURIResolver(
614 new OutputResolver(env.processor, outcome, true));
615 transformer.transform();
616 outcome.setPrincipalSerializedResult(sw.toString());
617 if (saveResults) {
618 // currently, only save the principal result file
619 saveResultsToFile(sw.toString(),
620 new File(resultsDir + "/results/" + testSetName + "/" + testName + ".out"));
621 Map<URI, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.getSecondaryResultDocuments();
622 for (Map.Entry<URI, TestOutcome.SingleResultDoc> entry : xslResultDocuments.entrySet()) {
623 URI key = entry.getKey();
624 if (key != null) {
625 String path = key.getPath();
626 String serialization = outcome.serialize(env.processor, entry.getValue());
627 saveResultsToFile(serialization, new File(path));
628 }
629 }
630 }
631
632 // run without serialization
633 if (env.streamedContent != null) {
634 transformer.setSource(new StreamSource(new StringReader(env.streamedContent), "inlineDoc"));
635 }
636 XdmDestination destination = new XdmDestination();
637 destination.setTreeModel(treeModel);
638 transformer.setDestination(destination);
639 transformer.getUnderlyingController().setOutputURIResolver(
640 new OutputResolver(env.processor, outcome, false));
641 transformer.transform();
642 outcome.setPrincipalResult(destination.getXdmNode());
643 outcome.setWarningsReported(collector.getFoundWarnings());
644 //}
645 } catch (SaxonApiException err) {
646 outcome.setException(err);
647 if (collector.getErrorCodes().isEmpty()) {
648 outcome.addReportedError(err.getErrorCode().getLocalName());
649 } else {
650 outcome.setErrorsReported(collector.getErrorCodes());
651 }
652 } catch (Exception err) {
653 err.printStackTrace();
654 noteFailure(testSetName, testName);
655 resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
656 return true;
657 }
658 return false;
659 }
660
661 protected void clearGlobalParameters(){}
662
663 protected void setGlobalParameter(QName qName, XdmValue value) {
664 // For overriding in Javascript driver
665 }
666
667 protected void clearInitialFunctionArguments() {
668 }
669
670 protected void addInitialFunctionArgument(XdmValue value) {
671 // For overriding in Javascript driver
672 }
673
674 protected boolean runWithXslt30Transformer(XdmNode testCase, XPathCompiler xpath, final TestOutcome outcome,
675 String testName, String testSetName, Environment env,
676 XdmNode testInput, XsltExecutable sheet, ErrorCollector collector,
677 String xsltLanguageVersion, XdmItem contextItem, XdmNode initialMode,
678 XdmNode initialFunction,
679 XdmNode initialTemplate, QName initialModeName, XdmValue initialMatchSelection,
680 QName initialTemplateName, String baseOutputURI) {
681 try {
682 boolean assertsSerial =
683 testCase.select(path(child("result"),
684 descendant("assert-serialization")
685 .cat(descendant("assert-serialization-error"))
686 .cat(descendant("serialization-matches")))).exists();
687 boolean resultAsTree = env.outputTree;
688 boolean serializationDeclared = env.outputSerialize;
689
690 Optional<String> needsTree = testInput.select(path("output", "@tree")).asOptionalString();
691 if (needsTree.isPresent()) {
692 resultAsTree = needsTree.get().equals("yes");
693 }
694
695 testInput.select(path("output", "@result-var"))
696 .forEach(att -> outcome.setResultVar(att.getStringValue()));
697
698 Optional<String> serializeAtt = testInput.select(path("output", "@serialize")).asOptionalString();
699 if (serializeAtt.isPresent()) {
700 serializationDeclared = serializeAtt.equals(Optional.of("yes"));
701 }
702 boolean resultSerialized = serializationDeclared || assertsSerial;
703
704 // if (assertsSerial) {
705 // String comment = outcome.getComment();
706 // comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* ");
707 // outcome.setComment(comment);
708 // }
709
710
711 Xslt30Transformer transformer = sheet.load30();
712 transformer.setURIResolver(env);
713 if (env.unparsedTextResolver != null) {
714 transformer.getUnderlyingController().setUnparsedTextURIResolver(env.unparsedTextResolver);
715 }
716 if (tracing) {
717 transformer.setTraceListener(new XSLTTraceListener());
718 }
719
720 Map<QName, XdmValue> caseGlobalParams = getNamedParameters(xpath, testInput, false, false);
721 //Map<QName, XdmValue> caseStaticParams = getNamedParameters(xpath, testInput, true, false);
722 Map<QName, XdmValue> globalParams = new HashMap<>(env.params);
723 //globalParams.putAll(caseStaticParams);
724 globalParams.putAll(caseGlobalParams); // has to be this way to ensure test-local overrides global
725 transformer.setStylesheetParameters(globalParams);
726
727 if (contextItem != null) {
728 transformer.setGlobalContextItem(contextItem);
729 }
730
731 transformer.setErrorListener(collector);
732
733 transformer.setBaseOutputURI(baseOutputURI);
734
735 transformer.setMessageListener((content, errorCode, terminate, locator) -> {
736 outcome.addXslMessage(content);
737 System.err.println(content.getStringValue());
738 });
739
740 XdmValue result = null;
741
742 StringWriter sw = new StringWriter();
743
744 Serializer serializer = env.processor.newSerializer(sw);
745 //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
746
747
748 XsltController controller = transformer.getUnderlyingController();
749
750 Destination dest = null;
751 if (resultAsTree && !resultSerialized) {
752 // If we want non-serialized, we need to accumulate any result documents as trees too
753 // But we can't do both, so serializing takes precedence.
754 transformer.setResultDocumentHandler(
755 new ResultDocHandler(env.processor, outcome, baseOutputURI, false));
756 dest = new XdmDestination();
757 ((XdmDestination)dest).setTreeModel(treeModel);
758 } else {
759 transformer.setResultDocumentHandler(
760 new ResultDocHandler(env.processor, outcome, baseOutputURI, true));
761 }
762 if (resultSerialized) {
763 dest = serializer;
764 }
765
766 Source src = null;
767 if (env.streamedFile != null) {
768 src = new StreamSource(env.streamedFile);
769 } else if (env.streamedContent != null) {
770 src = new StreamSource(new StringReader(env.streamedContent), "inlineDoc");
771 } else if (initialTemplate == null && contextItem != null) {
772 src = ((XdmNode) contextItem).getUnderlyingNode();
773 }
774 if (src != null && !"skip".equals(env.streamedInputValidation)) {
775 Processor processor = sheet.getProcessor();
776 SchemaValidator validator = processor.getSchemaManager().newSchemaValidator();
777 src = validator.asSource(src);
778 }
779
780 if (src == null && initialFunction == null && initialTemplateName == null && initialModeName == null) {
781 initialTemplateName = new QName("xsl", NamespaceConstant.XSLT, "initial-template");
782 }
783
784 try {
785 if (initialModeName != null) {
786 transformer.setInitialMode(initialModeName);
787 } else {
788 controller.getInitialMode(); /// has the side effect of setting to the unnamed
789 }
790 } catch (IllegalArgumentException e) {
791 if (e.getCause() instanceof XPathException) {
792 collector.fatalError((XPathException) e.getCause());
793 throw new SaxonApiException(e.getCause());
794 } else {
795 throw e;
796 }
797 }
798
799 if (initialMode != null || initialTemplate != null) {
800 XdmNode init = initialMode == null ? initialTemplate : initialMode;
801 Map<QName, XdmValue> params = getNamedParameters(xpath, init, false, false);
802 Map<QName, XdmValue> tunnelledParams = getNamedParameters(xpath, init, false, true);
803 if (xsltLanguageVersion.equals("2.0")) {
804 if (!(params.isEmpty() && tunnelledParams.isEmpty())) {
805 System.err.println("*** Initial template parameters ignored for XSLT 2.0");
806 }
807 } else {
808 transformer.setInitialTemplateParameters(params, false);
809 transformer.setInitialTemplateParameters(tunnelledParams, true);
810 }
811 }
812
813 if (initialTemplateName != null) {
814 transformer.setGlobalContextItem(contextItem);
815 if (dest == null) {
816 result = transformer.callTemplate(initialTemplateName);
817 } else {
818 transformer.callTemplate(initialTemplateName, dest);
819 }
820 } else if (initialFunction != null) {
821 QName name = getQNameAttribute(xpath, initialFunction, attribute("name"));
822 XdmValue[] params = getParameters(xpath, initialFunction);
823 if (dest == null) {
824 result = transformer.callFunction(name, params);
825 } else {
826 transformer.callFunction(name, params, dest);
827 }
828 } else if (initialMatchSelection != null) {
829 if (dest == null) {
830 result = transformer.applyTemplates(initialMatchSelection);
831 } else {
832 transformer.applyTemplates(initialMatchSelection, dest);
833 }
834 } else {
835 if (dest == null) {
836 result = transformer.applyTemplates(src);
837 } else {
838 transformer.applyTemplates(src, dest);
839 }
840 }
841
842 outcome.setWarningsReported(collector.getFoundWarnings());
843 if (resultAsTree && !resultSerialized) {
844 result = ((XdmDestination) dest).getXdmNode();
845 }
846 // Don't overwrite the principal result if it already exists: this happens
847 // when an xsl:result-document with empty or absent href has been executed
848 if (resultSerialized && outcome.getPrincipalSerializedResult() == null) {
849 outcome.setPrincipalSerializedResult(sw.toString());
850 }
851 if (outcome.getPrincipalResult() == null) {
852 outcome.setPrincipalResult(result);
853 }
854
855 if (saveResults) {
856 String s = sw.toString();
857 // If a transform result is entirely xsl:result-document, then result will be null
858 if (!resultSerialized && result != null) {
859 StringWriter sw2 = new StringWriter();
860 Serializer se = env.processor.newSerializer(sw2);
861 se.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
862 env.processor.writeXdmValue(result, se);
863 se.close();
864 s = sw2.toString();
865 }
866 // currently, only save the principal result file in the result directory
867 saveResultsToFile(s,
868 new File(resultsDir + "/results/" + testSetName + "/" + testName + ".out"));
869 Map<URI, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.getSecondaryResultDocuments();
870 for (Map.Entry<URI, TestOutcome.SingleResultDoc> entry : xslResultDocuments.entrySet()) {
871 URI key = entry.getKey();
872 String path = key.getPath();
873 String serialization = outcome.serialize(env.processor, entry.getValue());
874 saveResultsToFile(serialization, new File(path));
875 }
876 }
877 } catch (SaxonApiException err) {
878 if (err.getCause() instanceof XPathException &&
879 !((XPathException) err.getCause()).hasBeenReported()) {
880 System.err.println("Thrown exception " + ((XPathException) err.getCause()).getErrorCodeLocalPart() +
881 ": " + err.getCause().getMessage());
882 }
883 outcome.setException(err);
884 if (collector.getErrorCodes().isEmpty()) {
885 if (err.getErrorCode() == null) {
886 outcome.addReportedError("Error_with_no_error_code");
887 } else {
888 outcome.addReportedError(err.getErrorCode().getLocalName());
889 }
890 } else {
891 outcome.setErrorsReported(collector.getErrorCodes());
892 }
893 } catch (Exception err) {
894 err.printStackTrace();
895 noteFailure(testSetName, testName);
896 resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
897 return true;
898 }
899 return false;
900 }
901
902 protected void initPatternOptimization(XsltCompiler compiler) {
903 }
904
905 protected XsltExecutable exportImport(String testName, String testSetName, TestOutcome outcome, XsltCompiler compiler, XsltExecutable sheet, ErrorCollector collector, Source styleSource) {
906 try {
907 if (export && isExportable(testName)) {
908 sheet = exportStylesheet(testName, testSetName, compiler, sheet, styleSource);
909 } else if (sheet == null) {
910 sheet = compiler.compile(styleSource);
911 }
912 } catch (SaxonApiException err) {
913 outcome.setException(err);
914 if (err.getErrorCode() != null) {
915 collector.getErrorCodes().add(err.getErrorCode().getLocalName());
916 }
917 outcome.setErrorsReported(collector.getErrorCodes());
918 } catch (Exception err) {
919 err.printStackTrace();
920 System.err.println(err.getMessage());
921 outcome.setException(new SaxonApiException(err));
922 outcome.setErrorsReported(collector.getErrorCodes());
923 }
924 return sheet;
925 }
926
927 private boolean isExportable(String testName) {
928 // there are so few exceptions that we hard-code them
929 return !(testName.equals("load-xquery-module-004") // static variable calling fn:load-xquery-module
930 || testName.equals("transform-004")); // static variable calling fn:transform
931 }
932
933 protected XsltExecutable exportStylesheet(String testName, String testSetName, XsltCompiler compiler, XsltExecutable sheet, Source styleSource) throws SaxonApiException {
934 try {
935 driverProc.setConfigurationProperty(Feature.LINE_NUMBERING, true);
936 File exportFile = new File(resultsDir + "/export/" + testSetName + "/" + testName + ".sef");
937 if (xxCompilerLocation != null && !compiler.isSchemaAware()) {
938 if (xxCompiler == null) {
939 XdmMap options = new XdmMap();
940 boolean assertionsEnabled = compiler.isAssertionsEnabled();
941 options = options.put(new XdmAtomicValue("enable-assertions"), new XdmAtomicValue(assertionsEnabled));
942
943
944 XsltCompiler c = driverProc.newXsltCompiler();
945 c.setAssertionsEnabled(true);
946 c.setParameter(new QName("FAST_JAVA_XPATH"), new XdmAtomicValue(true));
947 c.setParameter(new QName("options"), options);
948 c.setFastCompilation(true); // TODO: temporary
949 xxCompiler = c.compile(new StreamSource(new File(xxCompilerLocation)));
950 }
951 Xslt30Transformer transformer = xxCompiler.load30();
952 // Copy over any static parameters that have been set
953 GlobalParameterSet staticParams = compiler.getUnderlyingCompilerInfo().getParameters();
954 XdmMap staticParamMap = new XdmMap();
955 for (StructuredQName name : staticParams.getKeys()) {
956 GroundedValue<?> value = staticParams.get(name);
957 staticParamMap = staticParamMap.put(new XdmAtomicValue(new QName(name)), XdmValue.wrap(value));
958 }
959 Map<QName, XdmValue> transformParams = new HashMap<>();
960 transformParams.put(new QName("staticParameters"), staticParamMap);
961 transformer.setStylesheetParameters(transformParams);
962 transformer.setAssertionsEnabled(true);
963 transformer.setInitialMode(new QName("compile-complete"));
964 List<QName> reportedErrors = new ArrayList<>();
965 transformer.setMessageListener(new MessageListener2() {
966 @Override
967 public void message(XdmNode content, QName errorCode, boolean terminate, SourceLocator locator) {
968 System.err.println(content);
969 if (!errorCode.getLocalName().equals("XTMM9000")) {
970 reportedErrors.add(errorCode);
971 }
972 }
973 });
974 Serializer serializer = driverProc.newSerializer(exportFile);
975 transformer.applyTemplates(styleSource, serializer);
976 if (!reportedErrors.isEmpty()) {
977 throw new SaxonApiException(new XPathException(
978 "Stylesheet compilation failed", reportedErrors.get(0).getLocalName()));
979 }
980 } else {
981 XsltPackage compiledPack = compiler.compilePackage(styleSource);
982 compiledPack.save(exportFile);
983 }
984 sheet = reloadExportedStylesheet(compiler, exportFile);
985 } catch (SaxonApiException e) {
986 try {
987 compiler.getErrorListener().fatalError(XPathException.makeXPathException(e));
988 } catch (TransformerException te) {
989 assert false;
990 }
991 //System.err.println(e.getMessage());
992 //e.printStackTrace(); //temporary, for debugging
993 throw e;
994 }
995 return sheet;
996 }
997
998 protected XsltExecutable reloadExportedStylesheet(XsltCompiler compiler, File exportFile) throws SaxonApiException {
999 return compiler.loadExecutablePackage(exportFile.toURI());
1000 }
1001
1002 private XsltPackage exportImportPackage(String testName, String testSetName, TestOutcome outcome, XsltCompiler compiler, XsltPackage pack, ErrorCollector collector) {
1003 try {
1004 if (export) {
1005 try {
1006 File exportFile = new File(resultsDir + "/export/" + testSetName + "/" + testName + ".base.sef");
1007 pack.save(exportFile);
1008 return compiler.loadLibraryPackage(exportFile.toURI());
1009 } catch (SaxonApiException e) {
1010 System.err.println(e.getMessage());
1011 //e.printStackTrace(); //temporary, for debugging
1012 throw e;
1013 }
1014 } else {
1015 return pack;
1016 }
1017 } catch (SaxonApiException err) {
1018 outcome.setException(err);
1019 if (err.getErrorCode() != null) {
1020 collector.getErrorCodes().add(err.getErrorCode().getLocalName());
1021 }
1022 outcome.setErrorsReported(collector.getErrorCodes());
1023 } catch (Exception err) {
1024 err.printStackTrace();
1025 System.err.println(err.getMessage());
1026 outcome.setException(new SaxonApiException(err));
1027 outcome.setErrorsReported(collector.getErrorCodes());
1028 }
1029 return pack;
1030 }
1031
1032 /**
1033 * Run streamability tests
1034 */
1035
1036 public void runStreamabilityTests(XPathCompiler xpc, XdmNode testCase) {
1037 // no action for Saxon-HE - ignore the test
1038 }
1039
1040 /**
1041 * Return a set of named parameters as a map
1042 *
1043 * @param xpath The XPath compiler to use
1044 * @param node The node to search for <param> children
1045 * @param getStatic Whether to collect static or non-static sets
1046 * @param tunnel Whether to collect tunnelled or non-tunnelled sets
1047 * @return Map of the evaluated parameters, keyed by QName
1048 * @throws SaxonApiException if things go wrong
1049 */
1050 protected Map<QName, XdmValue> getNamedParameters(XPathCompiler xpath, XdmNode node, boolean getStatic, boolean tunnel) throws SaxonApiException {
1051 Map<QName, XdmValue> params = new HashMap<>();
1052 int i = 1;
1053 Predicate<? super XdmNode> staticTest = isTrue("static");
1054 if (!getStatic) {
1055 staticTest = not(staticTest);
1056 }
1057 List<XdmNode> paramElements = node.select(child("param").where(staticTest)).asListOfNodes();
1058 for (XdmNode param : paramElements) {
1059 QName name = getQNameAttribute(xpath, param, attribute("name"));
1060 String select = param.attribute("select");
1061 String tunnelled = param.attribute("tunnel");
1062 QName as = getQNameAttribute(xpath, param, attribute("as"));
1063 // TODO: it won't always be a QName, could be a sequence type
1064 boolean required = tunnel == (tunnelled != null && tunnelled.equals("yes"));
1065 XdmValue value;
1066 if (name == null) {
1067 System.err.println("*** No name for parameter " + i + " in initial-template");
1068 throw new SaxonApiException("*** No name for parameter " + i + " in initial-template");
1069 }
1070 try {
1071 value = xpath.evaluate(select, null);
1072 i++;
1073 } catch (SaxonApiException e) {
1074 System.err.println("*** Error evaluating parameter " + name + " in initial-template : " + e.getMessage());
1075 throw e;
1076 }
1077 if (as != null) {
1078 value = new XdmAtomicValue(((AtomicValue) value.getUnderlyingValue()).getStringValue(),
1079 new ItemTypeFactory(xpath.getProcessor()).getAtomicType(as));
1080 }
1081 if (required) {
1082 params.put(name, value);
1083 }
1084 }
1085 return params;
1086 }
1087
1088 /**
1089 * Return a set of unnamed parameters as an array
1090 *
1091 * @param xpath The XPath compiler to use
1092 * @param node The node to search for <param> children
1093 * @return Array of the parameter values
1094 */
1095 protected XdmValue[] getParameters(XPathCompiler xpath, XdmNode node) {
1096 ArrayList<XdmValue> params = new ArrayList<>();
1097
1098 node.select(child("param").where(not(isTrue("static")))).forEach(param -> {
1099 String select = param.attribute("select");
1100 XdmValue value;
1101 try {
1102 value = xpath.evaluate(select, null);
1103 } catch (SaxonApiException e) {
1104 System.err.println("*** Error evaluating parameter " + params.size() + " in initial-function : " + e.getMessage());
1105 throw new SaxonApiUncheckedException(e);
1106 }
1107 params.add(value);
1108 });
1109 return params.toArray(new XdmValue[0]);
1110 }
1111
1112 @SuppressWarnings({"ResultOfMethodCallIgnored"})
1113 protected void saveResultsToFile(String content, File file) {
1114 try {
1115 Query.createFileIfNecessary(file);
1116 FileWriter writer = new FileWriter(file);
1117 writer.append(content);
1118 writer.close();
1119 } catch (IOException e) {
1120 System.err.println("*** Failed to save results to " + file.getAbsolutePath());
1121 e.printStackTrace();
1122 }
1123 }
1124
1125 protected void assertOptimization(XsltExecutable stylesheet, String assertion) throws SaxonApiException {
1126
1127 XdmDestination builder = new XdmDestination();
1128 stylesheet.explain(builder);
1129 builder.close();
1130 XdmNode expressionTree = builder.getXdmNode();
1131 XPathCompiler xpe = stylesheet.getProcessor().newXPathCompiler();
1132 XPathSelector exp = xpe.compile(assertion).load();
1133 exp.setContextItem(expressionTree);
1134 XdmAtomicValue bv = (XdmAtomicValue) exp.evaluateSingle();
1135 if (bv == null || !bv.getBooleanValue()) {
1136 println("** Optimization assertion failed");
1137 println(expressionTree.toString());
1138 throw new SaxonApiException("Expected optimization not performed");
1139 }
1140
1141 }
1142
1143 // Dependencies which are always satisfied in Saxon. (Note, this doesn't necessarily
1144 // mean that we support all possible values for the dependency, only that we support
1145 // all the values that actually appear in the test suite as it exists today.)
1146
1147 // The string in question is either a feature name, or it takes the form "feature/value"
1148 // where feature is the feature name (element name of a child of the dependencies element)
1149 // and value is the value of the "value" attribute.
1150
1151 protected Set<String> alwaysOn = new HashSet<>();
1152
1153 // Dependencies which are always satisfied in Saxon-EE but not in Saxon-HE or -PE
1154
1155 protected Set<String> needsEE = new HashSet<>();
1156
1157 // Dependencies which are always satisfied in Saxon-PE and -EE but not in Saxon-HE
1158
1159 protected Set<String> needsPE = new HashSet<>();
1160
1161 // Dependencies which are never satisfied in Saxon
1162
1163 protected Set<String> alwaysOff = new HashSet<>();
1164
1165 protected void setDependencyData() {
1166 alwaysOn.add("feature/disabling_output_escaping");
1167 alwaysOn.add("feature/serialization");
1168 alwaysOn.add("feature/namespace_axis");
1169 alwaysOn.add("feature/dtd");
1170 alwaysOn.add("feature/built_in_derived_types");
1171 alwaysOn.add("feature/remote_http");
1172 alwaysOn.add("feature/xsl-stylesheet-processing-instruction");
1173 alwaysOn.add("feature/fn-transform-XSLT");
1174 alwaysOn.add("available_documents");
1175 alwaysOn.add("ordinal_scheme_name");
1176 alwaysOn.add("default_calendar_in_date_formatting_functions");
1177 alwaysOn.add("supported_calendars_in_date_formatting_functions");
1178 alwaysOn.add("maximum_number_of_decimal_digits");
1179 alwaysOn.add("default_output_encoding");
1180 alwaysOn.add("unparsed_text_encoding");
1181 alwaysOn.add("recognize_id_as_uri_fragment");
1182 alwaysOn.add("feature/XPath_3.1");
1183 alwaysOn.add("feature/backwards_compatibility");
1184
1185 needsPE.add("feature/Saxon-PE");
1186 needsPE.add("feature/dynamic_evaluation");
1187
1188 needsEE.add("languages_for_numbering");
1189 needsEE.add("feature/streaming");
1190 needsEE.add("feature/schema_aware");
1191 needsEE.add("feature/Saxon-EE");
1192 //needsEE.add("feature/XSD_1.1");
1193
1194
1195 needsEE.add("feature/xquery_invocation");
1196 needsEE.add("feature/higher_order_functions");
1197
1198 alwaysOn.add("detect_accumulator_cycles");
1199 }
1200
1201 /**
1202 * Ensure that a dependency is satisfied, first by checking whether Saxon supports
1203 * the requested feature, and if necessary by reconfiguring Saxon so that it does;
1204 * if configuration changes are made, then resetActions should be registered to
1205 * reverse the changes when the test is complete.
1206 *
1207 * @param dependency the dependency to be checked
1208 * @param env the environment in which the test runs. The method may modify this
1209 * environment provided the changes are reversed for subsequent tests.
1210 * @return true if the test can proceed, false if the dependencies cannot be
1211 * satisfied.
1212 */
1213
1214 @Override
1215 public boolean ensureDependencySatisfied(XdmNode dependency, Environment env) {
1216 String type = dependency.getNodeName().getLocalName();
1217 String value = dependency.attribute("value");
1218 if (value == null) {
1219 value = "*";
1220 }
1221
1222 String tv = type + "/" + value;
1223
1224 boolean inverse = "false".equals(dependency.attribute("satisfied"));
1225 boolean needed = !"false".equals(dependency.attribute("satisfied"));
1226
1227 if (xxCompilerLocation != null) {
1228 if (type.equals("year_component_values") &&
1229 (value.equals("support year above 9999") ||
1230 value.equals("support negative year") ||
1231 value.equals("support year zero")
1232 )) {
1233 return false; // whether needed or not
1234 }
1235 if (unavailableInXX(type, value)) {
1236 return !needed;
1237 }
1238 }
1239
1240
1241 if (alwaysOn.contains(type) || alwaysOn.contains(tv)) {
1242 return needed;
1243 }
1244 if (alwaysOff.contains(type) || alwaysOff.contains(tv)) {
1245 return !needed;
1246 }
1247 String edition = env.processor.getSaxonEdition();
1248 if (needsPE.contains(type) || needsPE.contains(tv)) {
1249 return (edition.equals("PE") || edition.equals("EE")) == needed;
1250 }
1251 if (needsEE.contains(type) || needsEE.contains(tv)) {
1252 return edition.equals("EE") == needed;
1253 }
1254
1255 switch (type) {
1256 case "spec":
1257 boolean atLeast = value.endsWith("+");
1258 value = value.replace("+", "");
1259 String specName = spec.specAndVersion.replace("XT", "XSLT");
1260 int order = value.compareTo(specName);
1261 return atLeast ? order <= 0 : order == 0;
1262
1263 case "feature":
1264 switch (value) {
1265 case "XML_1.1": {
1266 String requiredVersion = inverse ? "1.0" : "1.1";
1267 final String oldVersion = env.processor.getXmlVersion();
1268 env.resetActions.add(new Environment.ResetAction() {
1269 @Override
1270 public void reset(Environment env) {
1271 env.processor.setXmlVersion(oldVersion);
1272 }
1273 });
1274 env.processor.setXmlVersion(requiredVersion);
1275 return true;
1276 }
1277 case "XSD_1.1": {
1278 String requiredVersion = inverse ? "1.0" : "1.1";
1279 final String oldVersion = env.processor.getConfigurationProperty(Feature.XSD_VERSION);
1280 if (!oldVersion.equals(requiredVersion)) {
1281 env.processor.setConfigurationProperty(Feature.XSD_VERSION, requiredVersion);
1282 env.resetActions.add(new Environment.ResetAction() {
1283 @Override
1284 public void reset(Environment env) {
1285 env.processor.setConfigurationProperty(Feature.XSD_VERSION, oldVersion);
1286 }
1287 });
1288 }
1289 return true;
1290 }
1291 case "higher_order_functions":
1292 return (edition.equals("PE") || edition.equals("EE")) ^ inverse;
1293 case "simple-uca-fallback":
1294 return !inverse;
1295 case "advanced-uca-fallback":
1296 return (edition.equals("PE") || edition.equals("EE")) ^ inverse;
1297 case "streaming-fallback":
1298 boolean required = !inverse;
1299 final boolean old = env.processor.getConfigurationProperty(Feature.STREAMING_FALLBACK);
1300 if (old != required) {
1301 env.processor.setConfigurationProperty(Feature.STREAMING_FALLBACK, required);
1302 env.resetActions.add(new Environment.ResetAction() {
1303 @Override
1304 public void reset(Environment env) {
1305 env.processor.setConfigurationProperty(Feature.STREAMING_FALLBACK, old);
1306 }
1307 });
1308 }
1309 return true;
1310 default:
1311 System.err.println("*** Unknown feature in HE: " + value);
1312 return env.processor.getSaxonEdition().equals("HE") ? false : null;
1313 }
1314
1315 case "default_language_for_numbering": {
1316 final String old = env.processor.getConfigurationProperty(Feature.DEFAULT_LANGUAGE);
1317 if (!value.equals(old)) {
1318 env.processor.setConfigurationProperty(Feature.DEFAULT_LANGUAGE, value);
1319 env.resetActions.add(new Environment.ResetAction() {
1320 public void reset(Environment env) {
1321 env.processor.setConfigurationProperty(Feature.DEFAULT_LANGUAGE, old);
1322 }
1323 });
1324 }
1325 return true;
1326 }
1327 case "enable_assertions": {
1328 boolean on = !inverse;
1329 final boolean old = env.xsltCompiler.isAssertionsEnabled();
1330 env.xsltCompiler.setAssertionsEnabled(on);
1331 env.resetActions.add(new Environment.ResetAction() {
1332 public void reset(Environment env) {
1333 env.xsltCompiler.setAssertionsEnabled(old);
1334 }
1335 });
1336 return true;
1337 }
1338 case "extension-function":
1339 if (value.equals("Q{http://relaxng.org/ns/structure/1.0}schema-report#1")) {
1340 try {
1341 Configuration config = env.processor.getUnderlyingConfiguration();
1342 Object sf = config.getInstance("net.cfoster.saxonjing.SchemaFunction", null);
1343 env.processor.registerExtensionFunction((ExtensionFunctionDefinition) sf);
1344 Object sfd = config.getInstance("net.cfoster.saxonjing.SchemaReportFunction", null);
1345 env.processor.registerExtensionFunction((ExtensionFunctionDefinition) sfd);
1346 return true;
1347 } catch (XPathException err) {
1348 System.err.println("Failed to load Saxon-Jing extension functions");
1349 return false;
1350 }
1351 }
1352 return false;
1353 case "year_component_values":
1354 if ("support year zero".equals(value)) {
1355 if (env != null) {
1356 env.processor.setConfigurationProperty(Feature.XSD_VERSION, inverse ? "1.0" : "1.1");
1357 return true;
1358 } else {
1359 return false;
1360 }
1361 }
1362 return !inverse;
1363 case "additional_normalization_form":
1364 if ("support FULLY-NORMALIZED".equals(value)) {
1365 return inverse;
1366 }
1367 return !inverse;
1368
1369 case "on-multiple-match":
1370 env.resetActions.add(new Environment.ResetAction() {
1371 @Override
1372 public void reset(Environment env) {
1373 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.RECOVER_WITH_WARNINGS);
1374 }
1375 });
1376 if ("error".equals(value)) {
1377 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.DO_NOT_RECOVER);
1378 } else {
1379 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.RECOVER_SILENTLY);
1380 }
1381 return true;
1382
1383 case "ignore_doc_failure":
1384 env.resetActions.add(new Environment.ResetAction() {
1385 @Override
1386 public void reset(Environment env) {
1387 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.RECOVER_WITH_WARNINGS);
1388 }
1389 });
1390 if (inverse) {
1391 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.DO_NOT_RECOVER);
1392 } else {
1393 env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Configuration.RECOVER_SILENTLY);
1394 }
1395 return true;
1396
1397 case "combinations_for_numbering":
1398 if (value.equals("COPTIC EPACT DIGIT ONE") || value.equals("SINHALA ARCHAIC DIGIT ONE") || value.equals("MENDE KIKAKUI DIGIT ONE")) {
1399 return false;
1400 }
1401 return !inverse;
1402
1403 case "xsd-version":
1404 return env.processor.getSaxonEdition().equals("HE") ? false : null;
1405
1406 case "sweep_and_posture":
1407 return env.processor.getSaxonEdition().equals("HE") ? inverse : null;
1408
1409 case "unicode-version":
1410 return value.equals("6.0"); // Avoid running Unicode 9.0 tests - they are slow!
1411
1412 default:
1413 println("**** dependency not recognized for HE: " + type);
1414 return false;
1415 }
1416 }
1417
1418 public boolean unavailableInXX(String type, String value) {
1419 if (type.equals("feature") && value.equals("higher_order_functions")) {
1420 return true;
1421 }
1422 if (type.equals("feature") && value.equals("streaming")) {
1423 return true;
1424 }
1425 if (type.equals("year_component_values") &&
1426 (value.equals("support year above 9999") ||
1427 value.equals("support negative year") ||
1428 value.equals("support year zero")
1429 )) {
1430 return true;
1431 }
1432 return false;
1433 }
1434
1435 /**
1436 * Return a QNamed value from an attribute. This can handle active namespace prefix bindings or Clark notations in the
1437 * attribute string values
1438 *
1439 * @param compiler XPath compiler
1440 * @param contextItem Context item
1441 * @param attributePath Path to the required (singleton?) attribute
1442 * @return the value of the attribute as a QName
1443 */
1444
1445 protected static QName getQNameAttribute(XPathCompiler compiler, XdmNode contextItem, Step<? extends XdmNode> attributePath) {
1446 Optional<XdmNode> att = contextItem.select(attributePath).asOptionalNode();
1447 if (att.isPresent()) {
1448 String val = att.get().getStringValue().trim();
1449 if (val.equals("#unnamed")) {
1450 return new QName(NamespaceConstant.XSLT, "unnamed");
1451 } else if (val.equals("#default")) {
1452 return new QName(NamespaceConstant.XSLT, "default");
1453 } else if (val.startsWith("{")) {
1454 return new QName(StructuredQName.fromClarkName(val));
1455 } else if (val.startsWith("Q{")) {
1456 return new QName(StructuredQName.fromEQName(val));
1457 } else if (val.contains(":")){
1458 try {
1459 QNameValue qn = ResolveQName.resolveQName(val, att.get().getUnderlyingNode().getParent());
1460 return new QName(qn.getStructuredQName());
1461 } catch (XPathException e) {
1462 e.printStackTrace();
1463 return null;
1464 }
1465 } else {
1466 return new QName(val);
1467 }
1468 } else {
1469 return null;
1470 }
1471 }
1472
1473 protected static class ResultDocHandler implements java.util.function.Function<URI, Destination> {
1474
1475 private Processor proc;
1476 private TestOutcome outcome;
1477 private URI baseOutputURI;
1478 boolean serialized;
1479
1480 public ResultDocHandler(Processor proc, TestOutcome outcome, String baseOutputURI, boolean serialized) {
1481 this.proc = proc;
1482 this.outcome = outcome;
1483 try {
1484 this.baseOutputURI = new URI(baseOutputURI);
1485 } catch (URISyntaxException e) {
1486 throw new IllegalArgumentException(e);
1487 }
1488 this.serialized = serialized;
1489 }
1490
1491 public Destination apply(URI uri) {
1492 if (serialized) {
1493 StringWriter stringWriter = new StringWriter();
1494 Serializer destination = proc.newSerializer(stringWriter);
1495 destination.setDestinationBaseURI(uri);
1496 if (uri.equals(baseOutputURI)) {
1497 destination.onClose(() -> outcome.setPrincipalSerializedResult(stringWriter.toString()));
1498 } else {
1499 destination.onClose(() -> outcome.setSecondaryResult(uri, null, stringWriter.toString()));
1500 }
1501 return destination;
1502 } else {
1503 XdmDestination destination = new XdmDestination();
1504 destination.setBaseURI(uri);
1505 if (uri.equals(baseOutputURI)) {
1506 destination.onClose(() -> outcome.setPrincipalResult(destination.getXdmNode()));
1507 } else {
1508 destination.onClose(() -> outcome.setSecondaryResult(uri, destination.getXdmNode(), null));
1509 }
1510 return destination;
1511 }
1512 }
1513
1514 }
1515
1516 protected static class OutputResolver implements OutputURIResolver {
1517
1518 private Processor proc;
1519 private TestOutcome outcome;
1520 private Destination destination;
1521 private StringWriter stringWriter;
1522 boolean serialized;
1523 URI uri;
1524
1525 public OutputResolver(Processor proc, TestOutcome outcome, boolean serialized) {
1526 this.proc = proc;
1527 this.outcome = outcome;
1528 this.serialized = serialized;
1529 }
1530
1531 public OutputResolver newInstance() {
1532 return new OutputResolver(proc, outcome, serialized);
1533 }
1534
1535 public Result resolve(String href, String base) throws XPathException {
1536 try {
1537 uri = new URI(base).resolve(href);
1538 if (serialized) {
1539 //destination = proc.newSerializer();
1540 stringWriter = new StringWriter();
1541 StreamResult result = new StreamResult(stringWriter);
1542 result.setSystemId(uri.toString());
1543 return result;
1544 // ((Serializer)destination).setOutputWriter(stringWriter);
1545 // Receiver r = destination.getReceiver(proc.getUnderlyingConfiguration());
1546 // r.setSystemId(uri.toString());
1547 // return r;
1548 } else {
1549 destination = new XdmDestination();
1550 destination.setDestinationBaseURI(uri);
1551 return destination.getReceiver(null, null); // TBA
1552 //return new SequenceNormalizerWithSpaceSeparator(r);
1553 }
1554 } catch (SaxonApiException | URISyntaxException e) {
1555 throw new XPathException(e);
1556 }
1557 }
1558
1559 public void close(Result result) throws XPathException {
1560 if (uri != null) {
1561 if (serialized) {
1562 outcome.setSecondaryResult(uri, null, stringWriter == null ? "" : stringWriter.toString());
1563 } else {
1564 XdmDestination xdm = (XdmDestination) destination;
1565 if (xdm != null) {
1566 outcome.setSecondaryResult(xdm.getDestinationBaseURI(), xdm.getXdmNode(), null);
1567 }
1568 }
1569 }
1570 }
1571
1572 }
1573 }