Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AspGenerator.cs « System.Web.Compilation « System.Web « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5c6496904d7693281c10ea1ced6c9a81a41327ca (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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//
// System.Web.Compilation.AspGenerator
//
// Authors:
//	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
// Copyright (c) 2004,2006 Novell, Inc (http://www.novell.com)
//

//
// 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.Collections;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.Util;

namespace System.Web.Compilation
{
	class BuilderLocation
	{
		public ControlBuilder Builder;
		public ILocation Location;

		public BuilderLocation (ControlBuilder builder, ILocation location)
		{
			this.Builder = builder;
			this.Location = location;
		}
	}

	class BuilderLocationStack : Stack
	{
		public override void Push (object o)
		{
			if (!(o is BuilderLocation))
				throw new InvalidOperationException ();

			base.Push (o);
		}
		
		public virtual void Push (ControlBuilder builder, ILocation location)
		{
			BuilderLocation bl = new BuilderLocation (builder, location);
			Push (bl);
		}

		public new BuilderLocation Peek ()
		{
			return (BuilderLocation) base.Peek ();
		}

		public new BuilderLocation Pop ()
		{
			return (BuilderLocation) base.Pop ();
		}

		public ControlBuilder Builder {
			get { return Peek ().Builder; }
		}
	}

	class ParserStack
	{
		Hashtable files;
		Stack parsers;
		AspParser current;

		public ParserStack ()
		{
			files = new Hashtable (); // may be this should be case sensitive for windows
			parsers = new Stack ();
		}
		
		public bool Push (AspParser parser)
		{
			if (files.Contains (parser.Filename))
				return false;

			files [parser.Filename] = true;
			parsers.Push (parser);
			current = parser;
			return true;
		}

		public AspParser Pop ()
		{
			if (parsers.Count == 0)
				return null;

			files.Remove (current.Filename);
			AspParser result = (AspParser) parsers.Pop ();
			if (parsers.Count > 0)
				current = (AspParser) parsers.Peek ();
			else
				current = null;

			return result;
		}
		
		public AspParser Parser {
			get { return current; }
		}

		public string Filename {
			get { return current.Filename; }
		}
	}

	class TagStack
	{
		Stack tags;

		public TagStack ()
		{
			tags = new Stack ();
		}
		
		public void Push (string tagid)
		{
			tags.Push (tagid);
		}

		public string Pop ()
		{
			if (tags.Count == 0)
				return null;

			return (string) tags.Pop ();
		}

		public bool CompareTo (string tagid)
		{
			if (tags.Count == 0)
				return false;

			return 0 == String.Compare (tagid, (string) tags.Peek (), true);
		}
		
		public int Count {
			get { return tags.Count; }
		}

		public string Current {
			get { return (string) tags.Peek (); }
		}
	}

	class AspGenerator
	{
		ParserStack pstack;
		BuilderLocationStack stack;
		TemplateParser tparser;
		StringBuilder text;
		RootBuilder rootBuilder;
		bool inScript, javascript, ignore_text;
		ILocation location;
		bool isApplication;
		StringBuilder tagInnerText = new StringBuilder ();
		static Hashtable emptyHash = new Hashtable ();
		bool inForm;
		bool useOtherTags;

		public AspGenerator (TemplateParser tparser)
		{
			this.tparser = tparser;
			text = new StringBuilder ();
			stack = new BuilderLocationStack ();
			rootBuilder = new RootBuilder (tparser);
			stack.Push (rootBuilder, null);
			tparser.RootBuilder = rootBuilder;
			pstack = new ParserStack ();
		}

		public AspParser Parser {
			get { return pstack.Parser; }
		}
		
		public string Filename {
			get { return pstack.Filename; }
		}
		
		BaseCompiler GetCompilerFromType ()
		{
			Type type = tparser.GetType ();
			if (type == typeof (PageParser))
				return new PageCompiler ((PageParser) tparser);

			if (type == typeof (ApplicationFileParser))
				return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);

			if (type == typeof (UserControlParser))
				return new UserControlCompiler ((UserControlParser) tparser);
#if NET_2_0
			if (type == typeof(MasterPageParser))
				return new UserControlCompiler ((UserControlParser) tparser);
#endif

			throw new Exception ("Got type: " + type);
		}
		
		void InitParser (string filename)
		{
			StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
			AspParser parser = new AspParser (filename, reader);
			reader.Close ();
			parser.Error += new ParseErrorHandler (ParseError);
			parser.TagParsed += new TagParsedHandler (TagParsed);
			parser.TextParsed += new TextParsedHandler (TextParsed);
			if (!pstack.Push (parser))
				throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
			tparser.AddDependency (filename);
		}

		void DoParse ()
		{
			pstack.Parser.Parse ();
			if (text.Length > 0)
				FlushText ();

			pstack.Pop ();
		}

		public Type GetCompiledType ()
		{
			Type type = (Type) HttpRuntime.Cache.Get ("@@Type" + tparser.InputFile);
			if (type != null) {
				return type;
			}

			isApplication = tparser.DefaultDirectiveName == "application";
			InitParser (Path.GetFullPath (tparser.InputFile));

			DoParse ();
#if DEBUG
			PrintTree (rootBuilder, 0);
#endif

			if (stack.Count > 1)
				throw new ParseException (stack.Builder.location,
						"Expecting </" + stack.Builder.TagName + "> " + stack.Builder);

			BaseCompiler compiler = GetCompilerFromType ();

			type = compiler.GetCompiledType ();
			CacheDependency cd = new CacheDependency ((string[])
							tparser.Dependencies.ToArray (typeof (string)));

			HttpRuntime.Cache.InsertPrivate ("@@Type" + tparser.InputFile, type, cd);
			return type;
		}

#if DEBUG
		static void PrintTree (ControlBuilder builder, int indent)
		{
			if (builder == null)
				return;

			string i = new string ('\t', indent);
			Console.Write (i);
			Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
					   builder, builder.ID, builder.ControlType, builder.parentBuilder);

			if (builder.Children != null)
			foreach (object o in builder.Children) {
				if (o is ControlBuilder)
					PrintTree ((ControlBuilder) o, indent++);
			}
		}
		
		static void PrintLocation (ILocation loc)
		{
			Console.WriteLine ("\tFile name: " + loc.Filename);
			Console.WriteLine ("\tBegin line: " + loc.BeginLine);
			Console.WriteLine ("\tEnd line: " + loc.EndLine);
			Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
			Console.WriteLine ("\tEnd column: " + loc.EndColumn);
			Console.WriteLine ("\tPlainText: " + loc.PlainText);
			Console.WriteLine ();
		}
#endif

		void ParseError (ILocation location, string message)
		{
			throw new ParseException (location, message);
		}

		void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
		{
			this.location = new Location (location);
			if (tparser != null)
				tparser.Location = location;

			// MS ignores tbody/thead
			if ((attributes == null || !attributes.IsRunAtServer ())) {
				if (String.Compare (tagid, "tbody", true) == 0 ||
				    String.Compare (tagid, "thead", true) == 0)
				return;
			}

			if (text.Length != 0)
				FlushText ();

			if (0 == String.Compare (tagid, "script", true)) {
				bool in_script = (inScript || ignore_text);
				if (in_script || (tagtype != TagType.Close && attributes != null)) {
					if ((in_script || attributes.IsRunAtServer ()) && ProcessScript (tagtype, attributes))
						return;
				}
			}

			switch (tagtype) {
			case TagType.Directive:
				if (tagid == "")
					tagid = tparser.DefaultDirectiveName;

				tparser.AddDirective (tagid, attributes.GetDictionary (null));
				break;
			case TagType.Tag:
				if (ProcessTag (tagid, attributes, tagtype)) {
					useOtherTags = true;
					break;
				}

				if (useOtherTags) {
					stack.Builder.EnsureOtherTags ();
					stack.Builder.OtherTags.Add (tagid);
				}

				TextParsed (location, location.PlainText);
				break;
			case TagType.Close:
				bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
				if (!notServer && CloseControl (tagid))
					break;
				
				TextParsed (location, location.PlainText);
				break;
			case TagType.SelfClosing:
				int count = stack.Count;
				if (!ProcessTag (tagid, attributes, tagtype)) {
					TextParsed (location, location.PlainText);
				} else if (stack.Count != count) {
					CloseControl (tagid);
				}
				break;
			case TagType.DataBinding:
				goto case TagType.CodeRender;
			case TagType.CodeRenderExpression:
				goto case TagType.CodeRender;
			case TagType.CodeRender:
				if (isApplication)
					throw new ParseException (location, "Invalid content for application file.");
			
				ProcessCode (tagtype, tagid, location);
				break;
			case TagType.Include:
				if (isApplication)
					throw new ParseException (location, "Invalid content for application file.");
			
				string file = attributes ["virtual"] as string;
				bool isvirtual = (file != null);
				if (!isvirtual)
					file = attributes ["file"] as string;

				if (isvirtual) {
					file = tparser.MapPath (file);
				} else {
					file = GetIncludeFilePath (tparser.BaseDir, file);
				}

				InitParser (file);
				DoParse ();
				break;
			default:
				break;
			}
			//PrintLocation (location);
		}

		static bool TryRemoveTag (string tagid, ArrayList otags)
		{
			if (otags == null || otags.Count == 0)
				return false;

			int idx = otags.Count - 1;
			string otagid = (string) otags [idx];
			if (0 != String.Compare (tagid, otagid, true))
				return false;

			otags.RemoveAt (idx);
			return true;
		}

		static string GetIncludeFilePath (string basedir, string filename)
		{
			if (Path.DirectorySeparatorChar == '/')
				filename = filename.Replace ("\\", "/");

			return Path.GetFullPath (Path.Combine (basedir, filename));
		}
		
		void TextParsed (ILocation location, string text)
		{
			if (ignore_text)
				return;

			if (text.IndexOf ("<%") != -1 && !inScript) {
				if (this.text.Length > 0)
					FlushText ();
				CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
				r.AddChildren ();
				return;
			}

			this.text.Append (text);
			//PrintLocation (location);
		}

		void FlushText ()
		{
			string t = text.ToString ();
			text.Length = 0;
			if (inScript) {
				// TODO: store location
				tparser.Scripts.Add (t);
				return;
			}

			if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
				throw new ParseException (location, "Content not valid for application file.");

			ControlBuilder current = stack.Builder;
			current.AppendLiteralString (t);
			if (current.NeedsTagInnerText ()) {
				tagInnerText.Append (t);
			}
		}

		bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
		{
			if (isApplication) {
				if (String.Compare (tagid, "object", true) != 0)
					throw new ParseException (location, "Invalid tag for application file.");
			}

			ControlBuilder parent = stack.Builder;
			ControlBuilder builder = null;
			Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
			if (stack.Count > 1) {
				try {
					builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
				} catch (TypeLoadException e) {
					throw new ParseException (Location, "Type not found.", e);
				} catch (Exception e) {
					throw new ParseException (Location, e.Message, e);
				}
			}

			if (builder == null && atts != null && atts.IsRunAtServer ()) {
				string id = htable ["id"] as string;
				if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
					throw new ParseException (Location, "'" + id + "' is not a valid identifier");
					
				try {
					builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
				} catch (TypeLoadException e) {
					throw new ParseException (Location, "Type not found.", e);
				} catch (Exception e) {
					throw new ParseException (Location, e.Message, e);
				}
			}
			
			if (builder == null)
				return false;

			builder.location = location;
			builder.ID = htable ["id"] as string;
			if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
				if (inForm)
					throw new ParseException (location, "Only one <form> allowed.");

				inForm = true;
			}

			if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
				if (builder is TemplateBuilder) {
				//	push the id list
				}
				stack.Push (builder, location);
			} else {
				if (!isApplication && builder is ObjectTagBuilder) {
					ObjectTagBuilder ot = (ObjectTagBuilder) builder;
					if (ot.Scope != null && ot.Scope != "")
						throw new ParseException (location, "Scope not allowed here");

					if (tagtype == TagType.Tag) {
						stack.Push (builder, location);
						return true;
					}
				}
				
				parent.AppendSubBuilder (builder);
				builder.CloseControl ();
			}

			return true;
		}

		string ReadFile (string filename)
		{
			string realpath = tparser.MapPath (filename);
			using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
				string content = sr.ReadToEnd ();
				return content;
			}
		}

		bool ProcessScript (TagType tagtype, TagAttributes attributes)
		{
			if (tagtype != TagType.Close) {
				if (attributes != null && attributes.IsRunAtServer ()) {
					CheckLanguage ((string) attributes ["language"]);
					string src = (string) attributes ["src"];
					if (src != null) {
						if (src == "")
							throw new ParseException (Parser,
								"src cannot be an empty string");

						string content = ReadFile (src);
						inScript = true;
						TextParsed (Parser, content);
						FlushText ();
						inScript = false;
						if (tagtype != TagType.SelfClosing) {
							ignore_text = true;
							Parser.VerbatimID = "script";
						}
					} else if (tagtype == TagType.Tag) {
						Parser.VerbatimID = "script";
						inScript = true;
					}

					return true;
				} else {
					if (tagtype != TagType.SelfClosing) {
						Parser.VerbatimID = "script";
						javascript = true;
					}
					TextParsed (location, location.PlainText);
					return true;
				}
			}

			bool result;
			if (inScript) {
				result = inScript;
				inScript = false;
			} else if (!ignore_text) {
				result = javascript;
				javascript = false;
				TextParsed (location, location.PlainText);
			} else {
				ignore_text = false;
				result = true;
			}

			return result;
		}

		bool CloseControl (string tagid)
		{
			ControlBuilder current = stack.Builder;
			string btag = current.TagName;
			if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
				if (!current.ChildrenAsProperties) {
					try {
						TextParsed (location, location.PlainText);
						FlushText ();
					} catch {}
				}
				return true;
			}
			
			if (0 != String.Compare (tagid, btag, true))
				return false;

			// if (current is TemplateBuilder)
			//	pop from the id list
			if (current.NeedsTagInnerText ()) {
				try { 
					current.SetTagInnerText (tagInnerText.ToString ());
				} catch (Exception e) {
					throw new ParseException (current.location, e.Message, e);
				}

				tagInnerText.Length = 0;
			}

			if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
				inForm = false;
			}

			current.CloseControl ();
			stack.Pop ();
			stack.Builder.AppendSubBuilder (current);
			return true;
		}

		bool ProcessCode (TagType tagtype, string code, ILocation location)
		{
			ControlBuilder b = null;
			if (tagtype == TagType.CodeRender)
				b = new CodeRenderBuilder (code, false, location);
			else if (tagtype == TagType.CodeRenderExpression)
				b = new CodeRenderBuilder (code, true, location);
			else if (tagtype == TagType.DataBinding)
				b = new DataBindingBuilder (code, location);
			else
				throw new HttpException ("Should never happen");

			stack.Builder.AppendSubBuilder (b);
			return true;
		}

		public ILocation Location {
			get { return location; }
		}

		void CheckLanguage (string lang)
		{
			if (lang == null || lang == "")
				return;

			if (String.Compare (lang, tparser.Language, true) == 0)
				return;

#if NET_2_0
			CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
			if (section.Compilers[tparser.Language] != section.Compilers[lang])
#else
			CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current); 
			if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
