Project

Profile

Help

How to connect?
Download (77.5 KB) Statistics
| Branch: | Revision:

he / src / samples / cs / TestRunner10.0 / Xslt30TestSuiteDriver.cs @ be17ef52

1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
using System.Text;
5
using System.Xml;
6
using System.IO;
7
using System.Text.RegularExpressions;
8
using System.Globalization;
9
using Saxon.Api;
10

    
11

    
12
using JFeatureKeys = net.sf.saxon.lib.FeatureKeys;
13
using JConfiguration = net.sf.saxon.Configuration;
14
using JVersion = net.sf.saxon.Version;
15
using JResult = javax.xml.transform.Result;
16
using System.Diagnostics;
17
using TestRunner;
18
using System.Linq;
19
using java.util;
20

    
21
namespace TestRunner
22
{
23
    //C:/work/repositories/hg/xslt30-test C:/work/repositories/hg/xslt30-test/results/saxon/ -lang:XT30 -xt30:on
24

    
25
    // file:////C:/work/repositories/hg/xslt30-test/ C:/work/repositories/hg/xslt30-test/results/saxon/ -lang:XT30 -xt30:on -s:mode -t:mode-1801
26
    /**
27
     * This class runs the W3C XSLT Test Suite, driven from the test catalog.
28
     */
29
    public class Xslt30TestSuiteDriver : TestDriver {
30

    
31

    
32

    
33
        private HashSet<String> alwaysOn = new HashSet<String>();
34

    
35
        private HashSet<String> alwaysOff = new HashSet<String>();
36

    
37
        private HashSet<String> needsEE = new HashSet<String>();
38

    
39
        private HashSet<String> needsPE = new HashSet<String>();
40

    
41
        public Xslt30TestSuiteDriver() {
42
            SetDependencyData();
43
        }
44

    
45

    
46
        //file:////C:/work/repositories/hg/xslt30-test/ C:/work/repositories/hg/xslt30-test/results/saxon/ -lang:XT30 -xt30:on
47
        public static void Mainxxxxx(string[] args) {
48
        if (args.Length == 0 || args[0].Equals("-?")) {
49
            System.Console.WriteLine("testsuiteDir catalog [-o:resultsdir] [-s:testSetName]" +
50
                    " [-t:testNamePattern] [-bytecode:on|off|debug] [-tree] [-lang] [-save][-export][-strict]");
51
        }
52

    
53
        System.Console.WriteLine("Testing Saxon " + (new Processor()).ProductVersion);
54
        new Xslt30TestSuiteDriver().go(args);
55
    }
56

    
57
        public static IPredicate<XdmItem> IsTrue(string attName) {
58
            return new Saxon.Api.Predicate<XdmItem>(element =>
59
            {
60
                if (element is XdmNode)
61
                {
62
                    string attVal = ((XdmNode)element).GetAttributeValue(attName);
63
                    if (attVal != null)
64
                    {
65
                        attVal = attVal.Trim();
66
                        return "yes".Equals(attVal) || "1".Equals(attVal) || "true".Equals(attVal);
67
                    }
68

    
69
                }
70
                return false;
71

    
72
            });
73
            
74
        }
75

    
76
        public void SetDependencyData() {
77
            alwaysOn.Add("feature/disabling_output_escaping");
78
            alwaysOn.Add("feature/serialization");
79
            alwaysOn.Add("feature/namespace_axis");
80
            alwaysOn.Add("feature/dtd");
81
            alwaysOn.Add("feature/built_in_derived_types");
82
            alwaysOn.Add("feature/remote_http");
83
            alwaysOn.Add("feature/xsl-stylesheet-processing-instruction");
84
            alwaysOn.Add("feature/fn-transform-XSLT");
85
            alwaysOn.Add("available_documents");
86
            alwaysOn.Add("ordinal_scheme_name");
87
            alwaysOn.Add("default_calendar_in_date_formatting_functions");
88
            alwaysOn.Add("supported_calendars_in_date_formatting_functions");
89
            alwaysOn.Add("maximum_number_of_decimal_digits");
90
            alwaysOn.Add("default_output_encoding");
91
            alwaysOn.Add("unparsed_text_encoding");
92
            alwaysOn.Add("recognize_id_as_uri_fragment");
93
            alwaysOn.Add("feature/XPath_3.1");
94
            alwaysOn.Add("feature/backwards_compatibility");
95
            alwaysOn.Add("feature/HTML4");
96
            alwaysOn.Add("feature/HTML5");
97

    
98
            needsPE.Add("feature/Saxon-PE");
99
            needsPE.Add("feature/dynamic_evaluation");
100

    
101
            needsEE.Add("languages_for_numbering");
102
            needsEE.Add("feature/streaming");
103
            needsEE.Add("feature/schema_aware");
104
            needsEE.Add("feature/Saxon-EE");
105
            //needsEE.Add("feature/XSD_1.1");
106

    
107

    
108
            needsEE.Add("feature/xquery_invocation");
109
            needsEE.Add("feature/higher_order_functions");
110

    
111
            alwaysOn.Add("detect_accumulator_cycles");
112

    
113

    
114

    
115

    
116
        }
117

    
118
    
119
    public override string catalogNamespace() {
120
        return "http://www.w3.org/2012/10/xslt-test-catalog";
121
    }
122

    
123
    public void writeResultFilePreamble(Processor processor, XdmNode catalog) {
124
        resultsDoc = new Xslt30ResultsDocument(this.resultsDir, Spec.XT30);
125
        //super.writeResultFilePreamble(processor, catalog);
126
    }
127

    
128
    
129
    public override void processSpec(string specStr) {
130
			if (specStr.Equals("XT10")) {
131
				spec = Spec.XT10;
132
			} else if (specStr.Equals("XT20")) {
133
				spec = Spec.XT20;
134
			} else if (specStr.Equals("XT30")) {
135
				spec = Spec.XT30;
136
			} else {
137
				throw new Exception("Unknown spec " + specStr);
138
			}
139
        resultsDoc = new Xslt30ResultsDocument(this.resultsDir, Spec.XT30);
140
        // No action: always use XSLT
141
    }
142

    
143
    
144
    protected override void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc) {
145
        Environment environment = null;
146
        Environment defaultEnv = null;
147
         try
148
            {
149
                defaultEnv = localEnvironments["default"];
150
            }
151
            catch (Exception) { }
152
        foreach (XdmNode env in catalog.Select(Steps.Descendant("environment"))) {
153
            environment = Environment.processEnvironment(this, xpc, env, globalEnvironments, defaultEnv);
154
        }
155
        //buildDependencyMap(driverProc, environment);
156
    }
157

    
158
		/**
159
     * Return a set of named parameters as a map
160
     *
161
     * @param xpath     The XPath compiler to use
162
     * @param node      The node to search for <param> children
163
     * @param getStatic Whether to collect static or non-static sets
164
     * @param tunnel    Whether to collect tunnelled or non-tunnelled sets
165
     * @return Map of the evaluated parameters, keyed by QName
166
     * @throws SaxonApiException
167
     */
168

    
169
		internal Dictionary <QName, XdmValue> GetNamedParameters(XPathCompiler xpath, XdmNode node, bool getStatic, bool tunnel)  {
170
			Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
171
			int i = 1;
172
			string staticTest = getStatic ? "@static='yes'" : "not(@static='yes')";
173
			foreach (XdmItem parami in xpath.Evaluate("param[" + staticTest + "]", node)) {
174
				QName name = GetQNameAttribute(xpath, parami, "@name");
175
				string select = ((XdmNode) parami).GetAttributeValue(new QName("select"));
176
				string tunnelled = ((XdmNode) parami).GetAttributeValue(new QName("tunnel"));
177
				bool required = tunnel == (tunnelled != null && tunnelled.Equals("yes"));
178
				XdmValue value;
179
				if (name == null) {
180
					System.Console.WriteLine("*** No name for parameter " + i + " in initial-template");
181
					throw new Exception("*** No name for parameter " + i + " in initial-template");
182
				}
183
				try {
184
					value = xpath.Evaluate(select, null);
185
					i++;
186
				} catch (Exception e) {
187
					System.Console.WriteLine("*** Error evaluating parameter " + name + " in initial-template : " + e.Message);
188
					throw e;
189
				}
190
				if (required) {
191
					params1.Add(name, value);
192
				}
193
			}
194
			return params1;
195
		}
196

    
197
		internal XdmValue[] getParameters(XPathCompiler xpath, XdmNode node) {
198
			List<XdmValue> params1 = new List<XdmValue>();
199

    
200
			int i = 1;
201
			foreach (XdmItem param in xpath.Evaluate("param[not(@static='yes')]", node)) {
202
				string select = ((XdmNode) param).GetAttributeValue(new QName("select"));
203
				XdmValue value;
204
				try {
205
					value = xpath.Evaluate(select, null);
206
					i++;
207
				} catch (Exception e) {
208
					System.Console.WriteLine("*** Error evaluating parameter " + i + " in initial-function : " + e.Message);
209
					throw e;
210
				}
211
				params1.Add(value);
212
			}
213
			return params1.ToArray();
214
		}
215

    
216

    
217

    
218
		internal static QName GetQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath) {
219
			string exp = "for $att in " + attributePath +
220
				" return if (contains($att, ':')) then resolve-QName($att, $att/..) else " +
221
				" if (contains($att,'{')) then QName(substring-before(substring-after($att,'{'),'}'),substring-after($att,'}')) else" +
222
				" xs:string($att)";
223
            XdmAtomicValue qname = null;
224
            try
225
            {
226
               qname = (XdmAtomicValue)xpath.EvaluateSingle(exp, contextItem);
227
            }
228
            catch (Exception ex) {
229
                Trace.WriteLine("Error in GetQNameAttribute : " + ex.Message);
230
                return null;
231
            }
232
            if (qname == null) {
233
                return null;
234
            }
235
            String qnameStr = qname.GetStringValue();
236
            if (qnameStr.Equals("#unnamed")) {
237
                return new QName(NamespaceConstant.XSLT, "unnamed");
238
            } else if (qnameStr.Equals("#default"))
239
            {
240
                return new QName(NamespaceConstant.XSLT, "default");
241
            }
242
            else if (qnameStr.StartsWith("{"))
243
            {
244
                return QName.FromClarkName(qnameStr);
245
            }
246
            else if (qnameStr.StartsWith("Q{"))
247
            {
248
                return QName.FromEQName(qnameStr);
249
            }
250
            if (qnameStr.Contains(":")) {
251
                QName qqname = new QName(qnameStr, (XdmNode)contextItem);
252
                return qqname;
253
            }
254
			return qname == null ? null : new QName(qname.ToString());
255
		}
