summaryrefslogtreecommitdiff
path: root/mcs/class/System.XML/Mono.Xml.Xsl/XslTransformProcessor.cs
blob: a4a8f6c602e1c082dd57c7136107ce0d39411335 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//
// XslTransformProcessor.cs
//
// Authors:
//	Ben Maurer (bmaurer@users.sourceforge.net)
//	Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//	
// (C) 2003 Ben Maurer
// (C) 2003 Atsushi Enomoto
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Mono.Xml.Xsl.Operations;
using Mono.Xml.XPath;

using QName = System.Xml.XmlQualifiedName;

namespace Mono.Xml.Xsl {
	internal class XslTransformProcessor {
		XsltDebuggerWrapper debugger;
		
		CompiledStylesheet compiledStyle;
		
		XslStylesheet style;
		
		Stack currentTemplateStack = new Stack ();
		
		XPathNavigator root;
		XsltArgumentList args;
		XmlResolver resolver;
//		bool outputStylesheetXmlns;
		string currentOutputUri;
		
		internal readonly XsltCompiledContext XPathContext;

		// Store the values of global params
		internal Hashtable globalVariableTable = new Hashtable ();
		
		public XslTransformProcessor (CompiledStylesheet style, object debugger)
		{
			this.XPathContext = new XsltCompiledContext (this);
			this.compiledStyle = style;
			this.style = style.Style;
			if (debugger != null)
				this.debugger = new XsltDebuggerWrapper (debugger);
		}

		public void Process (XPathNavigator root, Outputter outputtter, XsltArgumentList args, XmlResolver resolver)
		{
			this.args = args;
			this.root = root;
			this.resolver = resolver != null ? resolver : new XmlUrlResolver ();
//			this.outputStylesheetXmlns = true;
			this.currentOutputUri = String.Empty;

			PushNodeset (new SelfIterator (root, this.XPathContext));
CurrentNodeset.MoveNext ();
			
			// have to evaluate the params first, as Global vars may
			// be dependant on them
			if (args != null)
			{
				foreach (XslGlobalVariable v in CompiledStyle.Variables.Values)
				{
					if (v is XslGlobalParam)
					{
						object p = args.GetParam(v.Name.Name, v.Name.Namespace);
						if (p != null)
							((XslGlobalParam)v).Override (this, p);

						v.Evaluate (this);
					}
				}
			}

			foreach (XslGlobalVariable v in CompiledStyle.Variables.Values)	{
				if (args == null || !(v is XslGlobalParam)) {
					v.Evaluate (this);
				}
			}
			
			PopNodeset ();
			
			this.PushOutput (outputtter);
			this.ApplyTemplates (new SelfIterator (root, this.XPathContext), QName.Empty, null);
			this.PopOutput ();
		}

		public XsltDebuggerWrapper Debugger {
			get { return debugger; }
		}

		public CompiledStylesheet CompiledStyle { get { return compiledStyle; }}
		public XsltArgumentList Arguments {get{return args;}}

		public XPathNavigator Root { get { return root; } }

		public MSXslScriptManager ScriptManager {
			get { return compiledStyle.ScriptManager; }
		}

		#region Document Resolution
		public XmlResolver Resolver {get{return resolver;}}
		
		Hashtable docCache;
		
		public XPathNavigator GetDocument (Uri uri)
		{
			XPathNavigator result;
			
			if (docCache != null) {
				result = docCache [uri] as XPathNavigator;
				if (result != null)
					return result.Clone();
			} else {
				docCache = new Hashtable();
			}

			XmlReader rdr = null;
			try {
				rdr = new XmlTextReader (uri.ToString(), (Stream) resolver.GetEntity (uri, null, null), root.NameTable);
				XmlValidatingReader xvr = new XmlValidatingReader (rdr);
				xvr.ValidationType = ValidationType.None;
				result = new XPathDocument (xvr, XmlSpace.Preserve).CreateNavigator ();
			} finally {
				if (rdr != null)
					rdr.Close ();
			}
			docCache [uri] = result.Clone ();
			return result;
		}
		
		#endregion
		
		#region Output
		Stack outputStack = new Stack ();
		
		public Outputter Out { get { return (Outputter)outputStack.Peek(); }}
		
		public void PushOutput (Outputter newOutput)
		{
			this.outputStack.Push (newOutput);
		}
		
		public Outputter PopOutput ()
		{
			Outputter ret = (Outputter)this.outputStack.Pop ();
			ret.Done ();
			return ret;
		}
		
		public Hashtable Outputs { get { return compiledStyle.Outputs; }}

		public XslOutput Output { get { return Outputs [currentOutputUri] as XslOutput; } }

