* roottypes.cs: Rename from tree.cs.
[mono.git] / mcs / class / System.Web / System.Web.UI / TemplateParser.cs
1 //
2 // System.Web.UI.TemplateParser
3 //
4 // Authors:
5 //      Duncan Mak (duncan@ximian.com)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
9 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.CodeDom.Compiler;
32 using System.Collections;
33 using System.IO;
34 using System.Reflection;
35 using System.Security.Permissions;
36 using System.Web.Compilation;
37 using System.Web.Configuration;
38 using System.Web.Util;
39
40 namespace System.Web.UI {
41
42         // CAS
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45         public abstract class TemplateParser : BaseParser
46         {
47                 string inputFile;
48                 string text;
49                 string privateBinPath;
50                 Hashtable mainAttributes;
51                 ArrayList dependencies;
52                 ArrayList assemblies;
53                 Hashtable anames;
54                 ArrayList imports;
55                 ArrayList interfaces;
56                 ArrayList scripts;
57                 Type baseType;
58                 string className;
59                 RootBuilder rootBuilder;
60                 bool debug;
61                 string compilerOptions;
62                 string language;
63                 bool strictOn = false;
64                 bool explicitOn = false;
65                 bool output_cache;
66                 int oc_duration;
67                 string oc_header, oc_custom, oc_param, oc_controls;
68                 bool oc_shared;
69                 OutputCacheLocation oc_location;
70 #if NET_2_0
71                 string src;
72                 string partialClassName;
73 #endif
74                 Assembly srcAssembly;
75                 int appAssemblyIndex = -1;
76
77                 internal TemplateParser ()
78                 {
79                         imports = new ArrayList ();
80                         imports.Add ("System");
81                         imports.Add ("System.Collections");
82                         imports.Add ("System.Collections.Specialized");
83                         imports.Add ("System.Configuration");
84                         imports.Add ("System.Text");
85                         imports.Add ("System.Text.RegularExpressions");
86                         imports.Add ("System.Web");
87                         imports.Add ("System.Web.Caching");
88                         imports.Add ("System.Web.Security");
89                         imports.Add ("System.Web.SessionState");
90                         imports.Add ("System.Web.UI");
91                         imports.Add ("System.Web.UI.WebControls");
92                         imports.Add ("System.Web.UI.HtmlControls");
93
94                         assemblies = new ArrayList ();
95 #if NET_2_0
96                         bool addAssembliesInBin = false;
97                         foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
98                                 if (info.Assembly == "*")
99                                         addAssembliesInBin = true;
100                                 else
101                                         AddAssemblyByName (info.Assembly);
102                         }
103                         if (addAssembliesInBin)
104                                 AddAssembliesInBin ();
105 #else
106                         foreach (string a in CompilationConfig.Assemblies)
107                                 AddAssemblyByName (a);
108                         if (CompilationConfig.AssembliesInBin)
109                                 AddAssembliesInBin ();
110 #endif
111
112                         language = CompilationConfig.DefaultLanguage;
113                 }
114
115                 internal void AddApplicationAssembly ()
116                 {
117                         string location = Context.ApplicationInstance.AssemblyLocation;
118                         if (location != typeof (TemplateParser).Assembly.Location) {
119                                 appAssemblyIndex = assemblies.Add (location);
120                         }
121                 }
122
123                 protected abstract Type CompileIntoType ();
124
125                 internal virtual void HandleOptions (object obj)
126                 {
127                 }
128
129                 internal static string GetOneKey (Hashtable tbl)
130                 {
131                         foreach (object key in tbl.Keys)
132                                 return key.ToString ();
133
134                         return null;
135                 }
136                 
137                 internal virtual void AddDirective (string directive, Hashtable atts)
138                 {
139                         if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
140                                 if (mainAttributes != null)
141                                         ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
142
143                                 mainAttributes = atts;
144                                 ProcessMainAttributes (mainAttributes);
145                                 return;
146                         }
147
148                         int cmp = String.Compare ("Assembly", directive, true);
149                         if (cmp == 0) {
150                                 string name = GetString (atts, "Name", null);
151                                 string src = GetString (atts, "Src", null);
152
153                                 if (atts.Count > 0)
154                                         ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
155
156                                 if (name == null && src == null)
157                                         ThrowParseException ("You gotta specify Src or Name");
158                                         
159                                 if (name != null && src != null)
160                                         ThrowParseException ("Src and Name cannot be used together");
161
162                                 if (name != null) {
163                                         AddAssemblyByName (name);
164                                 } else {
165                                         GetAssemblyFromSource (src);
166                                 }
167
168                                 return;
169                         }
170
171                         cmp = String.Compare ("Import", directive, true);
172                         if (cmp == 0) {
173                                 string namesp = GetString (atts, "Namespace", null);
174                                 if (atts.Count > 0)
175                                         ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
176                                 
177                                 if (namesp != null && namesp != "")
178                                         AddImport (namesp);
179                                 return;
180                         }
181
182                         cmp = String.Compare ("Implements", directive, true);
183                         if (cmp == 0) {
184                                 string ifacename = GetString (atts, "Interface", "");
185
186                                 if (atts.Count > 0)
187                                         ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
188                                 
189                                 Type iface = LoadType (ifacename);
190                                 if (iface == null)
191                                         ThrowParseException ("Cannot find type " + ifacename);
192
193                                 if (!iface.IsInterface)
194                                         ThrowParseException (iface + " is not an interface");
195
196                                 AddInterface (iface.FullName);
197                                 return;
198                         }
199
200                         cmp = String.Compare ("OutputCache", directive, true);
201                         if (cmp == 0) {
202                                 output_cache = true;
203                                 
204                                 if (atts ["Duration"] == null)
205                                         ThrowParseException ("The directive is missing a 'duration' attribute.");
206                                 if (atts ["VaryByParam"] == null)
207                                         ThrowParseException ("This directive is missing a 'VaryByParam' " +
208                                                         "attribute, which should be set to \"none\", \"*\", " +
209                                                         "or a list of name/value pairs.");
210
211                                 foreach (DictionaryEntry entry in atts) {
212                                         string key = (string) entry.Key;
213                                         switch (key.ToLower ()) {
214                                         case "duration":
215                                                 oc_duration = Int32.Parse ((string) entry.Value);
216                                                 if (oc_duration < 1)
217                                                         ThrowParseException ("The 'duration' attribute must be set " +
218                                                                         "to a positive integer value");
219                                                 break;
220                                         case "varybyparam":
221                                                 oc_param = (string) entry.Value;
222                                                 if (String.Compare (oc_param, "none") == 0)
223                                                         oc_param = null;
224                                                 break;
225                                         case "varybyheader":
226                                                 oc_header = (string) entry.Value;
227                                                 break;
228                                         case "varybycustom":
229                                                 oc_custom = (string) entry.Value;
230                                                 break;
231                                         case "location":
232                                                 if (!(this is PageParser))
233                                                         goto default;
234
235                                                 try {
236                                                         oc_location = (OutputCacheLocation) Enum.Parse (
237                                                                 typeof (OutputCacheLocation), (string) entry.Value, true);
238                                                 } catch {
239                                                         ThrowParseException ("The 'location' attribute is case sensitive and " +
240                                                                         "must be one of the following values: Any, Client, " +
241                                                                         "Downstream, Server, None, ServerAndClient.");
242                                                 }
243                                                 break;
244                                         case "varybycontrol":
245                                                 if (this is PageParser)
246                                                         goto default;
247
248                                                 oc_controls = (string) entry.Value;
249                                                 break;
250                                         case "shared":
251                                                 if (this is PageParser)
252                                                         goto default;
253
254                                                 try {
255                                                         oc_shared = Boolean.Parse ((string) entry.Value);
256                                                 } catch {
257                                                         ThrowParseException ("The 'shared' attribute is case sensitive" +
258                                                                         " and must be set to 'true' or 'false'.");
259                                                 }
260                                                 break;
261                                         default:
262                                                 ThrowParseException ("The '" + key + "' attribute is not " +
263                                                                 "supported by the 'Outputcache' directive.");
264                                                 break;
265                                         }
266                                         
267                                 }
268                                 
269                                 return;
270                         }
271
272                         ThrowParseException ("Unknown directive: " + directive);
273                 }
274
275                 internal Type LoadType (string typeName)
276                 {
277                         // First try loaded assemblies, then try assemblies in Bin directory.
278                         Type type = null;
279                         bool seenBin = false;
280                         Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
281                         foreach (Assembly ass in assemblies) {
282                                 type = ass.GetType (typeName);
283                                 if (type == null)
284                                         continue;
285
286                                 if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
287                                         AddAssembly (ass, true);
288                                 } else {
289                                         seenBin = true;
290                                 }
291
292                                 AddDependency (ass.Location);
293                                 return type;
294                         }
295
296                         if (seenBin)
297                                 return null;
298
299                         // Load from bin
300                         if (!Directory.Exists (PrivateBinPath))
301                                 return null;
302
303                         string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
304                         foreach (string s in binDlls) {
305                                 Assembly binA = Assembly.LoadFrom (s);
306                                 type = binA.GetType (typeName);
307                                 if (type == null)
308                                         continue;
309
310                                 AddDependency (binA.Location);
311                                 return type;
312                         }
313
314                         return null;
315                 }
316
317                 void AddAssembliesInBin ()
318                 {
319                         if (!Directory.Exists (PrivateBinPath))
320                                 return;
321
322                         string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
323                         foreach (string s in binDlls) {
324                                 assemblies.Add (s);
325                         }
326                 }
327
328                 internal virtual void AddInterface (string iface)
329                 {
330                         if (interfaces == null)
331                                 interfaces = new ArrayList ();
332
333                         if (!interfaces.Contains (iface))
334                                 interfaces.Add (iface);
335                 }
336                 
337                 internal virtual void AddImport (string namesp)
338                 {
339                         if (imports == null)
340                                 imports = new ArrayList ();
341
342                         if (!imports.Contains (namesp))
343                                 imports.Add (namesp);
344                 }
345
346                 internal virtual void AddSourceDependency (string filename)
347                 {
348                         if (dependencies != null && dependencies.Contains (filename)) {
349                                 ThrowParseException ("Circular file references are not allowed. File: " + filename);
350                         }
351
352                         AddDependency (filename);
353                 }
354
355                 internal virtual void AddDependency (string filename)
356                 {
357                         if (filename == "")
358                                 return;
359
360                         if (dependencies == null)
361                                 dependencies = new ArrayList ();
362
363                         if (!dependencies.Contains (filename))
364                                 dependencies.Add (filename);
365                 }
366                 
367                 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
368                 {
369                         if (assembly.Location == "")
370                                 return;
371
372                         if (anames == null)
373                                 anames = new Hashtable ();
374
375                         string name = assembly.GetName ().Name;
376                         string loc = assembly.Location;
377                         if (fullPath) {
378                                 if (!assemblies.Contains (loc)) {
379                                         assemblies.Add (loc);
380                                 }
381
382                                 anames [name] = loc;
383                                 anames [loc] = assembly;
384                         } else {
385                                 if (!assemblies.Contains (name)) {
386                                         assemblies.Add (name);
387                                 }
388
389                                 anames [name] = assembly;
390                         }
391                 }
392
393                 internal virtual Assembly AddAssemblyByFileName (string filename)
394                 {
395                         Assembly assembly = null;
396                         Exception error = null;
397
398                         try {
399                                 assembly = Assembly.LoadFrom (filename);
400                         } catch (Exception e) { error = e; }
401
402                         if (assembly == null)
403                                 ThrowParseException ("Assembly " + filename + " not found", error);
404
405                         AddAssembly (assembly, true);
406                         return assembly;
407                 }
408
409                 internal virtual Assembly AddAssemblyByName (string name)
410                 {
411                         if (anames == null)
412                                 anames = new Hashtable ();
413
414                         if (anames.Contains (name)) {
415                                 object o = anames [name];
416                                 if (o is string)
417                                         o = anames [o];
418
419                                 return (Assembly) o;
420                         }
421
422                         Assembly assembly = null;
423                         Exception error = null;
424                         if (name.IndexOf (',') != -1) {
425                                 try {
426                                         assembly = Assembly.Load (name);
427                                 } catch (Exception e) { error = e; }
428                         }
429
430                         if (assembly == null) {
431                                 try {
432                                         assembly = Assembly.LoadWithPartialName (name);
433                                 } catch (Exception e) { error = e; }
434                         }
435                         
436                         if (assembly == null)
437                                 ThrowParseException ("Assembly " + name + " not found", error);
438
439                         AddAssembly (assembly, true);
440                         return assembly;
441                 }
442
443                 internal virtual void ProcessMainAttributes (Hashtable atts)
444                 {
445                         atts.Remove ("Description"); // ignored
446 #if NET_1_1
447                         atts.Remove ("CodeBehind");  // ignored
448 #endif
449                         atts.Remove ("AspCompat"); // ignored
450
451                         debug = GetBool (atts, "Debug", true);
452                         compilerOptions = GetString (atts, "CompilerOptions", "");
453                         language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
454                         strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
455                         explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
456
457                         string inherits = GetString (atts, "Inherits", null);
458 #if NET_2_0
459                         // In ASP 2, the source file is actually integrated with
460                         // the generated file via the use of partial classes. This
461                         // means that the code file has to be confirmed, but not
462                         // used at this point.
463                         src = GetString (atts, "CodeFile", null);
464
465                         if (src != null && inherits != null) {
466                                 // Make sure the source exists
467                                 src = UrlUtils.Combine (BaseVirtualDir, src);
468                                 string realPath = MapPath (src, false);
469                                 if (!File.Exists (realPath))
470                                         ThrowParseException ("File " + src + " not found");
471
472                                 // Verify that the inherits is a valid identify not a
473                                 // fully-qualified name.
474                                 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (inherits))
475                                         ThrowParseException (String.Format ("'{0}' is not valid for 'inherits'", inherits));
476
477                                 // We are going to create a partial class that shares
478                                 // the same name as the inherits tag, so reset the
479                                 // name. The base type is changed because it is the
480                                 // code file's responsibilty to extend the classes
481                                 // needed.
482                                 partialClassName = inherits;
483
484                                 // Add the code file as an option to the
485                                 // compiler. This lets both files be compiled at once.
486                                 compilerOptions += " \"" + realPath + "\"";
487                         } else if (inherits != null) {
488                                 // We just set the inherits directly because this is a
489                                 // Single-Page model.
490                                 SetBaseType (inherits);
491                         }
492 #else
493                         string src = GetString (atts, "Src", null);
494
495                         if (src != null)
496                                 srcAssembly = GetAssemblyFromSource (src);
497
498                         if (inherits != null)
499                                 SetBaseType (inherits);
500
501                         className = GetString (atts, "ClassName", null);
502                         if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
503                                 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
504 #endif
505
506                         if (atts.Count > 0)
507                                 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
508                 }
509
510                 internal void SetBaseType (string type)
511                 {
512                         if (type == DefaultBaseTypeName)
513                                 return;
514
515                         Type parent = null;
516                         if (srcAssembly != null)
517                                 parent = srcAssembly.GetType (type);
518
519                         if (parent == null)
520                                 parent = LoadType (type);
521
522                         if (parent == null)
523                                 ThrowParseException ("Cannot find type " + type);
524
525                         if (!DefaultBaseType.IsAssignableFrom (parent))
526                                 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
527
528                         baseType = parent;
529                 }
530
531                 Assembly GetAssemblyFromSource (string vpath)
532                 {
533                         vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
534                         string realPath = MapPath (vpath, false);
535                         if (!File.Exists (realPath))
536                                 ThrowParseException ("File " + vpath + " not found");
537
538                         AddSourceDependency (realPath);
539
540                         CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
541                         if (result.NativeCompilerReturnValue != 0) {
542                                 StreamReader reader = new StreamReader (realPath);
543                                 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
544                         }
545
546                         AddAssembly (result.CompiledAssembly, true);
547                         return result.CompiledAssembly;
548                 }
549                 
550                 internal abstract Type DefaultBaseType { get; }
551                 internal abstract string DefaultBaseTypeName { get; }
552                 internal abstract string DefaultDirectiveName { get; }
553
554                 internal string InputFile
555                 {
556                         get { return inputFile; }
557                         set { inputFile = value; }
558                 }
559
560 #if NET_2_0
561                 internal bool IsPartial
562                 {
563                         get { return src != null; }
564                 }
565
566                 internal string PartialClassName
567                 {
568                         get { return partialClassName; }
569                 }
570 #endif
571
572                 internal string Text
573                 {
574                         get { return text; }
575                         set { text = value; }
576                 }
577
578                 internal Type BaseType
579                 {
580                         get {
581                                 if (baseType == null)
582                                         baseType = DefaultBaseType;
583
584                                 return baseType;
585                         }
586                 }
587                 
588                 internal string ClassName {
589                         get {
590                                 if (className != null)
591                                         return className;
592
593                                 className = Path.GetFileName (inputFile).Replace ('.', '_');
594                                 className = className.Replace ('-', '_'); 
595                                 className = className.Replace (' ', '_');
596
597                                 if (Char.IsDigit(className[0])) {
598                                         className = "_" + className;
599                                 }
600
601                                 return className;
602                         }
603                 }
604
605                 internal string PrivateBinPath {
606                         get {
607                                 if (privateBinPath != null)
608                                         return privateBinPath;
609
610                                 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
611                                 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
612
613                                 return privateBinPath;
614                         }
615                 }
616
617                 internal ArrayList Scripts {
618                         get {
619                                 if (scripts == null)
620                                         scripts = new ArrayList ();
621
622                                 return scripts;
623                         }
624                 }
625
626                 internal ArrayList Imports {
627                         get { return imports; }
628                 }
629
630                 internal ArrayList Assemblies {
631                         get {
632                                 if (appAssemblyIndex != -1) {
633                                         object o = assemblies [appAssemblyIndex];
634                                         assemblies.RemoveAt (appAssemblyIndex);
635                                         assemblies.Add (o);
636                                         appAssemblyIndex = -1;
637                                 }
638
639                                 return assemblies;
640                         }
641                 }
642
643                 internal ArrayList Interfaces {
644                         get { return interfaces; }
645                 }
646
647                 internal RootBuilder RootBuilder {
648                         get { return rootBuilder; }
649                         set { rootBuilder = value; }
650                 }
651
652                 internal ArrayList Dependencies {
653                         get { return dependencies; }
654                         set { dependencies = value; }
655                 }
656
657                 internal string CompilerOptions {
658                         get { return compilerOptions; }
659                 }
660
661                 internal string Language {
662                         get { return language; }
663                 }
664
665                 internal bool StrictOn {
666                         get { return strictOn; }
667                 }
668
669                 internal bool ExplicitOn {
670                         get { return explicitOn; }
671                 }
672                 
673                 internal bool Debug {
674                         get { return debug; }
675                 }
676
677                 internal bool OutputCache {
678                         get { return output_cache; }
679                 }
680
681                 internal int OutputCacheDuration {
682                         get { return oc_duration; }
683                 }
684
685                 internal string OutputCacheVaryByHeader {
686                         get { return oc_header; }
687                 }
688
689                 internal string OutputCacheVaryByCustom {
690                         get { return oc_custom; }
691                 }
692
693                 internal string OutputCacheVaryByControls {
694                         get { return oc_controls; }
695                 }
696                 
697                 internal bool OutputCacheShared {
698                         get { return oc_shared; }
699                 }
700                 
701                 internal OutputCacheLocation OutputCacheLocation {
702                         get { return oc_location; }
703                 }
704
705                 internal string OutputCacheVaryByParam {
706                         get { return oc_param; }
707                 }
708
709 #if NET_2_0
710                 internal PagesSection PagesConfig {
711                         get {
712                                 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
713                         }
714                 }
715 #else
716                 internal PagesConfiguration PagesConfig {
717                         get { return PagesConfiguration.GetInstance (Context); }
718                 }
719 #endif
720         }
721 }
722