256

    
257
    private bool isSlow(string testName) {
258
			return testName.StartsWith("regex-classes")||
259
				testName.Equals("normalize-unicode-008");
260
    }
261

    
262
        internal void CopySchemaNamespace(Environment env, XPathCompiler testXpc) {
263
            JConfiguration config = env.xpathCompiler.Processor.Implementation;
264
            Set ns = config.getImportedNamespaces();
265
            foreach (String s in ns.toArray()) {
266
                testXpc.ImportSchemaNamespace(s);
267

    
268
            }
269

    
270

    
271
        }
272

    
273

    
274
    protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)  {
275

    
276
        TestOutcome outcome = new TestOutcome(this);
277
        string testName = testCase.GetAttributeValue(new QName("name"));
278
        string testSetName = testCase.Parent.GetAttributeValue(new QName("name"));
279

    
280
        if (exceptionsMap.ContainsKey(testName)) {
281
            notrun++;
282
            resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
283
            return;
284
        }
285

    
286
        if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) {
287
            notrun++;
288
            resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
289
            return;
290
        }
291

    
292
       
293
        
294

    
295

    
296
        Environment env = getEnvironment(testCase, xpath);
297
        if(env == null) {
298
            resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
299
            return;
300
        }
301

    
302
            if (testName.Contains("environment-variable"))
303
            {
304
                env.processor.Implementation.setConfigurationProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, new EnvironmentVariableResolver()); 
305

    
306
            }
307
        
308
       // XdmNode testInput = (XdmNode) xpath.EvaluateSingle("test", testCase);
309
        //XdmNode stylesheet = (XdmNode) xpath.EvaluateSingle("stylesheet", testInput);
310
		//XdmNode pack = (XdmNode) xpath.EvaluateSingle("package", testInput);
311

    
312
        Step<XdmNode, XdmNode> testSetDependencies = Steps.Root().Then(Steps.Child("test-set").Then(Steps.Child("dependencies")));
313
        Step<XdmNode, XdmNode> testCaseDependencies = Steps.Child("dependencies");
314
            
315

    
316
            XdmValue allDependencies = new XdmValue(testCase.Select(testSetDependencies.Cat(testCaseDependencies)));
317
            XdmNode lastSpecValue = allDependencies.Select(Steps.Path("spec", "@value")).FirstOrDefault();
318
            String specAtt = lastSpecValue!= null ? lastSpecValue.GetStringValue() : "XSLT10+";
319
            foreach (XdmNode dep in allDependencies.Select(Steps.Child(Predicates.IsElement()))) {
320
                if (!EnsureDependencySatisfied((XdmNode)dep, env)) {
321
                    notrun++;
322
                    string type = dep.NodeName.LocalName;
323
                    string value = dep.GetAttributeValue("value");
324
                    if (value == null) {
325
                        value = type;
326
                    } else {
327
                        value = type + ":" + value;
328
                    }
329

    
330
                    if ("false".Equals(dep.GetAttributeValue("satisfied"))) {
331
                        value = "!" + value;
332
                    }
333
                    String message = "dependency not satisfied" + value;
334
                    if (value.StartsWith("feature:")) {
335

    
336
                        message = "requires optional " + value;
337
                    }
338
                    resultsDoc.writeTestcaseElement(testName, "notRun", message);
339
                    return;
340
                }
341
            }
342

    
343
            if (env.failedToBuild)
344
            {
345
                resultsDoc.writeTestcaseElement(testName, "fail", "unable to build environment");
346
                //noteFailure(testSetName, testName);
347
                return;
348
            }
349

    
350
            if (!env.usable)
351
            {
352
                resultsDoc.writeTestcaseElement(testName, "n/a", "environment dependencies not satisfied");
353
                notrun++;
354
                return;
355
            }
356

    
357
            if (testName.Contains("load-xquery-module"))
358
            {
359

    
360
                ModuleResolver mr = new ModuleResolver(null, this);
361
                mr.setTestCase(testCase);
362
                env.processor.QueryResolver = mr;
363
                /*env.processor.getUnderlyingConfiguration().setModuleURIResolver(
364
                        (moduleURI, baseURI, locations)-> {
365
                    File file = queryModules.get(moduleURI);
366
                    if (file == null)
367
                    {
368
                        return null;
369
                    }
370
                    try
371
                    {
372
                        StreamSource ss = new StreamSource(new FileInputStream(file), baseURI);
373
                        return new StreamSource[] { ss };
374
                    }
375
                    catch (FileNotFoundException e)
376
                    {
377
                        throw new XPathException(e);
378
                    }
379
                }); */
380
            }
381

    
382
            XdmNode testInput = testCase.Select(Steps.Child("test")).FirstOrDefault();
383
            XdmNode stylesheet = testInput.Select(Steps.Child("stylesheet").Where(Predicates.Not(Predicates.AttributeEq("role", "secondary")))).FirstOrDefault();
384
            XdmNode postureAndSweep = testInput.Select(Steps.Child("posture-and-sweep")).FirstOrDefault();
385
            XdmNode principalPackage = testInput.Select(Steps.Child("package").Where(Predicates.AttributeEq("role", "principal"))).FirstOrDefault();
386
            IEnumerable<XdmNode> usedPackages = testInput.Select(Steps.Child("package").Where(Predicates.AttributeEq("role", "secondary")));
387

    
388

    
389

    
390
            XsltExecutable sheet = env.xsltExecutable;
391
       //ErrorCollector collector = new ErrorCollector();
392
		
393
			ErrorCollector collector = new ErrorCollector(outcome);
394
			IList<XmlProcessingError> errorList = new List<XmlProcessingError> ();
395
        XmlUrlResolver res = new XmlUrlResolver();
396
		string xsltLanguageVersion = specAtt.Contains("XSLT30") || specAtt  .Contains("XSLT20+") ? "3.0" : "2.0";