		public string CurrentOutputUri { get { return currentOutputUri; } }

		public bool InsideCDataElement { get { return this.XPathContext.IsCData; } }
		#endregion
		
		#region AVT StringBuilder
		StringBuilder avtSB;
	
		#if DEBUG
		bool avtSBlock = false;
		#endif
	
		public StringBuilder GetAvtStringBuilder ()
		{
			#if DEBUG
				if (avtSBlock)
					throw new XsltException ("String Builder was locked", null);
				avtSBlock = true;
			#endif
			
			if (avtSB == null)
				avtSB = new StringBuilder ();
			
			return avtSB;
		}
		
		public string ReleaseAvtStringBuilder ()
		{
			#if DEBUG
				if (!avtSBlock)
					throw new XsltException ("you never locked the string builder", null);
				avtSBlock = false;
			#endif
			
			string ret = avtSB.ToString ();
			avtSB.Length = 0;
			return ret;
		}
		#endregion
		
		#region Templates -- Apply/Call
		Stack paramPassingCache = new Stack ();
		
		Hashtable GetParams (ArrayList withParams)
		{
			if (withParams == null) return null;
			Hashtable ret;
			
			if (paramPassingCache.Count != 0) {
				ret = (Hashtable)paramPassingCache.Pop ();
				ret.Clear ();
			} else
				ret = new Hashtable ();
			
			int len = withParams.Count;
			for (int i = 0; i < len; i++) {
				XslVariableInformation param = (XslVariableInformation)withParams [i];
				ret.Add (param.Name, param.Evaluate (this));
			}
			return ret;
		}
		
		public void ApplyTemplates (XPathNodeIterator nodes, QName mode, ArrayList withParams)
		{

			Hashtable passedParams = GetParams (withParams);
			
			while (NodesetMoveNext (nodes)) {
				PushNodeset (nodes);
				XslTemplate t = FindTemplate (CurrentNode, mode);
				currentTemplateStack.Push (t);
				t.Evaluate (this, passedParams);
				currentTemplateStack.Pop ();
				PopNodeset ();
			}
			
			if (passedParams != null) paramPassingCache.Push (passedParams);
		}
		
		public void CallTemplate (QName name, ArrayList withParams)
		{
			Hashtable passedParams = GetParams (withParams);
			
			XslTemplate t = FindTemplate (name);
			currentTemplateStack.Push (null);
			t.Evaluate (this, passedParams);
			currentTemplateStack.Pop ();
			
			if (passedParams != null) paramPassingCache.Push (passedParams);
		}
		
		public void ApplyImports ()
		{	

			XslTemplate currentTemplate = (XslTemplate)currentTemplateStack.Peek();
			if (currentTemplate == null)
				throw new XsltException ("Invalid context for apply-imports", null, CurrentNode);
			XslTemplate t;
			
			for (int i = currentTemplate.Parent.Imports.Count - 1; i >= 0; i--) {
				XslStylesheet s = (XslStylesheet)currentTemplate.Parent.Imports [i];
				t = s.Templates.FindMatch (CurrentNode, currentTemplate.Mode, this);
				if (t != null) {					
					currentTemplateStack.Push (t);
					t.Evaluate (this);
					currentTemplateStack.Pop ();
					return;
				}
			}
			
			switch (CurrentNode.NodeType) {
			case XPathNodeType.Root:
			case XPathNodeType.Element:
				if (currentTemplate.Mode == QName.Empty)
					t = XslDefaultNodeTemplate.Instance;
				else
					t = new XslDefaultNodeTemplate(currentTemplate.Mode);
			
				break;
			case XPathNodeType.Attribute:
			case XPathNodeType.SignificantWhitespace:
			case XPathNodeType.Text:
			case XPathNodeType.Whitespace:
				t = XslDefaultTextTemplate.Instance;
				break;
			
			case XPathNodeType.Comment:
			case XPathNodeType.ProcessingInstruction:
				t = XslEmptyTemplate.Instance;
				break;
			
			default:
				t = XslEmptyTemplate.Instance;
				break;
			}
			currentTemplateStack.Push (t);
			t.Evaluate (this);
			currentTemplateStack.Pop ();
		}