#endif
				throw new ParseException (Location,
						String.Format ("Trying to mix language '{0}' and '{1}'.", 
								tparser.Language, lang));
		}

		// Used to get CodeRender tags in attribute values
		class CodeRenderParser
		{
			string str;
			ControlBuilder builder;

			public CodeRenderParser (string str, ControlBuilder builder)
			{
				this.str = str;
				this.builder = builder;
			}

			public void AddChildren ()
			{
				int index = str.IndexOf ("<%");
				if (index > 0) {
					TextParsed (null, str.Substring (0, index));
					str = str.Substring (index);
				}

				AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
				parser.Error += new ParseErrorHandler (ParseError);
				parser.TagParsed += new TagParsedHandler (TagParsed);
				parser.TextParsed += new TextParsedHandler (TextParsed);
				parser.Parse ();
			}

			void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
			{
				if (tagtype == TagType.CodeRender)
					builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
				else if (tagtype == TagType.CodeRenderExpression)
					builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
				else if (tagtype == TagType.DataBinding)
					builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
				else
					builder.AppendLiteralString (location.PlainText);
			}

			void TextParsed (ILocation location, string text)
			{
				builder.AppendLiteralString (text);
			}

			void ParseError (ILocation location, string message)
			{
				throw new ParseException (location, message);
			}
		}
	}
}