397
        if (stylesheet != null) {
398
               
399
                env.processor.SetProperty(FeatureKeys.ALLOW_MULTITHREADING, "false");
400
            XsltCompiler compiler = env.xsltCompiler;
401
			compiler.SetErrorList(errorList);
402
            Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
403
            Stream styleSource = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
404
            compiler.BaseUri = hrefFile;
405
            compiler.XsltLanguageVersion = (specAtt.Contains("XSLT30") || specAtt.Contains("XSLT20+") ? "3.0" : "2.0");
406

    
407
            IEnumerable<XdmNode> paramsi = testInput.Select(Steps.Child("param").Where(IsTrue("static")));
408
			foreach (XdmNode param in paramsi) {
409
					String name = param.GetAttributeValue("name");
410
					String select = param.GetAttributeValue("select");
411
					XdmValue value;
412
					try {
413
						value = xpath.Evaluate(select, null);
414
					} catch (Exception e) {
415
						Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
416
						//throw e;
417
						continue;
418
					}
419
					compiler.SetParameter(new QName(name), value);
420

    
421
		    }
422
                
423
                    foreach (XdmNode pack in usedPackages)
424
                    {
425
                        String fileName2 = pack.GetAttributeValue("file");
426
                        Uri fileUri = res.ResolveUri(pack.BaseUri, fileName2);
427
                        Stream styleSource2 = new FileStream(fileUri.AbsolutePath, FileMode.Open, FileAccess.Read);
428

    
429
                        XsltPackage xpack = compiler.CompilePackage(styleSource2);
430
                        xpack = exportImportPackage(testName, testSetName, outcome, compiler, xpack, collector);
431
                        compiler.ImportPackage(xpack);
432
                        // Following needed for dynamic loading of packages using fn:transform()
433
                        // env.processor.getUnderlyingConfiguration().getDefaultXsltCompilerInfo().getPackageLibrary().addPackage(xpack.getUnderlyingPreparedPackage()); //TODO - check this on .net
434
                    }
435
                
436

    
437
            try {
438
                sheet = exportImport(testName, testSetName, outcome, compiler, sheet, collector, styleSource);  //compiler.Compile(stream);
439

    
440
            } catch(Exception err){
441
					Console.WriteLine (err.Message);
442
					//Console.WriteLine(err.StackTrace);
443
					IEnumerator enumerator = errorList.GetEnumerator();
444
					bool checkCur = enumerator.MoveNext();
445
					/*if (checkCur && enumerator.Current != null) {
446
						outcome.SetException ((Exception)(enumerator.Current));
447
					} else {
448
						Console.WriteLine ("Error: Unknown exception thrown");
449
					}*/
450
					outcome.SetErrorsReported (errorList);
451
                    outcome.SetException(err);
452

    
453
                    //outcome.SetErrorsReported(collector.GetErrorCodes);
454
            }
455

    
456

    
457
                string optimizationAssertion;
458
                optimizationAssertions.TryGetValue(testName, out optimizationAssertion);
459
                if (optimizationAssertion != null && sheet != null)
460
                {
461
                    try
462
                    {
463
                        bool ok = AssertOptimization(sheet, optimizationAssertion);
464
                        if (ok)
465
                        {
466
                            Console.WriteLine("Optimization OK: " + optimizationAssertion);
467
                        }
468
                        else
469
                        {
470
                            outcome.SetComment("Optimization assertion failed");
471
                            if (strict)
472
                            {
473
                               //noteFailure(testSetName, testName);
474
                                resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
475
                            }
476
                        }
477
                        Console.WriteLine("Optimization OK: " + optimizationAssertion);
478
                    }
479
                    catch (Exception e)
480
                    {
481
                        Console.WriteLine("Optimization assertion failed: " + optimizationAssertion);
482
                    }
483
                }
484

    
485

    
486
                //  compiler.setErrorListener(collector);
487
            }  else if (principalPackage != null) {
488
                /*	Uri hrefFile = res.ResolveUri(pack.BaseUri, pack.GetAttributeValue(new QName("file")));
489
                    Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
490

    
491
                    XsltCompiler compiler = env.xsltCompiler;
492
                    compiler.ErrorList = errorList;
493
                    compiler.XsltLanguageVersion =  (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
494
                    //compiler.setErrorListener(collector);
495

    
496
                    try {
497
                        XsltPackage xpack = compiler.CompilePackage(stream);
498
                        sheet = xpack.Link();
499
                    } catch (Exception err) {
500
                        Console.WriteLine (err.Message);
501
                        IEnumerator enumerator = errorList.GetEnumerator ();
502
                        if (enumerator.MoveNext())
503
                        {
504
                            outcome.SetException((Exception)(enumerator.Current));
505
                            outcome.SetErrorsReported(errorList);
506
                        }
507
                    } */
508

    
509
                XsltCompiler compiler = env.xsltCompiler;
510
                //compiler.setXsltLanguageVersion(xsltLanguageVersion);
511
                //compiler.ErrorReporter = collector;
512
                compiler.ClearParameters();
513
                IEnumerable<XdmNode> paramEnumerable  = testInput.Select(Steps.Child("param").Where(IsTrue("static")));
514

    
515
                foreach(XdmNode itemxx in paramEnumerable) {
516
                    String name = itemxx.GetAttributeValue("name");
517
                    String select = itemxx.GetAttributeValue("select");
518
                    XdmValue value;
519
                    try
520
                    {
521
                        value = xpath.Evaluate(select, null);
522
                    }
523
                    catch (Exception e)
524
                    {
525
                        Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
526
                        throw e;
527
                    }
528
                    compiler.SetParameter(new QName(name), value);
529
                };
530

    
531
                foreach (XdmNode pack in usedPackages)
532
                {
533
                    String pfileName = pack.GetAttributeValue("file");
534
                    Uri pfileUri = res.ResolveUri(testCase.BaseUri, pfileName);
535
                    Stream pstyleSource = new FileStream(pfileUri.AbsolutePath, FileMode.Open, FileAccess.Read);
536

    
537

    
538
                    XsltPackage xpack = compiler.CompilePackage(pstyleSource);
539
                    compiler.ImportPackage(xpack);
540
                }
541
                String fileName = principalPackage.GetAttributeValue("file");
542
                Uri fileUri = res.ResolveUri(testCase.BaseUri, fileName);
543
                Stream styleSource = new FileStream(fileUri.AbsolutePath, FileMode.Open, FileAccess.Read);
544

    
545
                try
546
                {
547
                    XsltPackage xpack = compiler.CompilePackage(styleSource);
548
                    sheet = xpack.Link();
549
                }
550
                catch (Exception err)
551
                {
552
                    println(err.Message);
553
                    outcome.SetException(err);
554
                    //outcome.SetErrorsReported(collector.);
555
                }
556
               
557

    
558
                sheet = exportImport(testName, testSetName, outcome, compiler, sheet, collector, styleSource);
559

    
560
            }
561

    
562
            if (sheet != null)
563
            {
564
                XdmItem contextItem = env.contextItem;
565
                XdmValue initialMatchSelection = null;
566
                XdmNode initialMode = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput);
567
                XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput);
568
                XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput);
569

    
570
                QName initialModeName = initialMode == null ? null : GetQNameAttribute(xpath, initialMode, "@name");
571
                QName initialTemplateName = initialTemplate == null ? null : GetQNameAttribute(xpath, initialTemplate, "@name");
572
                string baseOutputURI = "file:////" + resultsDir + "/results/output.xml";
573
                XdmNode outputNode = testInput.Select(Steps.Path("output", "@file")).FirstOrDefault();
574
                string outputUri = (outputNode != null ? outputNode.GetStringValue() : null);
575

    
576
                if (outputUri != null)
577
                {
578
                    if (outputUri.Equals(""))
579
                    {
580
                        String testSetUri = testCase.BaseUri.AbsoluteUri;
581
                        int c = testSetUri.IndexOf("/tests/");
582
                        outputUri = testSetUri.Substring(c + 7);
583

    
584

    
585
                    }
586
                    baseOutputURI = (new XmlUrlResolver()).ResolveUri(new Uri(baseOutputURI), outputUri).AbsolutePath;
587
                }
588
                outcome.BaseOutputUri = new Uri(baseOutputURI);
589

    
590
                if (initialMode != null)
591
                {
592
                    XdmItem select = xpath.EvaluateSingle("@select", initialMode);
593
                    if (select != null)
594
                    {
595
                        initialMatchSelection = env.xpathCompiler.Evaluate(select.GetStringValue(), null);
596
                    }
597
                }
598

    
599
                if (useXslt30Transformer)
600
                {
601
                    try
602
                    {
603

    
604
                        bool assertsSerial = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0;
605
                        bool resultAsTree = env.outputTree;
606
                        bool serializationDeclared = env.outputSerialize;
607
                        XdmNode needsTree = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput);
608
                        if (needsTree != null)
609
                        {
610
                            resultAsTree = needsTree.StringValue.Equals("yes");
611
                        }
612
                        XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput);
613
                        if (needsSerialization != null)
614
                        {
615
                            serializationDeclared = needsSerialization.StringValue.Equals("yes");
616
                        }
617
                        bool resultSerialized = serializationDeclared || assertsSerial;
618

    
619
                        if (assertsSerial)
620
                        {
621
                            String comment = outcome.GetComment();
622
                            comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* ");
623
                            outcome.SetComment(comment);
624
                        }
625

    
626

    
627
                        Xslt30Transformer transformer = sheet.Load30();
628
                        transformer.InputXmlResolver = env;
629
                        if (env.unparsedTextResolver != null)
630
                        {
631
                            transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver);
632
                        }
633

    
634
                        Dictionary<QName, XdmValue> caseGlobalParams = GetNamedParameters(xpath, testInput, false, false);
635
                        Dictionary<QName, XdmValue> caseStaticParams = GetNamedParameters(xpath, testInput, true, false);