		// Outputs Literal namespace nodes described in spec 7.7.1
		internal void OutputLiteralNamespaceUriNodes (Hashtable nsDecls, ArrayList excludedPrefixes, string localPrefixInCopy)
		{
			if (nsDecls == null)
				return;

			foreach (DictionaryEntry cur in nsDecls) {
				string name = (string)cur.Key;
				string value = (string)cur.Value;

				// See XSLT 1.0 errata E25
				if (localPrefixInCopy == name)
					continue;
				if (localPrefixInCopy != null &&
					name.Length == 0 &&
					XPathContext.ElementNamespace.Length == 0)
					continue;

				// exclude-result-prefixes, see the spec 7.1.1
				bool skip = false;
				if (style.ExcludeResultPrefixes != null) {
					foreach (XmlQualifiedName exc in style.ExcludeResultPrefixes) {
						if (exc.Namespace == value) {
							skip = true;
							continue;
						}
					}
				}
				if (skip)
					continue;

				if (style.NamespaceAliases [name] != null)
					continue;

				switch (value) {//FIXME: compare names by reference
				case "http://www.w3.org/1999/XSL/Transform":
//					if ("xsl" == name)
						continue;
//					else
//						goto default;
				case XmlNamespaceManager.XmlnsXml:
					if (XmlNamespaceManager.PrefixXml == name)
						continue;
					else
						goto default;
				case XmlNamespaceManager.XmlnsXmlns:
					if (XmlNamespaceManager.PrefixXmlns == name)
						continue;
					else
						goto default;
				default:
					if (excludedPrefixes == null || !excludedPrefixes.Contains (name))
						Out.WriteNamespaceDecl (name, value);
					break;
				}
			}
		}

		XslTemplate FindTemplate (XPathNavigator node, QName mode)
		{
			XslTemplate ret = style.Templates.FindMatch (CurrentNode, mode, this);
			
			if (ret != null) return ret;

			switch (node.NodeType) {
			case XPathNodeType.Root:
			case XPathNodeType.Element:
				if (mode == QName.Empty)
					return XslDefaultNodeTemplate.Instance;
				else
					return new XslDefaultNodeTemplate(mode);
			
			case XPathNodeType.Attribute:
			case XPathNodeType.SignificantWhitespace:
			case XPathNodeType.Text:
			case XPathNodeType.Whitespace:
				return XslDefaultTextTemplate.Instance;
			
			case XPathNodeType.Comment:
			case XPathNodeType.ProcessingInstruction:
				return XslEmptyTemplate.Instance;
			
			default:
				return XslEmptyTemplate.Instance;
			}
		}
		
		XslTemplate FindTemplate (QName name)
		{
			XslTemplate ret = style.Templates.FindTemplate (name);
			if (ret != null) return ret;
				
			throw new XsltException ("Could not resolve named template " + name, null, CurrentNode);
		}
		
		#endregion

		public void PushForEachContext ()
		{
			currentTemplateStack.Push (null);
		}
		
		public void PopForEachContext ()
		{
			currentTemplateStack.Pop ();
		}
		

		#region Nodeset Context
		ArrayList nodesetStack = new ArrayList ();
		
		public XPathNodeIterator CurrentNodeset {
			get { return (XPathNodeIterator) nodesetStack [nodesetStack.Count - 1]; }
		}
		
		public XPathNavigator CurrentNode {
			get {
				XPathNavigator nav = CurrentNodeset.Current;
				if (nav != null)
					return nav;
				// Inside for-each context, CurrentNodeset.Current may be null
				for (int i = nodesetStack.Count - 2; i >= 0; i--) {
					nav = ((XPathNodeIterator) nodesetStack [i]).Current;
					if (nav != null)
						return nav;
				}
				return null;
			}
		}
		
		public bool NodesetMoveNext ()
		{
			return NodesetMoveNext (CurrentNodeset);
		}

		public bool NodesetMoveNext (XPathNodeIterator iter)
		{
			if (!iter.MoveNext ())
				return false;
			// FIXME: this check should not be required.
			// Since removal of this check causes some regressions,
			// there should be some wrong assumption on our
			// BaseIterator usage. Actually BaseIterator should
			// not do whitespace check and every PreserveWhitespace
			// evaluation in XslTransform should be done at
			// different level. One possible solution is to wrap
			// the input XmlReader by a new XmlReader that takes
			// whitespace stripping into consideration.
			if (iter.Current.NodeType == XPathNodeType.Whitespace && !XPathContext.PreserveWhitespace (iter.Current))
				return NodesetMoveNext (iter);
			return true;
		}

		public void PushNodeset (XPathNodeIterator itr)
		{
			BaseIterator bi = itr as BaseIterator;
			bi = bi != null ? bi : new WrapperIterator (itr, null);
			bi.NamespaceManager = XPathContext;
			nodesetStack.Add (bi);
		}
		
		public void PopNodeset ()
		{
			nodesetStack.RemoveAt (nodesetStack.Count - 1);
		}
		#endregion
		
		#region Evaluate
		
		public bool Matches (Pattern p, XPathNavigator n)
		{
			return p.Matches (n, this.XPathContext);
		}
		
