2003-03-10 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System.Web / System.Web.Compilation / AspGenerator.cs
1 //
2 // System.Web.Compilation.AspGenerator
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 //
9 using System;
10 using System.Collections;
11 using System.ComponentModel;
12 using System.Drawing;
13 using System.Diagnostics;
14 using System.IO;
15 using System.Reflection;
16 using System.Text;
17 using System.Text.RegularExpressions;
18 using System.Web.UI;
19 using System.Web.UI.HtmlControls;
20 using System.Web.UI.WebControls;
21 using System.Web.Util;
22
23 namespace System.Web.Compilation
24 {
25
26 class ControlStack
27 {
28         private Stack controls;
29         private ControlStackData top;
30         private bool space_between_tags;
31         private bool sbt_valid;
32
33         class ControlStackData 
34         {
35                 public Type controlType;
36                 public string controlID;
37                 public string tagID;
38                 public ChildrenKind childKind;
39                 public string defaultPropertyName;
40                 public int childrenNumber;
41                 public Type container;
42                 public StringBuilder dataBindFunction;
43                 public StringBuilder codeRenderFunction;
44                 public bool useCodeRender;
45                 public int codeRenderIndex;
46
47                 public ControlStackData (Type controlType,
48                                          string controlID,
49                                          string tagID,
50                                          ChildrenKind childKind,
51                                          string defaultPropertyName,
52                                          Type container)
53                 {
54                         this.controlType = controlType;
55                         this.controlID = controlID;
56                         this.tagID = tagID;
57                         this.childKind = childKind;
58                         this.defaultPropertyName = defaultPropertyName;
59                         this.container = container;
60                         childrenNumber = 0;
61                 }
62
63                 public override string ToString ()
64                 {
65                         return controlType + " " + controlID + " " + tagID + " " + childKind + " " + childrenNumber;
66                 }
67         }
68         
69         public ControlStack ()
70         {
71                 controls = new Stack ();
72         }
73
74         private Type GetContainerType (Type type)
75         {
76                 if (type != typeof (System.Web.UI.Control) &&
77                     !type.IsSubclassOf (typeof (System.Web.UI.Control)))
78                         return null;
79                 
80                 Type container_type;
81                 if (type == typeof (System.Web.UI.WebControls.DataList))
82                         container_type = typeof (System.Web.UI.WebControls.DataListItem);
83                 else if (type == typeof (System.Web.UI.WebControls.DataGrid))
84                         container_type = typeof (System.Web.UI.WebControls.DataGridItem);
85                 else if (type == typeof (System.Web.UI.WebControls.Repeater))
86                         container_type = typeof (System.Web.UI.WebControls.RepeaterItem);
87                 else if (type == typeof (ListControl) || type.IsSubclassOf (typeof (ListControl)))
88                         container_type = type;
89                 else
90                         container_type = Container;
91
92                 return container_type;
93         }
94
95         public void Push (object o)
96         {
97                 if (!(o is ControlStackData))
98                         return;
99
100                 controls.Push (o);
101                 top = (ControlStackData) o;
102                 sbt_valid = false;
103         }
104         
105         public void Push (Type controlType,
106                           string controlID,
107                           string tagID,
108                           ChildrenKind childKind,
109                           string defaultPropertyName)
110         {
111                 Type container_type = null;
112                 if (controlType != null){
113                         AddChild ();
114                         container_type = GetContainerType (controlType);
115                         if (container_type == null)
116                                 container_type = this.Container;
117                 }
118
119                 top = new ControlStackData (controlType,
120                                             controlID,
121                                             tagID,
122                                             childKind,
123                                             defaultPropertyName,
124                                             container_type);
125                 sbt_valid = false;
126                 controls.Push (top);
127         }
128
129         public object Pop ()
130         {
131                 object item = controls.Pop ();
132                 if (controls.Count != 0)
133                         top = (ControlStackData) controls.Peek ();
134                 sbt_valid = false;
135                 return item;
136         }
137
138         public Type PeekType ()
139         {
140                 return top.controlType;
141         }
142
143         public string PeekControlID ()
144         {
145                 return top.controlID;
146         }
147
148         public string PeekTagID ()
149         {
150                 return top.tagID;
151         }
152
153         public ChildrenKind PeekChildKind ()
154         {
155                 return top.childKind;
156         }
157
158         public string PeekDefaultPropertyName ()
159         {
160                 return top.defaultPropertyName;
161         }
162
163         public void AddChild ()
164         {
165                 if (top != null)
166                         top.childrenNumber++;
167         }
168
169         public bool HasDataBindFunction ()
170         {
171                 if (top.dataBindFunction == null || top.dataBindFunction.Length == 0)
172                         return false;
173                 return true;
174         }
175         
176         public bool UseCodeRender
177         {
178                 get {
179                         if (top.codeRenderFunction == null || top.codeRenderFunction.Length == 0)
180                                 return false;
181                         return top.useCodeRender;
182                 }
183
184                 set { top.useCodeRender= value; }
185         }
186         
187         public bool SpaceBetweenTags
188         {
189                 get {
190                         if (!sbt_valid){
191                                 sbt_valid = true;
192                                 Type type = top.controlType;
193                                 if (type.Namespace == "System.Web.UI.WebControls")
194                                         space_between_tags = true;
195                                 else if (type.IsSubclassOf (typeof (System.Web.UI.WebControls.WebControl)))
196                                         space_between_tags = true;
197                                 else if (type == typeof (System.Web.UI.HtmlControls.HtmlSelect))
198                                         space_between_tags = true;
199                                 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTable))
200                                         space_between_tags = true;
201                                 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableRow))
202                                         space_between_tags = true;
203                                 else if (type == typeof (System.Web.UI.HtmlControls.HtmlTableCell))
204                                         space_between_tags = true;
205                                 else
206                                         space_between_tags = false;
207                         }
208                         return space_between_tags;
209                 }
210         }
211         
212         public Type Container {
213                 get {
214                         if (top == null)
215                                 return null;
216                                 
217                         return top.container;
218                 }
219         }
220         
221         public StringBuilder DataBindFunction
222         {
223                 get {
224                         if (top.dataBindFunction == null)
225                                 top.dataBindFunction = new StringBuilder ();
226                         return top.dataBindFunction;
227                 }
228         }
229
230         public int CodeRenderIndex {
231                 get {
232                         return top.codeRenderIndex++;
233                 }
234         }
235         
236         public StringBuilder CodeRenderFunction
237         {
238                 get {
239                         if (top.codeRenderFunction == null)
240                                 top.codeRenderFunction = new StringBuilder ();
241                         return top.codeRenderFunction;
242                 }
243         }
244
245         public int ChildIndex
246         {
247                 get { return top.childrenNumber - 1; }
248         }
249         
250         public int Count
251         {
252                 get { return controls.Count; }
253         }
254
255         public override string ToString ()
256         {
257                 return top.ToString () + " " + top.useCodeRender;
258         }
259                 
260 }
261
262 enum ScriptStatus
263 {
264         Close,
265         Open,
266         Text
267 }
268
269 class AspGenerator
270 {
271         object [] parts;
272         StringBuilder prolog;
273         StringBuilder declarations;
274         StringBuilder script;
275         StringBuilder constructor;
276         StringBuilder init_funcs;
277         StringBuilder epilog;
278         StringBuilder current_function;
279         StringBuilder textChunk;
280         Stack functions;
281         ControlStack controls;
282         bool parse_ok;
283         bool has_form_tag;
284         AspComponentFoundry aspFoundry;
285
286         string classDecl;
287         string className;
288         string interfaces;
289         string basetype;
290         string parent;
291         Type parentType;
292         string fullPath;
293
294         Hashtable options;
295         string privateBinPath;
296         string main_directive;
297         static string app_file_wrong = "The content in the application file is not valid.";
298
299         bool isPage;
300         bool isUserControl;
301         bool isApplication;
302
303         Element current;
304         ScriptStatus sstatus = ScriptStatus.Close;
305         string waitClosing;
306         ArrayList dependencies;
307
308         HttpContext context;
309
310         SessionState sessionState = SessionState.Enabled;
311
312         static Type styleType = typeof (System.Web.UI.WebControls.Style);
313         static Type fontinfoType = typeof (System.Web.UI.WebControls.FontInfo);
314
315         enum UserControlResult
316         {
317                 OK = 0,
318                 FileNotFound = 1,
319                 CompilationFailed = 2
320         }
321
322         enum SessionState
323         {
324                 Enabled,
325                 ReadOnly,
326                 Disabled
327         }
328         
329         public AspGenerator (string pathToFile)
330         {
331                 if (pathToFile == null)
332                         throw new ArgumentNullException ("pathToFile");
333
334                 string filename = Path.GetFileName (pathToFile);
335                 this.className = filename.Replace ('.', '_'); // Overridden by @ Page classname
336                 this.className = className.Replace ('-', '_'); 
337                 this.className = className.Replace (' ', '_');
338                 Options ["ClassName"] = this.className;
339                 this.fullPath = Path.GetFullPath (pathToFile);
340
341                 this.has_form_tag = false;
342                 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
343                 privateBinPath = setup.PrivateBinPath;
344                 // This is a hack until we can run stuff in different domains
345                 if (privateBinPath == null || privateBinPath.Length == 0)
346                         privateBinPath = "bin";
347                         
348                 if (!Path.IsPathRooted (privateBinPath)) {
349                         string appbase = setup.ApplicationBase;
350                         if (appbase.StartsWith ("file://"))
351                                 appbase = appbase.Substring (7);
352                         privateBinPath = Path.Combine (appbase, privateBinPath);
353                 }
354                 
355                 Init ();
356         }
357
358         public string BaseType {
359                 get { return basetype; }
360
361                 set {
362                         if (parent == null)
363                                 parent = value;
364
365                         basetype = value;
366                         isUserControl = (basetype == "System.Web.UI.UserControl");
367                         isPage = (basetype == "System.Web.UI.Page");
368                         isApplication = (basetype == "System.Web.HttpApplication");
369                 }
370         }
371
372         public bool IsUserControl {
373                 get { return isUserControl; }
374         }
375         
376         public bool IsPage {
377                 get { return isPage; }
378         }
379         
380         public bool IsApplication {
381                 get { return isApplication; }
382         }
383
384         public string Interfaces {
385                 get { return interfaces; }
386         }
387
388         public Hashtable Options {
389                 get {
390                         if (options == null)
391                                 options = new Hashtable ();
392
393                         return options;
394                 }
395         }
396         
397         public ArrayList Dependencies {
398                 get { return dependencies; }
399         }
400         
401         internal HttpContext Context {
402                 get { return context; }
403                 set { context = value; }
404         }
405         
406         bool AddUsing (string nspace)
407         {
408                 string _using = "using " + nspace + ";";
409                 if (prolog.ToString ().IndexOf (_using) == -1) {
410                         prolog.AppendFormat ("\t{0}\n", _using);
411                         return true;
412                 }
413
414                 return false;
415         }
416
417         void AddInterface (Type type)
418         {
419                 AddInterface (type.ToString ());
420         }
421         
422         public void AddInterface (string iface)
423         {
424                 if (interfaces == null) {
425                         interfaces = ", " + iface;
426                 } else {
427                         string s = ", " + iface;
428                         if (interfaces.IndexOf (s) == -1)
429                                 interfaces += s;
430                 }
431         }
432
433         private AspComponentFoundry Foundry
434         {
435                 get {
436                         if (aspFoundry == null)
437                                 aspFoundry = new AspComponentFoundry ();
438
439                         return aspFoundry;
440                 }
441         }
442
443         private void Init ()
444         {
445                 dependencies = new ArrayList ();
446                 dependencies.Add (fullPath);
447
448                 controls = new ControlStack ();
449                 controls.Push (typeof (System.Web.UI.Control), "Root", null, ChildrenKind.CONTROLS, null);
450                 prolog = new StringBuilder ();
451                 declarations = new StringBuilder ();
452                 script = new StringBuilder ();
453                 constructor = new StringBuilder ();
454                 init_funcs = new StringBuilder ();
455                 epilog = new StringBuilder ();
456                 textChunk = new StringBuilder ();
457
458                 current_function = new StringBuilder ();
459                 functions = new Stack ();
460                 functions.Push (current_function);
461
462                 parts = new Object [6];
463                 parts [0] = prolog;
464                 parts [1] = declarations;
465                 parts [2] = script;
466                 parts [3] = constructor;
467                 parts [4] = init_funcs;
468                 parts [5] = epilog;
469
470                 prolog.Append ("namespace ASP {\n" +
471                               "\tusing System;\n" + 
472                               "\tusing System.Collections;\n" + 
473                               "\tusing System.Collections.Specialized;\n" + 
474                               "\tusing System.Configuration;\n" + 
475                               "\tusing System.IO;\n" + 
476                               "\tusing System.Text;\n" + 
477                               "\tusing System.Text.RegularExpressions;\n" + 
478                               "\tusing System.Web;\n" + 
479                               "\tusing System.Web.Caching;\n" + 
480                               "\tusing System.Web.Security;\n" + 
481                               "\tusing System.Web.SessionState;\n" + 
482                               "\tusing System.Web.UI;\n" + 
483                               "\tusing System.Web.UI.WebControls;\n" + 
484                               "\tusing System.Web.UI.HtmlControls;\n");
485
486                 declarations.Append ("\t\tprivate static int __autoHandlers;\n");
487
488                 current_function.Append ("\t\tprivate void __BuildControlTree (System.Web.UI.Control __ctrl)\n\t\t{\n");
489                 if (!IsUserControl)
490                         current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " + 
491                                                  "(System.Web.UI.IParserAccessor) __ctrl;\n\n");
492                 else
493                         controls.UseCodeRender = true;
494         }
495
496         public TextReader GetCode ()
497         {
498                 if (!parse_ok)
499                         throw new InvalidOperationException ("Parsing not done yet! (may be there were errors?)");
500
501                 StringBuilder code = new StringBuilder ();
502                 for (int i = 0; i < parts.Length; i++)
503                         code.Append ((StringBuilder) parts [i]);
504
505                 return new StringReader (code.ToString ());
506         }
507
508         // Regex.Escape () make some illegal escape sequences for a C# source.
509         private string Escape (string input)
510         {
511                 if (input == null)
512                         return String.Empty;
513
514                 string output = input.Replace ("\\", "\\\\");
515                 output = output.Replace ("\"", "\\\"");
516                 output = output.Replace ("\t", "\\t");
517                 output = output.Replace ("\r", "\\r");
518                 output = output.Replace ("\n", "\\n");
519                 output = output.Replace ("\n", "\\n");
520                 return output;
521         }
522         
523         bool AddProtectedField (Type type, string fieldName)
524         {
525                 if (parentType == null) {
526                         declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
527                         return true;
528                 }
529
530                 FieldInfo field = parentType.GetField (fieldName, BindingFlags.Public |
531                                                                   BindingFlags.NonPublic |
532                                                                   BindingFlags.Instance |
533                                                                   BindingFlags.Static);
534
535                 if (field == null || (!field.IsPublic && !field.IsFamily)) {
536                         declarations.AppendFormat ("\t\tprotected {0} {1};\n", type.ToString (), fieldName);
537                         return true;
538                 }
539
540                 if (!field.FieldType.IsAssignableFrom (type)) {
541                         string message = String.Format ("The base class includes the field '{0}', but its " +
542                                                         "type '{1}' is not compatible with {2}",
543                                                         fieldName, field.FieldType, type);
544
545                         throw new ApplicationException (message);
546                 }
547
548                 return false;
549         }
550         
551         private Type LoadParentType (string typeName)
552         {
553                 // First try loaded assemblies, then try assemblies in Bin directory.
554                 // By now i do this 'by hand' but may be this is a runtime/gac task.
555                 Type type = null;
556                 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
557                 foreach (Assembly ass in assemblies) {
558                         type = ass.GetType (typeName);
559                         if (type != null)
560                                 return type;
561                 }
562
563                 Assembly assembly;
564                 string [] binDlls = Directory.GetFiles (privateBinPath, "*.dll");
565                 foreach (string dll in binDlls) {
566                         string dllPath = Path.Combine (privateBinPath, dll);
567                         assembly = null;
568                         try {
569                                 assembly = Assembly.LoadFrom (dllPath);
570                                 type = assembly.GetType (typeName);
571                         } catch (Exception e) {
572                                 if (assembly != null) {
573                                         Console.WriteLine ("ASP.NET Warning: assembly {0} loaded", dllPath);
574                                         Console.WriteLine ("ASP.NET Warning: but type {0} not found", typeName);
575                                 } else {
576                                         Console.WriteLine ("ASP.NET Warning: unable to load type {0} from {1}",
577                                                            typeName, dllPath);
578                                 }
579                                 Console.WriteLine ("ASP.NET Warning: error was: {0}", e.Message);
580                         }
581
582                         if (type != null) {
583                                 dependencies.Add (dllPath);
584                                 return type;
585                         }
586                 }
587
588                 return null;
589         }
590
591         private void PageDirective (TagAttributes att)
592         {
593                 if (att ["ClassName"] != null){
594                         this.className = (string) att ["ClassName"];
595                         Options ["ClassName"] = className;
596                 }
597
598                 if (att ["EnableSessionState"] != null){
599                         if (!IsPage)
600                                 throw new ApplicationException ("EnableSessionState not allowed here.");
601                         
602                         string est = (string) att ["EnableSessionState"];
603                         if (0 == String.Compare (est, "false", true))
604                                 sessionState = SessionState.Disabled;
605                         else if (0 == String.Compare (est, "true", true))
606                                 sessionState = SessionState.Enabled;
607                         else if (0 == String.Compare (est, "readonly", true))
608                                 sessionState = SessionState.ReadOnly;
609                         else
610                                 throw new ApplicationException ("EnableSessionState in Page directive not set to " +
611                                                                 "a correct value: " + est);
612                 }
613
614                 if (att ["Inherits"] != null) {
615                         parent = (string) att ["Inherits"];
616                         parentType = LoadParentType (parent);
617                         if (parentType == null)
618                                 throw new ApplicationException ("The class " + parent + " cannot be found.");
619                 }
620
621                 if (att ["CompilerOptions"] != null)
622                         Options ["CompilerOptions"] = (string) att ["CompilerOptions"];
623
624                 if (att ["AutoEventWireup"] != null) {
625                         if (options ["AutoEventWireup"] != null)
626                                 throw new ApplicationException ("Already have an AutoEventWireup attribute");
627                         
628                         bool autoevent = true;
629                         string v = att ["AutoEventWireup"] as string;
630                         try {
631                                 autoevent = Convert.ToBoolean (v);
632                         } catch (Exception) {
633                                 throw new ApplicationException ("'" + v + "' is not a valid value for AutoEventWireup");
634                         }
635                         options ["AutoEventWireup"] = autoevent;
636                 }
637
638                 //FIXME: add support for more attributes.
639         }
640
641         void AddReference (string dll)
642         {
643                 string references = Options ["References"] as string;
644                 if (references == null)
645                         references = dll;
646                 else
647                         references = references + "|" + dll;
648
649                 Options ["References"] = references;
650         }
651
652         private void RegisterDirective (TagAttributes att)
653         {
654                 string tag_prefix = (string) (att ["tagprefix"] == null ?  "" : att ["tagprefix"]);
655                 string name_space = (string) (att ["namespace"] == null ?  "" : att ["namespace"]);
656                 string assembly_name = (string) (att ["assembly"] == null ?  "" : att ["assembly"]);
657                 string tag_name =  (string) (att ["tagname"] == null ?  "" : att ["tagname"]);
658                 string src = (string) (att ["src"] == null ?  "" : att ["src"]);
659
660                 if (tag_prefix != "" && name_space != "" && assembly_name != ""){
661                         if (tag_name != "" || src != "")
662                                 throw new ApplicationException ("Invalid attributes for @ Register: " +
663                                                                 att.ToString ());
664
665                         AddUsing (name_space);
666                         string dll = Path.Combine (privateBinPath, assembly_name + ".dll");
667                         // Hack: it should use assembly.load semantics...
668                         // may be when we don't run mcs as a external program...
669                         if (!File.Exists (dll))
670                                 dll = assembly_name;
671                         else
672                                 dependencies.Add (dll);
673
674                         Foundry.RegisterFoundry (tag_prefix, dll, name_space);
675                         AddReference (dll);
676                         return;
677                 }
678
679                 if (tag_prefix != "" && tag_name != "" && src != ""){
680                         if (name_space != "" && assembly_name != "")
681                                 throw new ApplicationException ("Invalid attributes for @ Register: " +
682                                                                 att.ToString ());
683                         
684                         if (!src.EndsWith (".ascx"))
685                                 throw new ApplicationException ("Source file extension for controls " + 
686                                                                 "must be .ascx");
687
688                         UserControlData data = GenerateUserControl (src, Context);
689                         switch (data.result) {
690                         case UserControlResult.OK:
691                                 AddUsing ("ASP");
692                                 Foundry.RegisterFoundry (tag_prefix, tag_name, data.assemblyName, "ASP", data.className);
693                                 AddReference (data.assemblyName);
694                                 break;
695                         case UserControlResult.FileNotFound:
696                                 throw new ApplicationException ("File '" + src + "' not found.");
697                         case UserControlResult.CompilationFailed:
698                                 //TODO: should say where the generated .cs file is for the server to
699                                 //show the source and the compiler error
700                                 throw new NotImplementedException ();
701                         }
702                         return;
703                 }
704
705                 throw new ApplicationException ("Invalid combination of attributes in " +
706                                                 "@ Register: " + att.ToString ());
707         }
708
709         private void ProcessDirective ()
710         {
711                 FlushPlainText ();
712                 Directive directive = (Directive) current;
713                 TagAttributes att = directive.Attributes;
714                 if (att == null)
715                         return;
716
717                 string value;
718                 string id = directive.TagID.ToUpper ();
719                 switch (id){
720                 case "APPLICATION":
721                         if (main_directive != null)
722                                 throw new ApplicationException (id + " not allowed after " + main_directive);
723
724                         if (!IsApplication)
725                                 throw new ApplicationException ("@Application not allowed.");
726
727                         string inherits = att ["inherits"] as string;
728                         if (inherits != null)
729                                 Options ["Inherits"] = inherits;
730
731                         main_directive = directive.TagID;
732                         break;
733                 case "PAGE":
734                 case "CONTROL":
735                         if (main_directive != null)
736                                 throw new ApplicationException (id + " not allowed after " + main_directive);
737
738                         if (IsUserControl && id != "CONTROL")
739                                 throw new ApplicationException ("@Page not allowed for user controls.");
740                         else if (IsPage && id != "PAGE")
741                                 throw new ApplicationException ("@Control not allowed here. This is a page!");
742
743                         PageDirective (att);
744                         main_directive = directive.TagID;
745                         break;
746                 case "IMPORT":
747                         value = att ["namespace"] as string;
748                         if (value == null || att.Count > 1)
749                                 throw new ApplicationException ("Wrong syntax in Import directive.");
750
751                         string _using = "using " + value + ";";
752                         if (AddUsing (value) == true) {
753                                 string imports = Options ["Import"] as string;
754                                 if (imports == null) {
755                                         imports = value;
756                                 } else {
757                                         imports += "," + value;
758                                 }
759
760                                 Options ["Import"] = imports;
761                         }
762                         break;
763                 case "IMPLEMENTS":
764                         if (IsApplication)
765                                 throw new ApplicationException ("@ Implements not allowed in an application file.");
766
767                         string iface = (string) att ["interface"];
768                         AddInterface (iface);
769                         break;
770                 case "REGISTER":
771                         if (IsApplication)
772                                 throw new ApplicationException ("@ Register not allowed in an application file.");
773
774                         RegisterDirective (att);
775                         break;
776                 case "ASSEMBLY":
777                         if (att.Count > 1)
778                                 throw new ApplicationException ("Wrong syntax in Assembly directive.");
779
780                         string name = att ["name"] as string;
781                         string src = att ["src"] as string;
782
783                         if (name == null && src == null)
784                                 throw new ApplicationException ("Wrong syntax in Assembly directive.");
785
786                         if (IsApplication && src != null)
787                                 throw new ApplicationException ("'name' attribute expected.");
788
789                         value = (name == null) ? src : name;
790                         string assemblies = Options ["Assembly"] as string;
791                         if (assemblies == null) {
792                                 assemblies = value;
793                         } else {
794                                 assemblies += "," + value;
795                         }
796
797                         Options ["Assembly"] = assemblies;
798                         break;
799                 }
800         }
801
802         private void ProcessPlainText ()
803         {
804                 PlainText asis = (PlainText) current;
805                 string trimmed = asis.Text.Trim ();
806                 if (trimmed == String.Empty && controls.SpaceBetweenTags == true)
807                         return;
808
809                 if (IsApplication) {
810                         if (trimmed != String.Empty)
811                                 throw new ApplicationException (app_file_wrong);
812                         return;
813                 }
814
815                 if (trimmed != String.Empty && controls.PeekChildKind () != ChildrenKind.CONTROLS){
816                         string tag_id = controls.PeekTagID ();
817                         throw new ApplicationException ("Literal content not allowed for " + tag_id);
818                 }
819                 
820                 string escaped_text = Escape (asis.Text);
821                 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject (" + 
822                                                "new System.Web.UI.LiteralControl (\"{0}\"));\n",
823                                                escaped_text);
824                 StringBuilder codeRenderFunction = controls.CodeRenderFunction;
825                 codeRenderFunction.AppendFormat ("\t\t\t__output.Write (\"{0}\");\n", escaped_text);
826         }
827
828         private string EnumValueNameToString (Type enum_type, string value_name)
829         {
830                 if (value_name.EndsWith ("*"))
831                         throw new ApplicationException ("Invalid property value: '" + value_name + 
832                                                         ". It must be a valid " + enum_type.ToString () + " value.");
833
834                 MemberInfo [] nested_types = enum_type.FindMembers (MemberTypes.Field, 
835                                                                     BindingFlags.Public | BindingFlags.Static,
836                                                                     Type.FilterNameIgnoreCase,
837                                                                     value_name);
838
839                 if (nested_types.Length == 0)
840                         throw new ApplicationException ("Value " + value_name + " not found in enumeration " +
841                                                         enum_type.ToString ());
842                 if (nested_types.Length > 1)
843                         throw new ApplicationException ("Value " + value_name + " found " + 
844                                                         nested_types.Length + " in enumeration " +
845                                                         enum_type.ToString ());
846
847                 return enum_type.ToString () + "." + nested_types [0].Name;
848         }
849         
850         private void NewControlFunction (string tag_id,
851                                          string control_id,
852                                          Type control_type,
853                                          ChildrenKind children_kind,
854                                          string defaultPropertyName)
855         {
856                 ChildrenKind prev_children_kind = controls.PeekChildKind ();
857                 if (prev_children_kind == ChildrenKind.NONE || 
858                     prev_children_kind == ChildrenKind.PROPERTIES){
859                         string prev_tag_id = controls.PeekTagID ();
860                         throw new ApplicationException ("Child controls not allowed for " + prev_tag_id);
861                 }
862
863                 Type allowed = null;
864                 if (prev_children_kind == ChildrenKind.DBCOLUMNS &&
865                     !typeof (DataGridColumn).IsAssignableFrom (control_type)) {
866                         allowed = typeof (DataGridColumn);
867                 } else if (prev_children_kind == ChildrenKind.LISTITEM &&
868                          control_type != typeof (System.Web.UI.WebControls.ListItem)) {
869                         allowed = typeof (DataGridColumn);
870                 } else if (prev_children_kind == ChildrenKind.HTMLROW) {
871                         Type prevType = controls.PeekType ();
872                         if (prevType == typeof (HtmlTable) && control_type != typeof (HtmlTableRow))
873                                 allowed = typeof (HtmlTableRow);
874                         else if (prevType == typeof (Table) && control_type != typeof (TableRow))
875                                 allowed = typeof (TableRow);
876                 } else if (prev_children_kind == ChildrenKind.HTMLCELL) {
877                         Type prevType = controls.PeekType ();
878                         if (prevType == typeof (HtmlTableRow) && control_type != typeof (HtmlTableCell))
879                                 allowed = typeof (HtmlTableCell);
880                         else if (prevType == typeof (TableRow) && control_type != typeof (TableCell))
881                                 allowed = typeof (TableCell);
882                 }
883         
884                 if (allowed != null)
885                         throw new ApplicationException ("Inside " + controls.PeekTagID () + " only " + 
886                                                         allowed + " objects are allowed");
887
888                 StringBuilder func_code = new StringBuilder ();
889                 current_function = func_code;
890                 if (0 == String.Compare (tag_id, "form", true)){
891                         if (has_form_tag)
892                                 throw new ApplicationException ("Only one form server tag allowed.");
893                         has_form_tag = true;
894                 }
895
896                 controls.Push (control_type, control_id, tag_id, children_kind, defaultPropertyName);
897                 bool is_generic = control_type ==  typeof (System.Web.UI.HtmlControls.HtmlGenericControl);
898                 functions.Push (current_function);
899                 if (control_type != typeof (System.Web.UI.WebControls.ListItem) &&
900                     prev_children_kind != ChildrenKind.DBCOLUMNS) {
901                         current_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_" +
902                                                         "{0} ()\n\t\t{{\n\t\t\t{1} __ctrl;\n\n\t\t\t__ctrl" +
903                                                         " = new {1} ({2});\n\t\t\tthis.{0} = __ctrl;\n",
904                                                         control_id, control_type,
905                                                         (is_generic? "\"" + tag_id + "\"" : ""));
906                 } else {
907                         current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ()\n\t\t{{" +
908                                                         "\n\t\t\t{1} __ctrl;\n\t\t\t__ctrl = new {1} ();" +
909                                                         "\n\t\t\tthis.{0} = __ctrl;\n",
910                                                         control_id, control_type);
911                 }
912
913                 if (children_kind == ChildrenKind.CONTROLS || children_kind == ChildrenKind.OPTION)
914                         current_function.Append ("\t\t\tSystem.Web.UI.IParserAccessor __parser = " + 
915                                                  "(System.Web.UI.IParserAccessor) __ctrl;\n");
916         }
917         
918         private void DataBoundProperty (Type target, string varName, string value)
919         {
920                 if (value == "")
921                         throw new ApplicationException ("Empty data binding tag.");
922
923                 string control_id = controls.PeekControlID ();
924                 string control_type_string = controls.PeekType ().ToString ();
925                 StringBuilder db_function = controls.DataBindFunction;
926                 string container;
927                 if (controls.Container == null || !typeof (INamingContainer).IsAssignableFrom (controls.Container))
928                         container = "System.Web.UI.Control";
929                 else {
930                         container = controls.Container.ToString ();
931                 }
932
933                 if (db_function.Length == 0)
934                         db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " + 
935                                                   "System.EventArgs e) {{\n" +
936                                                   "\t\t\t{1} Container;\n" +
937                                                   "\t\t\t{2} target;\n" +
938                                                   "\t\t\ttarget = ({2}) sender;\n" +
939                                                   "\t\t\tContainer = ({1}) target.BindingContainer;\n",
940                                                   control_id, container, control_type_string);
941
942                 /* Removes '<%#' and '%>' */
943                 string real_value = value.Remove (0,3);
944                 real_value = real_value.Remove (real_value.Length - 2, 2);
945                 real_value = real_value.Trim ();
946
947                 if (target == typeof (string))
948                         db_function.AppendFormat ("\t\t\ttarget.{0} = System.Convert.ToString ({1});\n",
949                                                   varName, real_value);
950                 else
951                         db_function.AppendFormat ("\t\t\ttarget.{0} = ({1}) ({2});\n",
952                                                   varName, target, real_value);
953         }
954
955         /*
956          * Returns true if it generates some code for the specified property
957          */
958         private void AddCodeForPropertyOrField (Type type, string var_name, string att, bool isDataBound)
959         {
960                 /* FIXME: should i check for this or let the compiler fail?
961                  * if (!prop.CanWrite)
962                  *    ....
963                  */
964                 if (isDataBound) {
965                         DataBoundProperty (type, var_name, att);
966                 }
967                 else if (type == typeof (string)){
968                         if (att == null)
969                                 throw new ApplicationException ("null value for attribute " + var_name );
970
971                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = \"{1}\";\n", var_name,
972                                                         Escape (att)); // FIXME: really Escape this?
973                 } 
974                 else if (type.IsEnum){
975                         if (att == null)
976                                 throw new ApplicationException ("null value for attribute " + var_name );
977
978                         string enum_value = EnumValueNameToString (type, att);
979
980                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, enum_value);
981                 } 
982                 else if (type == typeof (bool)){
983                         string value;
984                         if (att == null)
985                                 value = "true"; //FIXME: is this ok for non Style properties?
986                         else if (0 == String.Compare (att, "true", true))
987                                 value = "true";
988                         else if (0 == String.Compare (att, "false", true))
989                                 value = "false";
990                         else
991                                 throw new ApplicationException ("Value '" + att  + "' is not a valid boolean.");
992
993                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
994                 }
995                 else if (type == typeof (System.Web.UI.WebControls.Unit)){
996                          //FIXME: should use the culture specified in Page
997                         try {
998                                 Unit value = Unit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
999                         } catch (Exception) {
1000                                 throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
1001                         }
1002                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = " + 
1003                                                         "System.Web.UI.WebControls.Unit.Parse (\"{1}\", " + 
1004                                                         "System.Globalization.CultureInfo.InvariantCulture);\n", 
1005                                                         var_name, att);
1006                 }
1007                 else if (type == typeof (System.Web.UI.WebControls.FontUnit)){
1008                          //FIXME: should use the culture specified in Page
1009                         try {
1010                                 FontUnit value = FontUnit.Parse (att, System.Globalization.CultureInfo.InvariantCulture);
1011                         } catch (Exception) {
1012                                 throw new ApplicationException ("'" + att + "' cannot be parsed as a unit.");
1013                         }
1014                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = " + 
1015                                                         "System.Web.UI.WebControls.FontUnit.Parse (\"{1}\", " + 
1016                                                         "System.Globalization.CultureInfo.InvariantCulture);\n", 
1017                                                         var_name, att);
1018                 }
1019                 else if (type == typeof (Int16) || type == typeof (Int32) || type == typeof (Int64)) {
1020                         long value;
1021                         try {
1022                                 value = Int64.Parse (att); //FIXME: should use the culture specified in Page
1023                         } catch (Exception){
1024                                 throw new ApplicationException (att + " is not a valid signed number " + 
1025                                                                 "or is out of range.");
1026                         }
1027
1028                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1029                 }
1030                 else if (type == typeof (UInt16) || type == typeof (UInt32) || type == typeof (UInt64)) {
1031                         ulong value;
1032                         try {
1033                                 value = UInt64.Parse (att); //FIXME: should use the culture specified in Page
1034                         } catch (Exception){
1035                                 throw new ApplicationException (att + " is not a valid unsigned number " + 
1036                                                                 "or is out of range.");
1037                         }
1038
1039                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1040                 }
1041                 else if (type == typeof (float)) {
1042                         float value;
1043                         try {
1044                                 value = Single.Parse (att);
1045                         } catch (Exception){
1046                                 throw new ApplicationException (att + " is not  avalid float number or " +
1047                                                                 "is out of range.");
1048                         }
1049
1050                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1051                 }
1052                 else if (type == typeof (double)){
1053                         double value;
1054                         try {
1055                                 value = Double.Parse (att);
1056                         } catch (Exception){
1057                                 throw new ApplicationException (att + " is not  avalid double number or " +
1058                                                                 "is out of range.");
1059                         }
1060
1061                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = {1};\n", var_name, value);
1062                 }
1063                 else if (type == typeof (System.Drawing.Color)){
1064                         Color c;
1065                         try {
1066                                 c = (Color) TypeDescriptor.GetConverter (typeof (Color)).ConvertFromString (att);
1067                         } catch (Exception e){
1068                                 throw new ApplicationException ("Color " + att + " is not a valid color.", e);
1069                         }
1070
1071                         // Should i also test for IsSystemColor?
1072                         // Are KnownColor members in System.Drawing.Color?
1073                         if (c.IsKnownColor){
1074                                 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1075                                                                "{1};\n", var_name, c.Name);
1076                         }
1077                         else {
1078                                 current_function.AppendFormat ("\t\t\t__ctrl.{0} = System.Drawing.Color." +
1079                                                                "FromArgb ({1}, {2}, {3}, {4});\n",
1080                                                                var_name, c.A, c.R, c.G, c.B);
1081                         }
1082                 }
1083                 else if (type == typeof (string [])) {
1084                         string [] subStrings = att.Split (',');
1085                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = new String [] {{\n", var_name);
1086                         int end = subStrings.Length;
1087                         for (int i = 0; i < end; i++) {
1088                                 string s = subStrings [i].Trim ();
1089                                 current_function.AppendFormat ("\t\t\t\t\"{0}\"", s);
1090                                 if (i == end - 1)
1091                                         current_function.Append ("\t\t\t\t};\n");
1092                                 else
1093                                         current_function.Append (",\n");
1094                         }
1095                 } else {
1096                         throw new ApplicationException ("Unsupported type in property: " + 
1097                                                         type.ToString ());
1098                 }
1099         }
1100
1101         private bool ProcessPropertiesAndFields (MemberInfo member, string id, TagAttributes att)
1102         {
1103                 int hyphen = id.IndexOf ('-');
1104
1105                 bool isPropertyInfo = (member is PropertyInfo);
1106
1107                 bool is_processed = false;
1108                 bool isDataBound = att.IsDataBound ((string) att [id]);
1109                 Type type;
1110                 if (isPropertyInfo) {
1111                         type = ((PropertyInfo) member).PropertyType;
1112                         if (hyphen == -1 && ((PropertyInfo) member).CanWrite == false)
1113                                 return false;
1114                 } else {
1115                         type = ((FieldInfo) member).FieldType;
1116                 }
1117
1118                 if (0 == String.Compare (member.Name, id, true)){
1119                         AddCodeForPropertyOrField (type, member.Name, (string) att [id], isDataBound);
1120                         is_processed = true;
1121                 } else if (hyphen != -1 && (type == fontinfoType || type == styleType || type.IsSubclassOf (styleType))){
1122                         string prop_field = id.Replace ("-", ".");
1123                         string [] parts = prop_field.Split (new char [] {'.'});
1124                         if (parts.Length != 2 || 0 != String.Compare (member.Name, parts [0], true))
1125                                 return false;
1126
1127                         PropertyInfo [] subprops = type.GetProperties ();
1128                         foreach (PropertyInfo subprop in subprops){
1129                                 if (0 != String.Compare (subprop.Name, parts [1], true))
1130                                         continue;
1131
1132                                 if (subprop.CanWrite == false)
1133                                         return false;
1134
1135                                 bool is_bool = subprop.PropertyType == typeof (bool);
1136                                 if (!is_bool && att [id] == null){
1137                                         att [id] = ""; // Font-Size -> Font-Size="" as html
1138                                         return false;
1139                                 }
1140
1141                                 string value;
1142                                 if (att [id] == null && is_bool)
1143                                         value = "true"; // Font-Bold <=> Font-Bold="true"
1144                                 else
1145                                         value = (string) att [id];
1146
1147                                 AddCodeForPropertyOrField (subprop.PropertyType,
1148                                                  member.Name + "." + subprop.Name,
1149                                                  value, isDataBound);
1150                                 is_processed = true;
1151                         }
1152                 }
1153
1154                 return is_processed;
1155         }
1156         
1157         private void AddCodeForAttributes (Type type, TagAttributes att)
1158         {
1159                 EventInfo [] ev_info = type.GetEvents ();
1160                 PropertyInfo [] prop_info = type.GetProperties ();
1161                 FieldInfo [] field_info = type.GetFields ();
1162                 bool is_processed = false;
1163                 ArrayList processed = new ArrayList ();
1164
1165                 foreach (string id in att.Keys){
1166                         if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1167                                 continue;
1168
1169                         if (id.Length > 2 && id.Substring (0, 2).ToUpper () == "ON"){
1170                                 string id_as_event = id.Substring (2);
1171                                 foreach (EventInfo ev in ev_info){
1172                                         if (0 == String.Compare (ev.Name, id_as_event, true)){
1173                                                 current_function.AppendFormat (
1174                                                                 "\t\t\t__ctrl.{0} += " + 
1175                                                                 "new {1} (this.{2});\n", 
1176                                                                 ev.Name, ev.EventHandlerType, att [id]);
1177                                                 is_processed = true;
1178                                                 break;
1179                                         }
1180                                 }
1181                                 if (is_processed){
1182                                         is_processed = false;
1183                                         continue;
1184                                 }
1185                         } 
1186
1187                         foreach (PropertyInfo prop in prop_info){
1188                                 is_processed = ProcessPropertiesAndFields (prop, id, att);
1189                                 if (is_processed)
1190                                         break;
1191                         }
1192
1193                         if (!is_processed) {
1194                                 foreach (FieldInfo field in field_info){
1195                                         is_processed = ProcessPropertiesAndFields (field, id, att);
1196                                         if (is_processed)
1197                                                 break;
1198                                 }
1199                         }
1200
1201                         if (is_processed){
1202                                 is_processed = false;
1203                                 continue;
1204                         }
1205
1206                         current_function.AppendFormat ("\t\t\t((System.Web.UI.IAttributeAccessor) __ctrl)." +
1207                                                 "SetAttribute (\"{0}\", \"{1}\");\n",
1208                                                 id, Escape ((string) att [id]));
1209                 }
1210         }
1211         
1212         private void AddCodeRenderControl (StringBuilder function)
1213         {
1214                 AddCodeRenderControl (function, controls.CodeRenderIndex);
1215         }
1216
1217         private void AddCodeRenderControl (StringBuilder function, int index)
1218         {
1219                 function.AppendFormat ("\t\t\tparameterContainer.Controls [{0}]." + 
1220                                        "RenderControl (__output);\n", index);
1221         }
1222
1223         private void AddRenderMethodDelegate (StringBuilder function, string control_id)
1224         {
1225                 function.AppendFormat ("\t\t\t__ctrl.SetRenderMethodDelegate (new System.Web." + 
1226                                        "UI.RenderMethod (this.__Render_{0}));\n", control_id);
1227         }
1228
1229         private void AddCodeRenderFunction (string codeRender, string control_id)
1230         {
1231                 StringBuilder codeRenderFunction = new StringBuilder ();
1232                 codeRenderFunction.AppendFormat ("\t\tprivate void __Render_{0} " + 
1233                                                  "(System.Web.UI.HtmlTextWriter __output, " + 
1234                                                  "System.Web.UI.Control parameterContainer)\n" +
1235                                                  "\t\t{{\n", control_id);
1236                 codeRenderFunction.Append (codeRender);
1237                 codeRenderFunction.Append ("\t\t}\n\n");
1238                 init_funcs.Append (codeRenderFunction);
1239         }
1240
1241         private void RemoveLiterals (StringBuilder function)
1242         {
1243                 string no_literals = Regex.Replace (function.ToString (),
1244                                                     @"\t\t\t__parser.AddParsedSubObject \(" + 
1245                                                     @"new System.Web.UI.LiteralControl \(.+\);\n", "");
1246                 function.Length = 0;
1247                 function.Append (no_literals);
1248         }
1249
1250         private bool FinishControlFunction (string tag_id)
1251         {
1252                 if (functions.Count == 0)
1253                         throw new ApplicationException ("Unbalanced open/close tags");
1254
1255                 if (controls.Count == 0)
1256                         return false;
1257
1258                 string saved_id = controls.PeekTagID ();
1259                 if (0 != String.Compare (saved_id, tag_id, true))
1260                         return false;
1261
1262                 FlushPlainText ();
1263                 StringBuilder old_function = (StringBuilder) functions.Pop ();
1264                 current_function = (StringBuilder) functions.Peek ();
1265
1266                 string control_id = controls.PeekControlID ();
1267                 Type control_type = controls.PeekType ();
1268                 ChildrenKind child_kind = controls.PeekChildKind ();
1269
1270                 bool hasDataBindFunction = controls.HasDataBindFunction ();
1271                 if (hasDataBindFunction)
1272                         old_function.AppendFormat ("\t\t\t__ctrl.DataBinding += new System.EventHandler " +
1273                                                    "(this.__DataBind_{0});\n", control_id);
1274
1275                 bool useCodeRender = controls.UseCodeRender;
1276                 if (useCodeRender)
1277                         AddRenderMethodDelegate (old_function, control_id);
1278                 
1279                 if (control_type == typeof (System.Web.UI.ITemplate)){
1280                         old_function.Append ("\n\t\t}\n\n");
1281                         current_function.AppendFormat ("\t\t\t__ctrl.{0} = new System.Web.UI." + 
1282                                                        "CompiledTemplateBuilder (new System.Web.UI." +
1283                                                        "BuildTemplateMethod (this.__BuildControl_{1}));\n",
1284                                                        saved_id, control_id);
1285                 }
1286                 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumnCollection)){
1287                         old_function.Append ("\n\t\t}\n\n");
1288                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1289                                                         control_id, saved_id);
1290                 }
1291                 else if (control_type == typeof (System.Web.UI.WebControls.DataGridColumn) ||
1292                          control_type.IsSubclassOf (typeof (System.Web.UI.WebControls.DataGridColumn)) ||
1293                          control_type == typeof (System.Web.UI.WebControls.ListItem)){
1294                         old_function.Append ("\n\t\t}\n\n");
1295                         string parsed = "";
1296                         string ctrl_name = "ctrl";
1297                         Type cont = controls.Container;
1298                         if (cont == null || cont == typeof (System.Web.UI.HtmlControls.HtmlSelect)){
1299                                 parsed = "ParsedSubObject";
1300                                 ctrl_name = "parser";
1301                         }
1302
1303                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1304                                                        "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1305                                                        control_id, ctrl_name, parsed);
1306                 }
1307                 else if (child_kind == ChildrenKind.LISTITEM){
1308                         old_function.Append ("\n\t\t}\n\n");
1309                         init_funcs.Append (old_function); // Closes the BuildList function
1310                         old_function = (StringBuilder) functions.Pop ();
1311                         current_function = (StringBuilder) functions.Peek ();
1312                         old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1313                                                    "return __ctrl;\n\t\t}}\n\n",
1314                                                    control_id, controls.PeekDefaultPropertyName ());
1315
1316                         controls.Pop ();
1317                         control_id = controls.PeekControlID ();
1318                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1319                                                        "AddParsedSubObject (this.{0});\n\n", control_id);
1320                 } else if (control_type == typeof (HtmlTableCell) || control_type == typeof (TableCell)) {
1321                         old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1322                         object top = controls.Pop ();
1323                         Type t = controls.PeekType ();
1324                         controls.Push (top);
1325                         string parsed = "";
1326                         string ctrl_name = "ctrl";
1327                         if (!t.IsSubclassOf (typeof (WebControl)) && t != typeof (HtmlTableRow)) {
1328                                 parsed = "ParsedSubObject";
1329                                 ctrl_name = "parser";
1330                         }
1331
1332                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n" +
1333                                                        "\t\t\t__{1}.Add{2} (this.{0});\n\n",
1334                                                        control_id, ctrl_name, parsed);
1335                 } else if (child_kind == ChildrenKind.HTMLROW || child_kind == ChildrenKind.HTMLCELL) {
1336                         old_function.Append ("\n\t\t}\n\n");
1337                         init_funcs.Append (old_function);
1338                         old_function = (StringBuilder) functions.Pop ();
1339                         current_function = (StringBuilder) functions.Peek ();
1340                         old_function.AppendFormat ("\n\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n\t\t\t" +
1341                                                    "return __ctrl;\n\t\t}}\n\n",
1342                                                    control_id, controls.PeekDefaultPropertyName ());
1343
1344                         controls.Pop ();
1345                         control_id = controls.PeekControlID ();
1346                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n", control_id);
1347                         if (child_kind == ChildrenKind.HTMLROW) {
1348                                 current_function.AppendFormat ("\t\t\t__parser.AddParsedSubObject ({0});\n",
1349                                                                 control_id);
1350                         } else {
1351                                 current_function.AppendFormat ("\t\t\t__ctrl.Add (this.{0});\n", control_id);
1352                         }
1353                 } else {
1354                         old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1355                         current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1356                                                        "AddParsedSubObject (this.{0});\n\n", control_id);
1357                 }
1358
1359                 if (useCodeRender)
1360                         RemoveLiterals (old_function);
1361
1362                 init_funcs.Append (old_function);
1363                 if (useCodeRender)
1364                         AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), control_id);
1365                 
1366                 if (hasDataBindFunction){
1367                         StringBuilder db_function = controls.DataBindFunction;
1368                         db_function.Append ("\t\t}\n\n");
1369                         init_funcs.Append (db_function);
1370                 }
1371
1372                 // Avoid getting empty stacks for unbalanced open/close tags
1373                 if (controls.Count > 1){
1374                         controls.Pop ();
1375                         AddCodeRenderControl (controls.CodeRenderFunction, controls.ChildIndex);
1376                 }
1377
1378                 return true;
1379         }
1380
1381         private void NewTableElementFunction (HtmlControlTag ctrl)
1382         {
1383                 string control_id = Tag.GetDefaultID ();
1384                 ChildrenKind child_kind;
1385
1386                 Type t;
1387                 if (ctrl.ControlType == typeof (HtmlTable)) {
1388                         t = typeof (HtmlTableRowCollection);
1389                         child_kind = ChildrenKind.HTMLROW;
1390                 } else {
1391                         t = typeof (HtmlTableCellCollection);
1392                         child_kind = ChildrenKind.HTMLCELL;
1393                 }
1394
1395                 controls.Push (ctrl.ControlType,
1396                                control_id,
1397                                ctrl.TagID,
1398                                child_kind,
1399                                ctrl.ParseChildren);
1400
1401                 current_function = new StringBuilder ();
1402                 functions.Push (current_function);
1403                 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1404                                                 "\t\t{{\n", control_id, t);
1405         }
1406
1407         private void ProcessHtmlControlTag ()
1408         {
1409                 FlushPlainText ();
1410                 HtmlControlTag html_ctrl = (HtmlControlTag) current;
1411                 if (html_ctrl.TagID.ToUpper () == "SCRIPT"){
1412                         //FIXME: if the is script is to be read from disk, do it!
1413                         if (html_ctrl.SelfClosing)
1414                                 throw new ApplicationException ("Read script from file not supported yet.");
1415
1416                         sstatus = ScriptStatus.Open;
1417                         return;
1418                 }
1419                 
1420                 if (IsApplication)
1421                         throw new ApplicationException (app_file_wrong);
1422                 
1423                 Type controlType = html_ctrl.ControlType;
1424                 AddProtectedField (controlType, html_ctrl.ControlID);
1425
1426                 ChildrenKind children_kind;
1427                 if (0 == String.Compare (html_ctrl.TagID, "table", true))
1428                         children_kind = ChildrenKind.HTMLROW;
1429                 else if (0 == String.Compare (html_ctrl.TagID, "tr", true))
1430                         children_kind = ChildrenKind.HTMLCELL;
1431                 else if (0 != String.Compare (html_ctrl.TagID, "select", true))
1432                         children_kind = html_ctrl.IsContainer ? ChildrenKind.CONTROLS :
1433                                                                 ChildrenKind.NONE;
1434                 else
1435                         children_kind = ChildrenKind.OPTION;
1436
1437                 NewControlFunction (html_ctrl.TagID, html_ctrl.ControlID, controlType, children_kind, html_ctrl.ParseChildren); 
1438
1439                 current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", html_ctrl.ControlID);
1440                 AddCodeForAttributes (html_ctrl.ControlType, html_ctrl.Attributes);
1441
1442                 if (children_kind == ChildrenKind.HTMLROW || children_kind == ChildrenKind.HTMLCELL)
1443                         NewTableElementFunction (html_ctrl);
1444
1445                 if (html_ctrl.SelfClosing)
1446                         FinishControlFunction (html_ctrl.TagID);
1447         }
1448
1449         // Closing is performed in FinishControlFunction ()
1450         private void NewBuildListFunction (AspComponent component)
1451         {
1452                 string control_id = Tag.GetDefaultID ();
1453
1454                 controls.Push (component.ComponentType,
1455                                control_id, 
1456                                component.TagID, 
1457                                component.ChildrenKind, 
1458                                component.DefaultPropertyName);
1459
1460                 Type childType = component.DefaultPropertyType;
1461                 if (childType == null)
1462                         childType = typeof (ListItemCollection);
1463
1464                 current_function = new StringBuilder ();
1465                 functions.Push (current_function);
1466                 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1467                                                 "({1} __ctrl)\n" +
1468                                                 "\t\t{{\n", control_id, childType);
1469         }
1470
1471         private void ProcessComponent ()
1472         {
1473                 FlushPlainText ();
1474                 AspComponent component = (AspComponent) current;
1475                 Type component_type = component.ComponentType;
1476                 AddProtectedField (component_type, component.ControlID);
1477
1478                 NewControlFunction (component.TagID, component.ControlID, component_type,
1479                                     component.ChildrenKind, component.DefaultPropertyName); 
1480
1481                 if (component_type == typeof (UserControl) ||
1482                     component_type.IsSubclassOf (typeof (System.Web.UI.UserControl)))
1483                         current_function.Append ("\t\t\t__ctrl.InitializeAsUserControl (Page);\n");
1484
1485                 if (component_type == typeof (Control) ||
1486                     component_type.IsSubclassOf (typeof (System.Web.UI.Control)))
1487                         current_function.AppendFormat ("\t\t\t__ctrl.ID = \"{0}\";\n", component.ControlID);
1488
1489                 AddCodeForAttributes (component.ComponentType, component.Attributes);
1490                 if (component.ChildrenKind == ChildrenKind.LISTITEM || component.DefaultPropertyType != null)
1491                         NewBuildListFunction (component);
1492
1493                 if (component.SelfClosing)
1494                         FinishControlFunction (component.TagID);
1495         }
1496
1497         private void ProcessServerObjectTag ()
1498         {
1499                 FlushPlainText ();
1500                 ServerObjectTag obj = (ServerObjectTag) current;
1501                 declarations.AppendFormat ("\t\tprivate {0} cached{1};\n", obj.ObjectClass, obj.ObjectID);
1502                 constructor.AppendFormat ("\n\t\tprivate {0} {1}\n\t\t{{\n\t\t\tget {{\n\t\t\t\t" + 
1503                                           "if (this.cached{1} == null)\n\t\t\t\t\tthis.cached{1} = " + 
1504                                           "new {0} ();\n\t\t\t\treturn cached{1};\n\t\t\t}}\n\t\t}}\n\n",
1505                                           obj.ObjectClass, obj.ObjectID);
1506         }
1507
1508         // Creates a new function that sets the values of subproperties.
1509         private void NewStyleFunction (PropertyTag tag)
1510         {
1511                 current_function = new StringBuilder ();
1512
1513                 string prop_id = tag.PropertyID;
1514                 Type prop_type = tag.PropertyType;
1515                 // begin function
1516                 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} ({1} __ctrl)\n" +
1517                                                 "\t\t{{\n", prop_id, prop_type);
1518                 
1519                 // Add property initialization code
1520                 PropertyInfo [] subprop_info = prop_type.GetProperties ();
1521                 TagAttributes att = tag.Attributes;
1522
1523                 string subprop_name = null;
1524                 foreach (string id in att.Keys){
1525                         if (0 == String.Compare (id, "runat", true) || 0 == String.Compare (id, "id", true))
1526                                 continue;
1527
1528                         bool is_processed = false;
1529                         foreach (PropertyInfo subprop in subprop_info){
1530                                 is_processed = ProcessPropertiesAndFields (subprop, id, att);
1531                                 if (is_processed){
1532                                         subprop_name = subprop.Name;
1533                                         break;
1534                                 }
1535                         }
1536
1537                         if (subprop_name == null)
1538                                 throw new ApplicationException ("Property " + tag.TagID + " does not have " + 
1539                                                                 "a " + id + " subproperty.");
1540                 }
1541
1542                 // Finish function
1543                 current_function.Append ("\n\t\t}\n\n");
1544                 init_funcs.Append (current_function);
1545                 current_function = (StringBuilder) functions.Peek ();
1546                 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} (__ctrl.{1});\n",
1547                                                 prop_id, tag.PropertyName);
1548
1549                 if (!tag.SelfClosing){
1550                         // Next tag should be the closing tag
1551                         controls.Push (null, null, null, ChildrenKind.NONE, null);
1552                         waitClosing = tag.TagID;
1553                 }
1554         }
1555
1556         // This one just opens the function. Closing is performed in FinishControlFunction ()
1557         private void NewTemplateFunction (PropertyTag tag)
1558         {
1559                 /*
1560                  * FIXME
1561                  * This function does almost the same as NewControlFunction.
1562                  * Consider merging.
1563                  */
1564                 string prop_id = tag.PropertyID;
1565                 Type prop_type = tag.PropertyType;
1566                 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1567
1568                 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.CONTROLS, null);
1569                 current_function = new StringBuilder ();
1570                 functions.Push (current_function);
1571                 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1572                                                 "(System.Web.UI.Control __ctrl)\n" +
1573                                                 "\t\t{{\n" +
1574                                                 "\t\t\tSystem.Web.UI.IParserAccessor __parser " + 
1575                                                 "= (System.Web.UI.IParserAccessor) __ctrl;\n" , prop_id);
1576         }
1577
1578         // Closing is performed in FinishControlFunction ()
1579         private void NewDBColumnFunction (PropertyTag tag)
1580         {
1581                 /*
1582                  * FIXME
1583                  * This function also does almost the same as NewControlFunction.
1584                  * Consider merging.
1585                  */
1586                 string prop_id = tag.PropertyID;
1587                 Type prop_type = tag.PropertyType;
1588                 string tag_id = tag.PropertyName; // Real property name used in FinishControlFunction
1589
1590                 controls.Push (prop_type, prop_id, tag_id, ChildrenKind.DBCOLUMNS, null);
1591                 current_function = new StringBuilder ();
1592                 functions.Push (current_function);
1593                 current_function.AppendFormat ("\t\tprivate void __BuildControl_{0} " +
1594                                                 "(System.Web.UI.WebControls.DataGridColumnCollection __ctrl)\n" +
1595                                                 "\t\t{{\n", prop_id);
1596         }
1597
1598         private void NewPropertyFunction (PropertyTag tag)
1599         {
1600                 FlushPlainText ();
1601                 if (tag.PropertyType == typeof (System.Web.UI.WebControls.Style) ||
1602                     tag.PropertyType.IsSubclassOf (typeof (System.Web.UI.WebControls.Style)))
1603                         NewStyleFunction (tag);
1604                 else if (tag.PropertyType == typeof (System.Web.UI.ITemplate))
1605                         NewTemplateFunction (tag);
1606                 else if (tag.PropertyType == typeof (System.Web.UI.WebControls.DataGridColumnCollection))
1607                         NewDBColumnFunction (tag);
1608                 else
1609                         throw new ApplicationException ("Other than Style and ITemplate not supported yet. " + 
1610                                                         tag.PropertyType);
1611         }
1612         
1613         private void ProcessHtmlTag ()
1614         {
1615                 Tag tag = (Tag) current;
1616                 ChildrenKind child_kind = controls.PeekChildKind ();
1617                 if (child_kind == ChildrenKind.NONE){
1618                         string tag_id = controls.PeekTagID ();
1619                         throw new ApplicationException (tag + " not allowed inside " + tag_id);
1620                 }
1621                                         
1622                 if (child_kind == ChildrenKind.OPTION){
1623                         if (0 != String.Compare (tag.TagID, "option", true))
1624                                 throw new ApplicationException ("Only <option> tags allowed inside <select>.");
1625
1626                         string default_id = Tag.GetDefaultID ();
1627                         Type type = typeof (System.Web.UI.WebControls.ListItem);
1628                         AddProtectedField (type, default_id);
1629                         NewControlFunction (tag.TagID, default_id, type, ChildrenKind.CONTROLS, null); 
1630                         return;
1631                 }
1632
1633                 if (child_kind == ChildrenKind.CONTROLS) {
1634                         ArrayList tag_elements = tag.GetElements ();
1635                         foreach (Element e in tag_elements) {
1636                                 if (e is PlainText) {
1637                                         current = e;
1638                                         textChunk.Append (((PlainText) e).Text);
1639                                 } else if (e is CodeRenderTag) {
1640                                         current = e;
1641                                         ProcessCodeRenderTag ();
1642                                 } else if (e is DataBindingTag) {
1643                                         current = e;
1644                                         ProcessDataBindingLiteral ();
1645                                 } else {
1646                                         throw new ApplicationException (fullPath + ": unexpected tag type " + e.GetType ());
1647                                 }
1648                         }
1649                         return;
1650                 }
1651
1652                 if (child_kind == ChildrenKind.HTMLROW) {
1653                         if (0 == String.Compare (tag.TagID, "tr", true)) {
1654                                 current = new HtmlControlTag (tag);
1655                                 ProcessHtmlControlTag ();
1656                                 return;
1657                         }
1658                 }
1659
1660                 if (child_kind == ChildrenKind.HTMLCELL) {
1661                         if (0 == String.Compare (tag.TagID, "td", true)) {
1662                                 current = new HtmlControlTag (tag);
1663                                 ProcessHtmlControlTag ();
1664                                 return;
1665                         }
1666                 }
1667
1668                 // Now child_kind should be PROPERTIES, so only allow tag_id == property
1669                 Type control_type = controls.PeekType ();
1670                 PropertyInfo [] prop_info = control_type.GetProperties ();
1671                 bool is_processed = false;
1672                 foreach (PropertyInfo prop in prop_info){
1673                         if (0 == String.Compare (prop.Name, tag.TagID, true)){
1674                                 PropertyTag prop_tag = new PropertyTag (tag, prop.PropertyType, prop.Name);
1675                                 NewPropertyFunction (prop_tag);
1676                                 is_processed = true;
1677                                 break;
1678                         }
1679                 }
1680                 
1681                 if (!is_processed){
1682                         string tag_id = controls.PeekTagID ();
1683                         throw new ApplicationException (tag.TagID + " is not a property of " + control_type);
1684                 }
1685         }
1686
1687         private Tag Map (Tag tag)
1688         {
1689                 int pos = tag.TagID.IndexOf (":");
1690                 if (pos == -1) {
1691                         ChildrenKind child_kind = controls.PeekChildKind ();
1692                         if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1693                                 tag.Attributes.Add ("runat", "server");
1694                                 return new HtmlControlTag (tag);
1695                         } else if (child_kind == ChildrenKind.HTMLROW && 0 == String.Compare (tag.TagID, "tr", true)) {
1696                                 tag.Attributes.Add ("runat", "server");
1697                                 return new HtmlControlTag (tag);
1698                         }
1699                 }
1700
1701                 if (tag is CloseTag ||
1702                     ((tag.Attributes == null || 
1703                     !tag.Attributes.IsRunAtServer ()) && pos == -1))
1704                         return tag;
1705
1706                 if (pos == -1){
1707                         if (0 == String.Compare (tag.TagID, "object", true))
1708                                 return new ServerObjectTag (tag);
1709
1710                         return new HtmlControlTag (tag);
1711                 }
1712
1713                 string foundry_name = tag.TagID.Substring (0, pos);
1714                 string component_name = tag.TagID.Substring (pos + 1);
1715
1716                 if (Foundry.LookupFoundry (foundry_name) == false)
1717                         throw new ApplicationException ("Cannot find foundry for alias'" + foundry_name + "'");
1718
1719                 AspComponent component = Foundry.MakeAspComponent (foundry_name, component_name, tag);
1720                 if (component == null)
1721                         throw new ApplicationException ("Cannot find component '" + component_name + 
1722                                                         "' for alias '" + foundry_name + "'");
1723
1724                 return component;
1725         }
1726         
1727         private void ProcessCloseTag ()
1728         {
1729                 CloseTag closeTag = (CloseTag) current;
1730                 if (FinishControlFunction (closeTag.TagID))
1731                         return;
1732
1733                 textChunk.Append (closeTag.PlainHtml);
1734         }
1735
1736         private void ProcessDataBindingLiteral ()
1737         {
1738                 FlushPlainText ();
1739                 DataBindingTag dataBinding = (DataBindingTag) current;
1740                 string actual_value = dataBinding.Data;
1741                 if (actual_value == "")
1742                         throw new ApplicationException ("Empty data binding tag.");
1743
1744                 if (controls.PeekChildKind () != ChildrenKind.CONTROLS)
1745                         throw new ApplicationException ("Data bound content not allowed for " + 
1746                                                         controls.PeekTagID ());
1747
1748                 StringBuilder db_function = new StringBuilder ();
1749                 string control_id = Tag.GetDefaultID ();
1750                 string control_type_string = "System.Web.UI.DataBoundLiteralControl";
1751                 AddProtectedField (typeof (System.Web.UI.DataBoundLiteralControl), control_id);
1752                 // Build the control
1753                 db_function.AppendFormat ("\t\tprivate System.Web.UI.Control __BuildControl_{0} ()\n" +
1754                                           "\t\t{{\n\t\t\t{1} __ctrl;\n\n" +
1755                                           "\t\t\t__ctrl = new {1} (0, 1);\n" + 
1756                                           "\t\t\tthis.{0} = __ctrl;\n" +
1757                                           "\t\t\t__ctrl.DataBinding += new System.EventHandler " + 
1758                                           "(this.__DataBind_{0});\n" +
1759                                           "\t\t\treturn __ctrl;\n"+
1760                                           "\t\t}}\n\n",
1761                                           control_id, control_type_string);
1762                 // DataBinding handler
1763                 db_function.AppendFormat ("\t\tpublic void __DataBind_{0} (object sender, " + 
1764                                           "System.EventArgs e) {{\n" +
1765                                           "\t\t\t{1} Container;\n" +
1766                                           "\t\t\t{2} target;\n" +
1767                                           "\t\t\ttarget = ({2}) sender;\n" +
1768                                           "\t\t\tContainer = ({1}) target.BindingContainer;\n" +
1769                                           "\t\t\ttarget.SetDataBoundString (0, System.Convert." +
1770                                           "ToString ({3}));\n" +
1771                                           "\t\t}}\n\n",
1772                                           control_id, controls.Container, control_type_string,
1773                                           actual_value);
1774
1775                 init_funcs.Append (db_function);
1776                 current_function.AppendFormat ("\t\t\tthis.__BuildControl_{0} ();\n\t\t\t__parser." +
1777                                                "AddParsedSubObject (this.{0});\n\n", control_id);
1778
1779                 AddCodeRenderControl (controls.CodeRenderFunction);
1780         }
1781
1782         private void ProcessCodeRenderTag ()
1783         {
1784                 FlushPlainText ();
1785                 CodeRenderTag code_tag = (CodeRenderTag) current;
1786
1787                 controls.UseCodeRender = true;
1788                 if (code_tag.IsVarName)
1789                         controls.CodeRenderFunction.AppendFormat ("\t\t\t__output.Write ({0});\n",
1790                                                                   code_tag.Code);
1791                 else
1792                         controls.CodeRenderFunction.AppendFormat ("\t\t\t{0}\n", code_tag.Code);
1793         }
1794         
1795         void FlushPlainText ()
1796         {
1797                 if (textChunk.Length != 0) {
1798                         Element saved = current;
1799                         current = new PlainText (textChunk.ToString ());
1800                         textChunk.Length = 0;
1801                         ProcessPlainText ();
1802                         current = saved;
1803                 }
1804         }
1805         
1806         void ParseError (string msg, int line, int col)
1807         {
1808                 throw new ParseException (fullPath, msg, line, col);
1809         }
1810
1811         void TagParsed (Tag tag, int line, int col)
1812         {
1813                 if (waitClosing != null) {
1814                         if (!(tag is CloseTag) || tag.TagID.ToUpper () != waitClosing.ToUpper ())
1815                                 throw new HttpException ("Tag " + waitClosing + " not properly closed.");
1816
1817                         waitClosing = null;
1818                         controls.Pop ();
1819                         return;
1820                 }
1821                 
1822                 if ((sstatus == ScriptStatus.Open || sstatus == ScriptStatus.Text) &&
1823                      tag.TagID.ToUpper () == "SCRIPT" && tag is CloseTag) {
1824                         sstatus = ScriptStatus.Close;
1825                         return;
1826                 }
1827
1828                 current = tag;
1829
1830                 if (current is Directive) {
1831                         ProcessDirective ();
1832                         return;
1833                 } else if (current is DataBindingTag) {
1834                         if (IsApplication)
1835                                 throw new ApplicationException (app_file_wrong);
1836
1837                         ProcessDataBindingLiteral ();
1838                         return;
1839                 } else if (current is CodeRenderTag) {
1840                         if (IsApplication)
1841                                 throw new ApplicationException (app_file_wrong);
1842
1843                         ProcessCodeRenderTag ();
1844                         return;
1845                 }
1846
1847                 current = Map (tag);
1848
1849                 if (current is ServerObjectTag) {
1850                         ProcessServerObjectTag ();
1851                         return;
1852                 } else if (current is HtmlControlTag) {
1853                         ProcessHtmlControlTag ();
1854                         return;
1855                 }
1856
1857                 if (IsApplication)
1858                         throw new ApplicationException (app_file_wrong);
1859
1860                 if (current is AspComponent) {
1861                         ProcessComponent ();
1862                 } else if (current is CloseTag) {
1863                         ProcessCloseTag ();
1864                 } else if (current is Tag) {
1865                         ProcessHtmlTag ();
1866                 } else {
1867                         throw new HttpException ("This place should not be reached.");
1868                 }
1869         }
1870
1871         void TextParsed (string text, int line, int col)
1872         {
1873                 if (sstatus == ScriptStatus.Open) {
1874                         script.Append (text);
1875                         sstatus = ScriptStatus.Text;
1876                         return;
1877                 }
1878
1879                 textChunk.Append (text);
1880         }
1881
1882         public void ProcessElements ()
1883         {
1884                 AspParser parser = new AspParser (fullPath, File.OpenRead (fullPath));
1885                 
1886                 parser.Error += new ParseErrorHandler (ParseError);
1887                 parser.TagParsed += new TagParsedHandler (TagParsed);
1888                 parser.TextParsed += new TextParsedHandler (TextParsed);
1889
1890                 try {
1891                         parser.Parse ();
1892                 } catch (CompilationException e) {
1893                         throw;
1894                 } catch (ParseException e) {
1895                         throw;
1896                 } catch (Exception e) {
1897                         throw new ParseException (fullPath, e.Message, parser.Line, parser.Column, e);
1898                 }
1899
1900                 End ();
1901                 parse_ok = true;
1902         }
1903         
1904         private string GetTemplateDirectory ()
1905         {
1906                 string templatePath = Path.GetDirectoryName (fullPath);
1907                 string appPath = Path.GetDirectoryName (HttpRuntime.AppDomainAppPath);
1908
1909                 if (templatePath == appPath)
1910                         return "/";
1911
1912                 templatePath = templatePath.Substring (appPath.Length);
1913                 if (Path.DirectorySeparatorChar != '/')
1914                         templatePath = templatePath.Replace (Path.DirectorySeparatorChar, '/');
1915                         
1916                 return templatePath;
1917         }
1918
1919         private void End ()
1920         {
1921                 FlushPlainText ();
1922
1923                 if (isPage) {
1924                         if (sessionState == SessionState.Enabled || sessionState == SessionState.ReadOnly)
1925                                 AddInterface (typeof (System.Web.SessionState.IRequiresSessionState));
1926
1927                         if (sessionState == SessionState.ReadOnly)
1928                                 AddInterface (typeof (System.Web.SessionState.IReadOnlySessionState));
1929                 }
1930                 
1931                 classDecl = "\tpublic class " + className + " : " + parent + interfaces + " {\n"; 
1932                 prolog.Append ("\n" + classDecl);
1933                 declarations.Append ("\t\tprivate static bool __intialized = false;\n\n");
1934                 if (IsPage)
1935                         declarations.Append ("\t\tprivate static ArrayList __fileDependencies;\n\n");
1936
1937                 // adds the constructor
1938                 constructor.AppendFormat ("\t\tpublic {0} ()\n\t\t{{\n", className);
1939                 if (!IsApplication)
1940                         constructor.Append ("\t\t\tSystem.Collections.ArrayList dependencies;\n\n");
1941                         
1942                 constructor.AppendFormat ("\t\t\tif (ASP.{0}.__intialized == false){{\n", className); 
1943
1944                 if (IsPage) {
1945                         constructor.AppendFormat ("\t\t\t\tdependencies = new System.Collections.ArrayList ();\n" +
1946                                                 "\t\t\t\tdependencies.Add (@\"{1}\");\n" +
1947                                                 "\t\t\t\tASP.{0}.__fileDependencies = dependencies;\n",
1948                                                 className, fullPath);
1949                 }
1950
1951                 constructor.AppendFormat ("\t\t\t\tASP.{0}.__intialized = true;\n\t\t\t}}\n\t\t}}\n\n",
1952                                           className);
1953          
1954                 if (!IsApplication) {
1955                         //FIXME: add AutoHandlers: don't know what for...yet!
1956                         constructor.AppendFormat (
1957                                 "\t\tprotected override int AutoHandlers\n\t\t{{\n" +
1958                                 "\t\t\tget {{ return ASP.{0}.__autoHandlers; }}\n" +
1959                                 "\t\t\tset {{ ASP.{0}.__autoHandlers = value; }}\n" +
1960                                 "\t\t}}\n\n", className);
1961
1962                         constructor.Append (
1963                                 "\t\tprotected System.Web.HttpApplication ApplicationInstance\n\t\t{\n" +
1964                                 "\t\t\tget { return (System.Web.HttpApplication) this.Context.ApplicationInstance; }\n" +
1965                                 "\t\t}\n\n");
1966
1967                         constructor.AppendFormat (
1968                                 "\t\tpublic override string TemplateSourceDirectory\n\t\t{{\n" +
1969                                 "\t\t\tget {{ return \"{0}\"; }}\n" +
1970                                 "\t\t}}\n\n", GetTemplateDirectory ());
1971
1972                         epilog.Append ("\n\t\tprotected override void FrameworkInitialize ()\n\t\t{\n" +
1973                                         "\t\t\tthis.__BuildControlTree (this);\n");
1974
1975                         if (IsPage) {
1976                                 epilog.AppendFormat ("\t\t\tthis.FileDependencies = ASP.{0}.__fileDependencies;\n" +
1977                                                         "\t\t\tthis.EnableViewStateMac = true;\n", className);
1978                         }
1979
1980                         epilog.Append ("\t\t}\n\n");
1981                 }
1982
1983                 if (IsPage) {
1984                         Random rnd = new Random ();
1985                         epilog.AppendFormat ("\t\tpublic override int GetTypeHashCode ()\n\t\t{{\n" +
1986                                              "\t\t\treturn {0};\n" +
1987                                              "\t\t}}\n", rnd.Next ());
1988                 }
1989
1990                 epilog.Append ("\t}\n}\n");
1991
1992                 // Closes the currently opened tags
1993                 StringBuilder old_function = current_function;
1994                 string control_id;
1995                 while (functions.Count > 1){
1996                         old_function.Append ("\n\t\t\treturn __ctrl;\n\t\t}\n\n");
1997                         init_funcs.Append (old_function);
1998                         control_id = controls.PeekControlID ();
1999                         FinishControlFunction (control_id);
2000                         controls.AddChild ();
2001                         old_function = (StringBuilder) functions.Pop ();
2002                         current_function = (StringBuilder) functions.Peek ();
2003                         controls.Pop ();
2004                 }
2005
2006                 bool useCodeRender = controls.UseCodeRender;
2007                 if (useCodeRender){
2008                         RemoveLiterals (current_function);
2009                         AddRenderMethodDelegate (current_function, controls.PeekControlID ());
2010                 }
2011                 
2012                 current_function.Append ("\t\t}\n\n");
2013                 init_funcs.Append (current_function);
2014                 if (useCodeRender)
2015                         AddCodeRenderFunction (controls.CodeRenderFunction.ToString (), controls.PeekControlID ());
2016
2017                 functions.Pop ();
2018         }
2019
2020         //
2021         // Functions related to compilation of user controls
2022         //
2023         
2024         private static char dirSeparator = Path.DirectorySeparatorChar;
2025         struct UserControlData
2026         {
2027                 public UserControlResult result;
2028                 public string className;
2029                 public string assemblyName;
2030         }
2031
2032         private UserControlData GenerateUserControl (string src, HttpContext context)
2033         {
2034                 UserControlData data = new UserControlData ();
2035                 data.result = UserControlResult.OK;
2036
2037                 UserControlCompiler compiler = new UserControlCompiler (new UserControlParser (src, context));
2038                 Type t = compiler.GetCompiledType ();
2039                 if (t == null) {
2040                         data.result = UserControlResult.CompilationFailed;
2041                         return data;
2042                 }
2043                 
2044                 data.className = t.Name;
2045                 data.assemblyName = compiler.TargetFile;
2046                 dependencies.Add (src);
2047                 foreach (string s in compiler.Dependencies)
2048                         dependencies.Add (s);
2049                 
2050                 return data;
2051         }
2052 }
2053
2054 }
2055