636
                        Dictionary<QName, XdmValue> globalParams = new Dictionary<QName, XdmValue>(env.params1);
637

    
638
                        foreach (KeyValuePair<QName, XdmValue> entry in caseGlobalParams)
639
                        {
640
                            globalParams.Add(entry.Key, entry.Value);
641

    
642
                        }
643

    
644
                        /*foreach(KeyValuePair<QName, XdmValue> entry in caseStaticParams) {
645
							globalParams.Add(entry.Key, entry.Value);
646

    
647
						}*/
648

    
649

    
650
                        transformer.SetStylesheetParameters(globalParams);
651

    
652
                        if (contextItem != null)
653
                        {
654
                            transformer.GlobalContextItem = contextItem;
655
                        }
656

    
657
                        transformer.MessageListener = collector;
658

    
659
                        transformer.BaseOutputURI = baseOutputURI;
660

    
661
                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);
662

    
663
                        XdmValue result = null;
664

    
665
                        TextWriter sw = new StringWriter();
666

    
667
                        Serializer serializer = env.processor.NewSerializer();
668

    
669
                        serializer.SetOutputWriter(sw);
670
                        //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
671

    
672
                        OutputResolver serializingOutput = new OutputResolver(env.processor, outcome, true);
673
                        net.sf.saxon.Controller controller = transformer.GetUnderlyingController;
674

    
675

    
676
                        XmlDestination dest = null;
677
                        if (resultAsTree && !resultSerialized)
678
                        {
679
                            // If we want non-serialized, we need to accumulate any result documents as trees too
680
                            transformer.ResultDocumentHandler = new ResultDocumentHandler(env.processor, outcome, baseOutputURI, false);
681

    
682

    
683
                            dest = new XdmDestination();
684

    
685
                        }
686
                        else
687
                        if (resultSerialized)
688
                        {
689
                            dest = serializer;
690
                        }
691

    
692
                        Stream src = null;
693
                        Uri srcBaseUri = new Uri("http://uri");
694
                        XdmNode srcNode = null;
695
                        DocumentBuilder builder2 = env.processor.NewDocumentBuilder();
696

    
697
                        if (env.streamedPath != null)
698
                        {
699
                            src = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read);
700
                            srcBaseUri = new Uri(env.streamedPath);
701
                        }
702
                        else if (env.streamedContent != null)
703
                        {
704
                            byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent);
705
                            src = new MemoryStream(byteArray);//, "inlineDoc");
706
                            builder2.BaseUri = new Uri("http://uri");
707
                        }
708
                        else if (initialTemplate == null && contextItem != null)
709
                        {
710
                            srcNode = (XdmNode)(contextItem);
711
                        }
712

    
713
                        if (src != null && !"skip".Equals(env.streamedInputValidation))
714
                        {
715
                            Processor processor = (Processor)sheet.Implementation.getUnderlyingCompiledStylesheet().getConfiguration().getProcessor();
716
                            SchemaValidator validatori = processor.SchemaManager.NewSchemaValidator();
717
                            //validatori.SetDestination
718

    
719
                        }
720

    
721
                        if (initialMode != null)
722
                        {
723
                            QName name = GetQNameAttribute(xpath, initialMode, "@name");
724
                            try
725
                            {
726
                                if (name != null)
727
                                {
728
                                    transformer.InitialMode = name;
729
                                }
730
                            }
731
                            catch (Exception e)
732
                            {
733
                                if (e.InnerException is net.sf.saxon.trans.XPathException)
734
                                {
735
                                    Console.WriteLine(e.Message);
736
                                    outcome.SetException(e);
737
                                    //throw new SaxonApiException(e.getCause());
738
                                }
739
                                else
740
                                {
741
                                    throw e;
742
                                }
743
                            }
744
                        }
745
                        if (src == null && srcNode == null && initialFunction == null && initialTemplateName == null && initialModeName == null)
746
                        {
747
                            initialTemplateName = new QName("xsl", NamespaceConstant.XSLT, "initial-template");
748
                        }
749

    
750
                        if (initialMode != null || initialTemplate != null)
751
                        {
752
                            XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode);
753
                            Dictionary<QName, XdmValue> params1 = GetNamedParameters(xpath, init, false, false);
754
                            Dictionary<QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true);
755
                            if (xsltLanguageVersion.Equals("2.0"))
756
                            {
757
                                if (!(params1.Count == 0 && tunnelledParams.Count == 0))
758
                                {
759
                                    Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0");
760
                                }
761
                            }
762
                            else
763
                            {
764
                                transformer.SetInitialTemplateParameters(params1, false);
765
                                transformer.SetInitialTemplateParameters(tunnelledParams, true);
766
                            }
767
                        }
768

    
769

    
770
                        if (initialTemplateName != null)
771
                        {
772
                            transformer.GlobalContextItem = contextItem;
773
                            if (dest == null)
774
                            {
775
                                result = transformer.CallTemplate(initialTemplateName);
776
                            }
777
                            else
778
                            {
779
                                transformer.CallTemplate(initialTemplateName, dest);
780
                            }
781
                        }
782
                        else if (initialFunction != null)
783
                        {
784
                            QName name = GetQNameAttribute(xpath, initialFunction, "@name");
785
                            XdmValue[] params2 = getParameters(xpath, initialFunction);
786
                            if (dest == null)
787
                            {
788
                                result = transformer.CallFunction(name, params2);
789
                            }
790
                            else
791
                            {
792
                                transformer.CallFunction(name, params2, dest);
793
                            }
794
                        }
795
                        else if (initialMatchSelection != null)
796
                        {
797
                            if (dest == null)
798
                            {
799
                                result = transformer.ApplyTemplates(initialMatchSelection);
800
                            }
801
                            else
802
                            {
803
                                transformer.ApplyTemplates(initialMatchSelection, dest);
804
                            }
805

    
806
                        }
807
                        else
808
                        {
809
                            if (dest == null)
810
                            {
811
                                if (src != null)
812
                                {
813
                                    result = transformer.ApplyTemplates(src, srcBaseUri);
814
                                }
815
                                else
816
                                {
817
                                    result = transformer.ApplyTemplates(srcNode);
818
                                }
819
                            }
820
                            else
821
                            {
822
                                if (src != null)
823
                                {
824
                                    transformer.ApplyTemplates(src, dest);
825
                                }
826
                                else
827
                                {
828
                                   
829
                                        transformer.ApplyTemplates(srcNode, dest);
830
                                        
831
                                    
832
                                    }
833
                            }
834
                        }
835

    
836
                        //outcome.SetWarningsReported(collector.getFoundWarnings());
837
                        if (resultAsTree && !resultSerialized)
838
                        {
839
                            result = ((XdmDestination)(dest)).XdmNode;
840
                        }
841
                        if (resultSerialized)
842
                        {
843
                            outcome.SetPrincipalSerializedResult(sw.ToString());
844
                        }
845
                        outcome.SetPrincipalResult(result);
846

    
847
                        if (saveResults)
848
                        {
849
                            String s = sw.ToString();
850
                            // If a transform result is entirely xsl:result-document, then result will be null
851
                            if (!resultSerialized && result != null)
852
                            {
853
                                StringWriter sw2 = new StringWriter();
854
                                Serializer se = env.processor.NewSerializer(sw2);
855
                                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
856
                                env.processor.WriteXdmValue(result, se);
857
                                se.Close();
858
                                s = sw2.ToString();
859
                            }
860
                            // currently, only save the principal result file in the result directory
861
                            saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out");
862
                            Dictionary<Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments();
863
                            foreach (KeyValuePair<Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments)
864
                            {
865
                                Uri key = entry.Key;
866
                                String path = key.AbsolutePath;
867
                                String serialization = outcome.Serialize(env.processor, entry.Value);
868

    
869
                                saveResultsToFile(serialization, path);
870
                            }
871
                        }
872
                    }
873
                    catch (Exception err)
874
                    {
875
                        //if (err.getCause() is XPathException &&
876
                        //!((XPathException) err.getCause()).hasBeenReported()) {
877
                        //System.err.println("Unreported ERROR: " + err.getCause());
878
                        //}
879
                        outcome.SetException(err);
880
                        if (collector.getErrorCodes().Count > 0)
881
                        {
882
                            outcome.SetErrorQNameReported(collector.getErrorCodes());
883
                        }
884
                        //Console.WriteLine(err.StackTrace);
885
                        /*if(err.getErrorCode() == null) {
886
                        int b = 3 + 4;  }
887
                    if(err.getErrorCode() != null)
888
                        outcome.AddReportedError(err.getErrorCode().getLocalName());
889
                    } else {
890
                        outcome.SetErrorsReported(collector.getErrorCodes());
891
                    }*/
892
                    } /*catch (Exception err) {
893
						err.printStackTrace();
894
						failures++;
895
						resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
896
						return;
897
					}*/