		public object Evaluate (XPathExpression expr)
		{
			XPathNodeIterator itr = CurrentNodeset;
			BaseIterator bi = (BaseIterator) itr;
			CompiledExpression cexpr = (CompiledExpression) expr;
			if (bi.NamespaceManager == null)
				bi.NamespaceManager = cexpr.NamespaceManager;
			return cexpr.Evaluate (bi);
		}
		
		public string EvaluateString (XPathExpression expr)
		{
			XPathNodeIterator itr = CurrentNodeset;
#if true
			return itr.Current.EvaluateString (expr, itr, XPathContext);
#else
			BaseIterator bi = (BaseIterator) itr;
			CompiledExpression cexpr = (CompiledExpression) expr;
			if (bi.NamespaceManager == null)
				bi.NamespaceManager = cexpr.NamespaceManager;
			return cexpr.EvaluateString (bi);
#endif
		}
				
		public bool EvaluateBoolean (XPathExpression expr)
		{
			XPathNodeIterator itr = CurrentNodeset;
#if true
			return itr.Current.EvaluateBoolean (expr, itr, XPathContext);
#else
			BaseIterator bi = (BaseIterator) itr;
			CompiledExpression cexpr = (CompiledExpression) expr;
			if (bi.NamespaceManager == null)
				bi.NamespaceManager = cexpr.NamespaceManager;
			return cexpr.EvaluateBoolean (bi);
#endif
		}
		
		public double EvaluateNumber (XPathExpression expr)
		{
			XPathNodeIterator itr = CurrentNodeset;
#if true
			return itr.Current.EvaluateNumber (expr, itr, XPathContext);
#else
			BaseIterator bi = (BaseIterator) itr;
			CompiledExpression cexpr = (CompiledExpression) expr;
			if (bi.NamespaceManager == null)
				bi.NamespaceManager = cexpr.NamespaceManager;
			return cexpr.EvaluateNumber (bi);
#endif
		}
		
		public XPathNodeIterator Select (XPathExpression expr)
		{
#if true
			return CurrentNodeset.Current.Select (expr, XPathContext);
#else
			BaseIterator bi = (BaseIterator) CurrentNodeset;
			CompiledExpression cexpr = (CompiledExpression) expr;
			if (bi.NamespaceManager == null)
				bi.NamespaceManager = cexpr.NamespaceManager;
			return cexpr.EvaluateNodeSet (bi);
#endif
		}
		
		#endregion
		
		public XslAttributeSet ResolveAttributeSet (QName name)
		{
			return CompiledStyle.ResolveAttributeSet (name);
		}
		
		#region Variable Stack
		Stack variableStack = new Stack ();
		object [] currentStack;
		public int StackItemCount {
			get {
				if (currentStack == null)
				      return 0;
				for (int i = 0; i < currentStack.Length; i++)
					if (currentStack [i] == null)
						return i;
				return currentStack.Length;
			}
		}

		public object GetStackItem (int slot)
		{
			return currentStack [slot];
		}
		
		public void SetStackItem (int slot, object o)
		{
			currentStack [slot] = o;
		}
		
		public void PushStack (int stackSize)
		{
			variableStack.Push (currentStack);
			currentStack = new object [stackSize];
		}
		
		public void PopStack ()
		{
			currentStack = (object[])variableStack.Pop();
		}
		
		#endregion
		
		#region Free/Busy
		Hashtable busyTable = new Hashtable ();
		static object busyObject = new object ();
		
		public void SetBusy (object o)
		{
			busyTable [o] = busyObject;
		}
		
		public void SetFree (object o)
		{
			busyTable.Remove (o);
		}
		
		public bool IsBusy (object o)
		{
			return busyTable [o] == busyObject;
		}
		#endregion

		public bool PushElementState (string prefix, string name, string ns, bool preserveWhitespace)
		{
			bool b = IsCData (name, ns);
			XPathContext.PushScope ();
			Out.InsideCDataSection = XPathContext.IsCData = b;
			XPathContext.WhitespaceHandling = true;//preserveWhitespace;
			XPathContext.ElementPrefix = prefix;
			XPathContext.ElementNamespace = ns;
			return b;
		}

		bool IsCData (string name, string ns)
		{
			for (int i = 0; i < Output.CDataSectionElements.Length; i++) {
				XmlQualifiedName qname = Output.CDataSectionElements [i];
				if (qname.Name == name && qname.Namespace == ns) {
					return true;
				}
			}
			return false;
		}

		public void PopCDataState (bool isCData)
		{
			XPathContext.PopScope ();
			Out.InsideCDataSection = XPathContext.IsCData;
		}

		public bool PreserveOutputWhitespace {
			get { return XPathContext.Whitespace; }
		}
	}
}