898
                }
899
                else
900
                {
901

    
902
                    try
903
                    {
904
                        XsltTransformer transformer = sheet.Load();
905

    
906

    
907
                        //transformer.SetURIResolver(env); //TODO
908
                        if (env.unparsedTextResolver != null)
909
                        {
910
                            transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
911
                        }
912
                        if (initialTemplate != null)
913
                        {
914
                            transformer.InitialTemplate = initialTemplateName;
915
                        }
916
                        if (initialMode != null)
917
                        {
918
                            transformer.InitialMode = initialModeName;
919
                        }
920
                        foreach (XdmItem param in xpath.Evaluate("param", testInput))
921
                        {
922
                            string name = ((XdmNode)param).GetAttributeValue(new QName("name"));
923
                            string select = ((XdmNode)param).GetAttributeValue(new QName("select"));
924
                            XdmValue value = xpath.Evaluate(select, null);
925
                            transformer.SetParameter(new QName(name), value);
926
                        }
927
                        if (contextItem != null)
928
                        {
929
                            transformer.InitialContextNode = (XdmNode)contextItem;
930
                        }
931
                        if (env.streamedPath != null)
932
                        {
933
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
934
                        }
935
                        foreach (QName varName in env.params1.Keys)
936
                        {
937
                            transformer.SetParameter(varName, env.params1[varName]);
938
                        }
939
                        //transformer.setErrorListener(collector);
940
                        transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");
941
                        /*transformer.MessageListener = (new MessageListener() {
942
                            public void message(XdmNode content, bool terminate, SourceLocator locator) {
943
                                outcome.addXslMessage(content);
944
                            }
945
                        });*/
946

    
947

    
948
                        // Run the transformation twice, once for serialized results, once for a tree.
949
                        // TODO: we could be smarter about this and capture both
950

    
951
                        // run with serialization
952
                        StringWriter sw = new StringWriter();
953
                        Serializer serializer = env.processor.NewSerializer(sw);
954
                        transformer.ResultDocumentHandler = new ResultDocumentHandler(env.processor, outcome, testCase.BaseUri.AbsolutePath, true);
955

    
956

    
957
                        transformer.Run(serializer);
958

    
959
                        outcome.SetPrincipalSerializedResult(sw.ToString());
960
                        if (saveResults)
961
                        {
962
                            // currently, only save the principal result file
963
                            saveResultsToFile(sw.ToString(),
964
                                    resultsDir + "/results/" + testSetName + "/" + testName + ".out");
965
                            Dictionary<Uri, TestOutcome.SingleResultDoc> xslResultDocument = outcome.GetSecondaryResultDocuments();
966

    
967
                            foreach (KeyValuePair<Uri, TestOutcome.SingleResultDoc> entry in xslResultDocument) {
968
                                Uri key = entry.Key;
969
                                if (key != null) {
970
                                    String path = entry.Key.AbsolutePath;
971
                                    String serialization = outcome.Serialize(env.processor, entry.Value);
972
                                    saveResultsToFile(serialization, path);
973

    
974
                                }
975

    
976
                            }
977

    
978
                        }
979
                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);
980

    
981
                        // run without serialization
982
                        if (env.streamedPath != null)
983
                        {
984
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
985
                        }
986
                        XdmDestination destination = new XdmDestination();
987
                        transformer.ResultDocumentHandler = new ResultDocumentHandler(env.processor, outcome, testCase.BaseUri.AbsolutePath, false);
988
                        transformer.Run(destination);
989

    
990
                        //transformer. .transform();
991
                        outcome.SetPrincipalResult(destination.XdmNode);
992
                        //}
993
                    }
994
                    catch (Exception err)
995
                    {
996
                        outcome.SetException(err);
997
                        //outcome.SetErrorsReported(collector.getErrorCodes());
998
                        // err.printStackTrace();
999
                        // failures++;
1000
                        //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
1001
                        //return;
1002
                    }
1003
                }
1004
            }
1005
            XdmNode assertion = (XdmNode) xpath.EvaluateSingle("result/*", testCase); //testCase.Select(PathFromList(new List<>Child("result"), Child().Where(IsElement())));
1006
            if (assertion == null) {
1007
            failures++;
1008
            resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
1009
            return;
1010
        }
1011
        XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
1012
            //assertionXPath.setLanguageVersion("3.0");
1013
            CopySchemaNamespace(env, assertionXPath);
1014
        bool success = outcome.TestAssertion(outcome, assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);
1015
        if (success) {
1016
            if (outcome.GetWrongErrorMessage() != null) {
1017
                outcome.SetComment(outcome.GetWrongErrorMessage());
1018
                wrongErrorResults++;
1019
            } else {
1020
                successes++;
1021
            }
1022
            resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
1023
        } else {
1024
            failures++;
1025
            resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
1026
        }
1027
    
1028
}
1029

    
1030
        private bool AssertOptimization(XsltExecutable stylesheet, string assertion)
1031
        {
1032
            XdmDestination builder = new XdmDestination();
1033
            stylesheet.Explain(builder);
1034
            builder.Close();
1035
            XdmNode expressionTree = builder.XdmNode;
1036
            XPathCompiler xpe = stylesheet.Processor.NewXPathCompiler();
1037
            XPathSelector exp = xpe.Compile(assertion).Load();
1038
            exp.ContextItem = expressionTree;
1039
            XdmAtomicValue bv = (XdmAtomicValue)exp.EvaluateSingle();
1040
            if (bv == null || !bv.GetBooleanValue())
1041
            {
1042
                println("** Optimization assertion failed");
1043
                println(expressionTree.StringValue);
1044
            }
1045
            return bv != null && bv.GetBooleanValue();
1046
        }
1047

    
1048
        protected XsltExecutable exportImport(string testName, string testSetName, TestOutcome outcome, XsltCompiler compiler, XsltExecutable sheet, ErrorCollector collector, Stream styleSource)
1049
        {
1050
            try
1051
            {
1052
                if (export && IsExportable(testName))
1053
                {
1054
                    sheet = ExportStylesheet(testName, testSetName, compiler, sheet, styleSource);
1055
                }
1056
                else if (sheet == null)
1057
                {
1058
                    sheet = compiler.Compile(styleSource);
1059
                }
1060
            }
1061

    
1062
            catch (Exception err)
1063
            {
1064
                //err.printStackTrace();
1065
                Console.WriteLine(err.Message);
1066
                outcome.SetException(err);
1067
                //outcome.setErrorsReported(collector.getErrorCodes());
1068
            }
1069
            return sheet;
1070
        }
1071

    
1072
        private XsltExecutable ExportStylesheet(string testName, string testSetName, XsltCompiler compiler, XsltExecutable sheet, Stream styleSource)
1073
        {
1074
            try
1075
            {
1076
                Uri fileUri = new Uri(resultsDir + "/export/" + testSetName + "/" + testName + ".sef");
1077
                Stream exportFile = new FileStream(fileUri.AbsolutePath, FileMode.Open, FileAccess.Read);
1078
               
1079
                XsltPackage compiledPack = compiler.CompilePackage(styleSource);
1080
                compiledPack.Save(exportFile);
1081
                
1082
                sheet = ReloadExportedStylesheet(compiler,fileUri);
1083
            }
1084
            catch (Exception e)
1085
            {
1086
               // compiler.GetErrorList().Add(new StaticError(e));
1087
                //System.err.println(e.getMessage());
1088
                //e.printStackTrace();  //temporary, for debugging
1089
                throw e;
1090
            }
1091
            return sheet;
1092
        }
1093

    
1094
        private XsltExecutable ReloadExportedStylesheet(XsltCompiler compiler, Uri exportFile)
1095
        {
1096
            return compiler.LoadExecutablePackage(exportFile);
1097
        }
1098

    
1099
        private bool IsExportable(string testName)
1100
        {
1101
            return !(testName.Equals("load-xquery-module-004") || testName.Equals("transform-004"));
1102
        }
1103

    
1104
        private XsltPackage exportImportPackage(string testName, string testSetName, TestOutcome outcome, XsltCompiler compiler, XsltPackage pack, ErrorCollector collector)
1105
        {
1106
            try
1107
            {
1108
                if (export)
1109
                {
1110
                    try
1111
                    {
1112
                        Uri fileUri = new Uri(resultsDir + "/export/" + testSetName + "/" + testName + ".base.sef");
1113
                        Stream exportFile = new FileStream(fileUri.AbsolutePath, FileMode.Open, FileAccess.Read);
1114

    
1115
                        Console.WriteLine("Exported package to " + fileUri);
1116
                        pack.Save(exportFile);
1117
                        return compiler.LoadLibraryPackage(fileUri);
1118
                    }
1119
                    catch (Exception e)
1120
                    {
1121
                        Console.WriteLine(e.Message);
1122
                        //e.printStackTrace();  //temporary, for debugging
1123
                        throw e;
1124
                    }
1125
                }
1126
                else
1127
                {
1128
                    return pack;
1129
                }
1130
            }
1131
            catch (Exception err)
1132
            {
1133
                outcome.SetException(err);
1134
               
1135
              //  outcome.SetErrorsReported(collector.getErrorCodes());
1136
            }
1137
           /* catch (Exception err)
1138
            {
1139
                err.printStackTrace();
1140
                System.err.println(err.getMessage());
1141
                outcome.setException(new QName(err.getClass().getName()));
1142
                outcome.setErrorsReported(collector.getErrorCodes());
1143
            }*/
1144
            return pack;
1145
        }
1146

    
1147
public class EnvironmentVariableResolver : net.sf.saxon.lib.EnvironmentVariableResolver
1148
{
1149

    
1150
    public EnvironmentVariableResolver() { }
1151

    
1152
    public Set getAvailableEnvironmentVariables()
1153
    {
1154
        Set strings = new HashSet();
1155
        strings.add("QTTEST");
1156
        strings.add("QTTEST2");
1157
        strings.add("QTTESTEMPTY");
1158
        return strings;
1159
    }
1160

    
1161
    public string getEnvironmentVariable(string name)
1162
    {
1163
        if (name.Equals("QTTEST"))
1164
        {
1165
            return "42";
1166
        }
1167
        else if (name.Equals("QTTEST2"))
1168
        {
1169
            return "other";
1170
        }
1171
        else if (name.Equals("QTTESTEMPTY"))
1172
        {
1173
            return "";
1174
        }
1175
        else
1176
        {
1177
            return null;
1178
        }
1179
    }
1180

    
1181

    
1182
}
1183

    
1184
public class ResultDocumentHandler : IResultDocumentHandler
1185
        {
1186

    
1187
            private Processor proc;
1188
            private TestOutcome outcome;
1189
            private Uri baseOutputUri;
1190
            bool serialized;
1191
            public ResultDocumentHandler(Processor processor, TestOutcome outcome, String baseOutputURI, bool serialized) {
1192
                this.proc = processor;
1193
                this.outcome = outcome;
1194
                try {
1195
                    this.baseOutputUri = new Uri(baseOutputURI);
1196
                }
1197
                catch (Exception e) { }
1198
                this.serialized = serialized;
1199

    
1200
            }
1201
            public XmlDestination HandleResultDocument(string href, Uri baseUri)
1202
            {
1203
               // if (serialized) {
1204

    
1205
                    StringWriter writer = new StringWriter();
1206
                    Serializer dest = proc.NewSerializer();
1207
                   
1208
                    XmlUrlResolver res = new XmlUrlResolver();
1209
                    Uri uri = res.ResolveUri(baseUri, href);
1210
                    dest.BaseUri = uri;
1211
                dest.SetOutputFile(uri.AbsolutePath);
1212

    
1213
                if (uri.Equals(baseOutputUri))
1214
                    {
1215

    
1216
                        outcome.SetPrincipalSerializedResult(writer.ToString());
1217
                    }
1218
                    else
1219
                    {
1220
                        outcome.SetSecondaryResult(uri, null, writer.ToString(), proc);
1221
                    }
1222
                    return dest;
1223
                /*   }
1224
                   else {
1225

    
1226
                       XdmDestination dest = new XdmDestination();
1227
                       XmlUrlResolver res = new XmlUrlResolver();
1228
                       Uri uri = res.ResolveUri(baseUri, href);
1229
                       dest.BaseUri = uri;
1230
                    
1231
                    XdmValue doc = proc.NewXPathCompiler().Compile("doc('" + uri + "')").Load().EvaluateSingle();
1232
                    if (uri.Equals(baseOutputUri))
1233
                       {
1234

    
1235
                           outcome.SetPrincipalResult(null);
1236
                       }
1237
                       else
1238
                       {
1239
                        
1240
                          outcome.SetSecondaryResult(uri, null ,null, proc);
1241
                       }
1242
                       return dest;
1243

    
1244
                   }*/
1245
            }
1246
        }
1247

    
1248

    
1249

    
1250

    
1251
        internal bool mustSerialize(XdmNode testCase, XPathCompiler xpath) {
1252
        return saveResults ||
1253
                ((XdmAtomicValue) xpath.EvaluateSingle(
1254
                "exists(./result//(assert-serialization-error|serialization-matches|assert-serialization)[not(parent::*[self::assert-message|self::assert-result-document])])", testCase)).GetBooleanValue();
1255
    }
1256

    
1257
    private void saveResultsToFile(string content, string filePath) {
1258
        try {
1259
            System.IO.File.WriteAllText(filePath, content);
1260
        } catch (IOException e) {
1261
            println("*** Failed to save results to " + filePath);
1262
            throw e;
1263
        }
1264
    }
1265

    
1266

    
1267
    public class ResetAction {
1268

    
1269
            Environment env = null;
1270
            decimal oldVersion;
1271

    
1272
            ResetAction(Environment envi, decimal oldVer) {
1273
                oldVersion = oldVer;
1274
                env = envi;
1275
            }
1276
        public void reset(Environment env)
1277
        {
1278
            env.processor.XmlVersion = oldVersion;
1279
        }
1280
    }
1281

    
1282

    
1283

    
1284
        public override bool EnsureDependencySatisfied(XdmNode dependency, Environment env) {
1285
            string type = dependency.NodeName.LocalName;
1286
            string value = dependency.GetAttributeValue("value");
1287
            if (value == null) {
1288
                value = "*";
1289
            }
1290
            String tv = type + "/" + value;
1291
            bool inverse = "false".Equals(dependency.GetAttributeValue("satisfied"));
1292
            bool needed = !"false".Equals(dependency.GetAttributeValue("satisfied"));
1293

    
1294
            if (alwaysOn.Contains(type) || alwaysOn.Contains(tv)) {
1295
                return needed;
1296
            }
1297

    
1298
            if (alwaysOff.Contains(type) || alwaysOff.Contains(tv))
1299
            {
1300
                return !needed;
1301
            }
1302

    
1303
            String edition = env.processor.Edition;
1304

    
1305
            if (needsPE.Contains(type) || needsPE.Contains(tv)) {
1306

    
1307
                return (edition.Equals("PE") || edition.Equals("EE")) == needed;
1308
            }
1309

    
1310
            if (needsEE.Contains(type) || needsEE.Contains(tv)) {
1311
                return edition.Equals("EE") == needed;
1312
            }
1313
            
1314

    
1315

    
1316
            switch (type)
1317
            {
1318
                case "spec":
1319

    
1320
                    bool atLeast = value.EndsWith("+");
1321
                    value = value.Replace("+", "");
1322

    
1323
                    String specName = ((SpecAttr)spec.GetAttr()).svname.Replace("XT", "XSLT");
1324
                    int order = value.CompareTo(specName);
1325
                    return atLeast ? order <= 0 : order == 0;
1326

    
1327
                case "feature":
1328
                    switch (value)
1329
                    {
1330
                        case "XML_1.1":
1331
                            {
1332
                                decimal requiredVersion = (decimal)(inverse ? 1.0 : 1.1);
1333
                                decimal oldVersion = env.processor.XmlVersion;
1334
                                env.resetActions.Add(envi =>
1335
                                {
1336
                                    envi.processor.XmlVersion = oldVersion;
1337
                                }
1338
                            );
1339
                                env.processor.XmlVersion = requiredVersion;
1340
                                return true;
1341
                            }
1342

    
1343
                        case "XSD_1.1":
1344
                            {
1345
                                String requiredVersion = (inverse ? "1.0" : "1.1");
1346
                                String oldVersion = env.processor.GetProperty(Saxon.Api.Feature<string>.XSD_VERSION);
1347
                                if (!oldVersion.Equals(requiredVersion))
1348
                                {
1349
                                    env.processor.SetProperty(Saxon.Api.Feature<string>.XSD_VERSION, requiredVersion);
1350
                                    env.resetActions.Add(envi =>
1351
                                    {
1352
                                        envi.processor.SetProperty(Saxon.Api.Feature<String>.XSD_VERSION, oldVersion);
1353

    
1354
                                    });
1355
                                }
1356
                                return true;
1357
                            }
1358

    
1359
                        case "higher_order_functions":
1360
                            return !inverse;
1361
                        case "simple-uca-fallback":
1362
                            return !inverse;
1363
                        case "advanced-uca-fallback":
1364
                            return (edition.Equals("PE") || edition.Equals("EE")) ^ inverse;
1365
                        case "streaming-fallback":
1366
                            bool requiredi = !inverse;
1367
                            bool old = (bool)env.processor.GetProperty(Feature<bool>.STREAMING_FALLBACK);
1368
                            if (old != requiredi)
1369
                            {
1370
                                env.processor.SetProperty(Feature<bool>.STREAMING_FALLBACK, requiredi);
1371
                                env.resetActions.Add(envi =>
1372
                                {
1373
                                    env.processor.SetProperty(Feature<bool>.STREAMING_FALLBACK, old);
1374
                                });
1375
                            }
1376
                            return true;
1377
                    
1378

    
1379
                    default:
1380
                        Console.WriteLine("*** Unknown feature in HE: " + value);
1381
                        return env.processor.Edition.Equals("HE") ? false : true; //in java the true is null. Check logic on .net
1382
                    
1383
            }
1384

    
1385

    
1386
            
1387
             case "default_language_for_numbering": {
1388
                String old = env.processor.GetProperty(Feature<string>.DEFAULT_LANGUAGE);
1389
                if (!value.Equals(old)) {
1390
                    env.processor.SetProperty(Feature<string>.DEFAULT_LANGUAGE, value);
1391
                    env.resetActions.Add(envi => 
1392
                        {
1393
                            env.processor.SetProperty(Feature<string>.DEFAULT_LANGUAGE, old);
1394
                        }
1395
                    );
1396
                }
1397
                return true;
1398
            }
1399
            case "enable_assertions": {
1400
                bool on = !inverse;
1401
                bool old = env.xsltCompiler.AssertionsEnabled;
1402
                env.xsltCompiler.AssertionsEnabled = on;
1403
                env.resetActions.Add(envi =>
1404
                {
1405
                    env.xsltCompiler.AssertionsEnabled = old;
1406
                });
1407
                return true;
1408
            }
1409
            case "extension-function":
1410
               /* if (value.Equals("Q{http://relaxng.org/ns/structure/1.0}schema-report#1")) {
1411
                    try {
1412
                        Configuration config = env.processor.getUnderlyingConfiguration();
1413
Object sf = config.getInstance("net.cfoster.saxonjing.SchemaFunction", null);
1414
env.processor.registerExtensionFunction((ExtensionFunctionDefinition) sf);
1415
                        Object sfd = config.getInstance("net.cfoster.saxonjing.SchemaReportFunction", null);
1416
env.processor.registerExtensionFunction((ExtensionFunctionDefinition) sfd);
1417
                        return true;
1418
                    } catch (XPathException err) {
1419
                        System.err.println("Failed to load Saxon-Jing extension functions");
1420
                        return false;
1421
                    }
1422
                }*/
1423
                return false;
1424
            case "year_component_values":
1425
                if ("support year zero".Equals(value)) {
1426
                    if (env != null) {
1427
                        env.processor.SetProperty(Feature<string>.XSD_VERSION, inverse? "1.0" : "1.1");
1428
                        return true;
1429
                    } else {
1430
                        return false;
1431
                    }
1432
                }
1433
                return !inverse;
1434
            case "additional_normalization_form":
1435
                if ("support FULLY-NORMALIZED".Equals(value)) {
1436
                    return inverse;
1437
                }
1438
                return !inverse;
1439

    
1440
            case "on-multiple-match":
1441
                throw new Exception("on-multiple-match is no longer recognized");
1442
//                env.resetActions.add(new Environment.ResetAction() {
1443
//                    @Override
1444
//                    public void reset(Environment env) {
1445
//                        env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Mode.RECOVER_WITH_WARNINGS);
1446
//                    }
1447
//                });
1448
//                if ("error".Equals(value)) {
1449
//                    env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Mode.DO_NOT_RECOVER);
1450
//                } else {
1451
//                    env.xsltCompiler.getUnderlyingCompilerInfo().setRecoveryPolicy(Mode.RECOVER_SILENTLY);
1452
//                }
1453
//                return true;
1454

    
1455
            case "ignore_doc_failure":
1456
                return inverse;
1457

    
1458
            case "combinations_for_numbering":
1459
                if (value.Equals("COPTIC EPACT DIGIT ONE") || value.Equals("SINHALA ARCHAIC DIGIT ONE") || value.Equals("MENDE KIKAKUI DIGIT ONE")) {
1460
                    return false;
1461
                }
1462
                return !inverse;
1463

    
1464
            case "xsd-version":
1465
                return env.processor.Edition.Equals("HE") ? false : true;
1466

    
1467
            case "sweep_and_posture":
1468
                return env.processor.Edition.Equals("HE") ? inverse : true;
1469

    
1470
            case "unicode-version":
1471
                return value.Equals("6.0"); // Avoid running Unicode 9.0 tests - they are slow!
1472

    
1473
            case "default_html_version": {
1474
                return value.Equals("5");
1475
            }
1476

    
1477
            default:
1478
                println("**** dependency not recognized for HE: " + type);
1479
                return false;
1480
        }
1481

    
1482

    
1483

    
1484
            if ("spec".Equals(type))
1485
            {
1486
                bool atLeast = value.EndsWith("+");
1487
                value = value.Replace("+", "");
1488

    
1489
                String specName = ((SpecAttr)spec.GetAttr()).svname.Replace("XT", "XSLT");
1490
                int order = value.CompareTo(specName);
1491
                return atLeast ? order <= 0 : order == 0;
1492
            }
1493
            else if ("feature".Equals(type))
1494
            {
1495
                //            <xs:enumeration value="backwards_compatibility" />
1496
                //            <xs:enumeration value="disabling_output_escaping" />
1497
                //            <xs:enumeration value="schema_aware" />
1498
                //            <xs:enumeration value="namespace_axis" />
1499
                //            <xs:enumeration value="streaming" />
1500
                //            <xs:enumeration value="XML_1.1" />
1501

    
1502
                if ("XML_1.1".Equals(value) && !inverse)
1503
                {
1504
                    if (env != null)
1505
                    {
1506
                        env.processor.XmlVersion = (decimal)1.1;
1507
                        return true;
1508
                    }
1509
                    else
1510
                    {
1511
                        return false;
1512
                    }
1513
                }
1514
                else if ("disabling_output_escaping".Equals(value))
1515
                {
1516
                    return !inverse;
1517
                }
1518
                else if ("schema_aware".Equals(value))
1519
                {
1520
                    if (!env.xsltCompiler.SchemaAware)
1521
                    {
1522
                        return false; // cannot use the selected tree model for schema-aware tests
1523
                    }
1524
                    if (env != null)
1525
                    {
1526
                        env.xsltCompiler.SchemaAware = !inverse;
1527
                    }
1528
                    return true;
1529
                }
1530
                else if ("namespace_axis".Equals(value))
1531
                {
1532
                    return !inverse;
1533
                }
1534
                else if ("streaming".Equals(value))
1535
                {
1536
                    return !inverse;
1537
                }
1538
                else if ("backwards_compatibility".Equals(value))
1539
                {
1540
                    return !inverse;
1541
                }
1542
                return false;
1543
            }
1544
            else if ("xsd-version".Equals(type))
1545
            {
1546
                if ("1.1".Equals(value))
1547
                {
1548
                    if (env != null)
1549
                    {
1550
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.0" : "1.1"));
1551
                    }
1552
                    else
1553
                    {
1554
                        return false;
1555
                    }
1556
                }
1557
                else if ("1.0".Equals(value))
1558
                {
1559
                    if (env != null)
1560
                    {
1561
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.1" : "1.0"));
1562
                    }
1563
                    else
1564
                    {
1565
                        return false;
1566
                    }
1567
                }
1568
                return true;
1569
            }
1570
            else if ("available_documents".Equals(type))
1571
            {
1572
                return !inverse;
1573
            }
1574
            else if ("default_language_for_numbering".Equals(type))
1575
            {
1576
                return !inverse;
1577
            }
1578
            else if ("languages_for_numbering".Equals(type))
1579
            {
1580
                return !inverse;
1581
            }
1582
            else if ("supported_calendars_in_date_formatting_functions".Equals(type))
1583
            {
1584
                return !inverse;
1585
            }
1586
            else if ("default_calendar_in_date_formatting_functions".Equals(type))
1587
            {
1588
                return !inverse;
1589
            }
1590
            else if ("maximum_number_of_decimal_digits".Equals(type))
1591
            {
1592
                return !inverse;
1593
                //        } else if ("collation_uri".Equals(type)) {
1594
                //            return !inverse;
1595
                //        } else if ("statically_known_collations".Equals(type)) {
1596
                //            if (value.Equals("http://www.w3.org/xslts/collation/caseblind") && !inverse) {
1597
                //                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
1598
                //                        new StandardCollationURIResolver() {
1599
                //                            public stringCollator resolve(string uri, string base, Configuration config) {
1600
                //                                if ("http://www.w3.org/xslts/collation/caseblind".Equals(uri)) {
1601
                //                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
1602
                //                                } else {
1603
                //                                    return super.resolve(uri, base, config);
1604
                //                                }
1605
                //                            }
1606
                //                        }
1607
                //                );
1608
                //            }
1609
                //            // Alternative case-blind collation URI used in QT3 tests
1610
                //            if (value.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") && !inverse) {
1611
                //                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
1612
                //                        new StandardCollationURIResolver() {
1613
                //                            public stringCollator resolve(string uri, string base, Configuration config) {
1614
                //                                if ("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind".Equals(uri)) {
1615
                //                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
1616
                //                                } else {
1617
                //                                    return super.resolve(uri, base, config);
1618
                //                                }
1619
                //                            }
1620
                //                        }
1621
                //                );
1622
                //            }
1623
                //            return true;
1624
            }
1625
            else if ("default_output_encoding".Equals(type))
1626
            {
1627
                return !inverse;
1628
            }
1629
            else if ("unparsed_text_encoding".Equals(type))
1630
            {
1631
                return !inverse;
1632
            }
1633
            else if ("additional_normalization_form".Equals(type))
1634
            {
1635
                return !inverse;
1636
            }
1637
            else if ("recognize_id_as_uri_fragment".Equals(type))
1638
            {
1639
                return !inverse;
1640
            }
1641
            else if ("on-multiple-match".Equals(type))
1642
            {
1643
                throw new Exception("on-muplte-match is no longer recognized");
1644
                /*if (value.Equals("error"))
1645
                {
1646
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.DoNotRecover);
1647
                }
1648
                else
1649
                {
1650
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.RecoverSilently);
1651
                }
1652
                return true; */
1653
            }
1654
            else if ("ignore_doc_failure".Equals(type))
1655
            {
1656
                return inverse;
1657
            }
1658
            else if ("combinations_for_numbering".Equals(type))
1659
            {
1660
                if (value.Equals("COPTIC EPACT DIGIT ONE") || value.Equals("SINHALA ARCHAIC DIGIT ONE") || value.Equals("MENDE KIKAKUI DIGIT ONE")) {
1661
                    return false;
1662
                }
1663
                return !inverse;
1664
            }
1665
            else if ("higher_order_functions".Equals(type))
1666
            {
1667
                return !inverse;
1668

    
1669
            }
1670
            else if ("ignore_doc_failure".Equals(type))
1671
            {
1672
                //TODO
1673
                return false;
1674

    
1675
            }
1676
            else if ("simple-uca-fallback".Equals(type))
1677
            {
1678
                return !inverse;
1679

    
1680
            }
1681
            else if ("advanced-uca-fallback".Equals(type))
1682
            {
1683
                return !inverse;
1684

    
1685
            }
1686
            else if ("streaming-fallback".Equals(type))
1687
            {
1688
                bool required = !inverse;
1689
                bool old = env.processor.GetProperty(FeatureKeys.STREAMING_FALLBACK) == "true" || env.processor.GetProperty(FeatureKeys.STREAMING_FALLBACK) == "on";
1690
                if (old != required)
1691
                {
1692
                    env.processor.SetProperty<bool>(Feature<bool>.STREAMING_FALLBACK, required);
1693
                }
1694

    
1695
                return true;
1696
            }
1697
            else if ("sweep_and_posture".Equals(type))
1698
            {
1699
                return !inverse;
1700
            }
1701
            else if ("unicode_version".Equals(type))
1702
            {
1703
                return value.Equals("6.0");
1704
            }
1705
            else if ("enable_assertions".Equals(type))
1706
            {
1707
                return false;
1708
            }
1709
            else if ("year_component_values".Equals(type))
1710
            {
1711
                if ("support year zero".Equals(value)) {
1712
                    if (env != null)
1713
                    {
1714
                        env.processor.SetProperty<String>(Feature<String>.XSD_VERSION, inverse ? "1.0" : "1.1");
1715
                    }
1716
                    else {
1717
                        return false;
1718
                    }
1719

    
1720
                }
1721
                return !inverse;
1722

    
1723
            }
1724
            else
1725
            {
1726
                println("**** dependency not recognized: " + type);
1727
                return false;
1728
            }
1729
    }
1730

    
1731
    /*private static string getCanonicalPath(File file) {
1732
        try {
1733
            return file.getCanonicalPath();
1734
        } catch (IOException err) {
1735
            return file.getAbsolutePath();
1736
        }
1737
    }*/
1738

    
1739
    private static QName getQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath)  {
1740
        string exp = "for $att in " + attributePath +
1741
                " return if (contains($att, ':')) then resolve-QName($att, $att/..) else QName('', $att)";
1742
        XdmAtomicValue qname = (XdmAtomicValue) xpath.EvaluateSingle(exp, contextItem);
1743
        return (qname == null ? null : (QName) qname.Value);
1744
    }
1745

    
1746
    internal class OutputResolver : net.sf.saxon.lib.OutputURIResolver{
1747

    
1748
        private Processor proc;
1749
        private TestOutcome outcome;
1750
        private XdmDestination destination;
1751
        private java.io.StringWriter stringWriter;
1752
        bool serialized;
1753
        Uri uri;
1754

    
1755
        public OutputResolver(Processor proc, TestOutcome outcome, bool serialized) {
1756
            this.proc = proc;
1757
            this.outcome = outcome;
1758
            this.serialized = serialized;
1759
        }
1760

    
1761
        public net.sf.saxon.lib.OutputURIResolver newInstance()
1762
        {
1763
            return new OutputResolver(proc, outcome, serialized);
1764
        }
1765
         XmlUrlResolver res = new XmlUrlResolver();
1766
         public JResult resolve(string href, string base1)
1767
         {
1768
            try {
1769
                uri = res.ResolveUri(new Uri(base1), href);
1770
                if (serialized) {
1771
                  
1772
                    stringWriter = new java.io.StringWriter();
1773
                    javax.xml.transform.stream.StreamResult result =  new javax.xml.transform.stream.StreamResult(stringWriter);
1774
                    result.setSystemId(uri.ToString());
1775
                    return result; 
1776
                } else {
1777
                    destination = new XdmDestination();
1778
                    ((XdmDestination)destination).BaseUri = uri;
1779
                        return null;//  destination..GetReceiver(proc.Implementation.makePipelineConfiguration());
1780
                }
1781
            } catch (Exception e) {
1782
                throw e;
1783
            }
1784
        }
1785

    
1786
        public void close(JResult result) {
1787
            if (serialized) {
1788
                outcome.SetSecondaryResult(uri, null, stringWriter.ToString(), proc);
1789
            } else {
1790
                XdmDestination xdm = (XdmDestination)destination;
1791
                outcome.SetSecondaryResult(xdm.BaseUri, xdm.XdmNode, null, proc);
1792
            }
1793
        }
1794

    
1795
    }
1796

    
1797

    
1798

    
1799
}
1800

    
1801
    public class ModuleResolver : IQueryResolver
1802
    {
1803

    
1804
        XQueryCompiler catXQC;
1805
        XdmNode testCase;
1806
        TestDriver driver = null;
1807

    
1808
        public ModuleResolver(XQueryCompiler xqc, TestDriver driveri)
1809
        {
1810
            this.catXQC = xqc;
1811
            driver = driveri;
1812
        }
1813

    
1814
        public void setTestCase(XdmNode testCase)
1815
        {
1816
            this.testCase = testCase;
1817
        }
1818

    
1819

    
1820
        public Object GetEntity(Uri absoluteUri)
1821
        {
1822
            FileStream stream = null;
1823
            try
1824
            {
1825
                stream =  new FileStream(driver.queryModules[absoluteUri], FileMode.Open, FileAccess.Read);
1826
            }
1827
            catch (Exception ex) {
1828
                return null;
1829
            }
1830
            return stream;
1831
        }
1832

    
1833
        internal Uri resolve(Uri basei, String child)
1834
        {
1835

    
1836
            return (new XmlUrlResolver()).ResolveUri(testCase.BaseUri, child);
1837

    
1838

    
1839
        }
1840

    
1841

    
1842
        public Uri[] GetModules(String moduleUri, Uri baseUri, String[] locationHints)
1843
        {
1844
            //  XdmValue files = catXPC.Evaluate("./module[@uri='" + moduleUri + "']/@file/string()", testCase);
1845
            /*if (files.Count == 0)
1846
            {
1847
                throw new Exception("Failed to find module entry for " + moduleUri);
1848
            }*/
1849
            XmlUrlResolver res = new XmlUrlResolver();
1850
            
1851
            Uri[] fullPaths = new Uri[1];
1852

    
1853
            try
1854
            {
1855
                fullPaths[0] = res.ResolveUri(baseUri, moduleUri);
1856
            }
1857
            catch (Exception e) {
1858
                return null;
1859
            }
1860

    
1861
            return fullPaths;
1862
        }
1863

    
1864
        
1865
    }
1866
}
(18-18/19)