2006-02-14 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System.Web / System.Web.Compilation / BaseCompiler.cs
1 //
2 // System.Web.Compilation.BaseCompiler
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (c) Copyright 2002,2003 Ximian, Inc (http://www.ximian.com)
8 //
9
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;
32 using System.CodeDom;
33 using System.CodeDom.Compiler;
34 using System.Collections;
35 using System.Reflection;
36 using System.Text;
37 using System.Web.UI;
38 using System.Web.Configuration;
39 using System.IO;
40
41 namespace System.Web.Compilation
42 {
43         abstract class BaseCompiler
44         {
45 #if NET_2_0
46                 static BindingFlags replaceableFlags = BindingFlags.Public | BindingFlags.NonPublic |
47                                                   BindingFlags.Instance;
48 #endif
49
50                 TemplateParser parser;
51                 CodeDomProvider provider;
52                 ICodeCompiler compiler;
53                 CodeCompileUnit unit;
54                 CodeNamespace mainNS;
55                 CompilerParameters compilerParameters;
56 #if NET_2_0
57                 bool isRebuilding = false;
58                 protected Hashtable partialNameOverride = new Hashtable();
59 #endif
60                 protected CodeTypeDeclaration mainClass;
61                 protected CodeTypeReferenceExpression mainClassExpr;
62                 protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
63
64                 protected BaseCompiler (TemplateParser parser)
65                 {
66                         compilerParameters = new CompilerParameters ();
67                         this.parser = parser;
68                 }
69
70                 void Init ()
71                 {
72                         unit = new CodeCompileUnit ();
73 #if NET_2_0
74                         if (parser.IsPartial) {
75                                 mainNS = new CodeNamespace ();
76                                 mainClass = new CodeTypeDeclaration (parser.PartialClassName);
77                                 mainClass.IsPartial = true;     
78                                 mainClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
79                         } else {
80 #endif
81                         mainNS = new CodeNamespace ("ASP");
82                         mainClass = new CodeTypeDeclaration (parser.ClassName);
83                         mainClass.BaseTypes.Add (new CodeTypeReference (parser.BaseType.FullName));
84                         mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName);
85 #if NET_2_0
86                         }
87 #endif
88                         unit.Namespaces.Add (mainNS);
89                         mainClass.TypeAttributes = TypeAttributes.Public;
90                         mainNS.Types.Add (mainClass);
91
92                         foreach (object o in parser.Imports) {
93                                 if (o is string)
94                                         mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
95                         }
96
97                         if (parser.Assemblies != null) {
98                                 foreach (object o in parser.Assemblies) {
99                                         if (o is string)
100                                                 unit.ReferencedAssemblies.Add ((string) o);
101                                 }
102                         }
103
104                         // Late-bound generators specifics (as for MonoBASIC/VB.NET)
105                         unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
106                         unit.UserData["AllowLateBound"] = !parser.StrictOn;
107                         
108                         AddInterfaces ();
109                         AddClassAttributes ();
110                         CreateStaticFields ();
111                         AddApplicationAndSessionObjects ();
112                         AddScripts ();
113                         CreateConstructor (null, null);
114                 }
115
116 #if NET_2_0
117                 internal CodeDomProvider Provider {
118                         get { return provider; }
119                 }
120
121                 internal CodeCompileUnit CompileUnit {
122                         get { return unit; }
123                 }
124 #endif
125                 protected virtual void CreateStaticFields ()
126                 {
127                         CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
128                         fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
129                         fld.InitExpression = new CodePrimitiveExpression (false);
130                         mainClass.Members.Add (fld);
131                 }
132
133                 protected virtual void CreateConstructor (CodeStatementCollection localVars,
134                                                           CodeStatementCollection trueStmt)
135                 {
136                         CodeConstructor ctor = new CodeConstructor ();
137                         ctor.Attributes = MemberAttributes.Public;
138                         mainClass.Members.Add (ctor);
139
140                         if (localVars != null)
141                                 ctor.Statements.AddRange (localVars);
142
143                         CodeTypeReferenceExpression r;
144 #if NET_2_0
145                         if (parser.IsPartial)
146                                 r = new CodeTypeReferenceExpression (mainClass.Name);
147                         else
148 #endif
149                         r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
150                         CodeFieldReferenceExpression intialized;
151                         intialized = new CodeFieldReferenceExpression (r, "__intialized");
152                         
153                         CodeBinaryOperatorExpression bin;
154                         bin = new CodeBinaryOperatorExpression (intialized,
155                                                                 CodeBinaryOperatorType.ValueEquality,
156                                                                 new CodePrimitiveExpression (false));
157
158                         CodeAssignStatement assign = new CodeAssignStatement (intialized,
159                                                                               new CodePrimitiveExpression (true));
160
161                         CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
162                         if (trueStmt != null)
163                                 cond.TrueStatements.AddRange (trueStmt);
164                         
165                         ctor.Statements.Add (cond);
166                 }
167                 
168                 void AddScripts ()
169                 {
170                         if (parser.Scripts == null || parser.Scripts.Count == 0)
171                                 return;
172
173                         foreach (object o in parser.Scripts) {
174                                 if (o is string)
175                                         mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
176                         }
177                 }
178                 
179                 protected internal virtual void CreateMethods ()
180                 {
181                 }
182
183                 protected virtual void AddInterfaces ()
184                 {
185                         if (parser.Interfaces == null)
186                                 return;
187
188                         foreach (object o in parser.Interfaces) {
189                                 if (o is string)
190                                         mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
191                         }
192                 }
193
194                 protected virtual void AddClassAttributes ()
195                 {
196                 }
197                 
198                 protected virtual void AddApplicationAndSessionObjects ()
199                 {
200                 }
201
202                 /* Utility methods for <object> stuff */
203                 protected void CreateApplicationOrSessionPropertyForObject (Type type,
204                                                                             string propName,
205                                                                             bool isApplication,
206                                                                             bool isPublic)
207                 {
208                         /* if isApplication this generates (the 'cachedapp' field is created earlier):
209                         private MyNS.MyClass app {
210                                 get {
211                                         if ((this.cachedapp == null)) {
212                                                 this.cachedapp = ((MyNS.MyClass)
213                                                         (this.Application.StaticObjects.GetObject("app")));
214                                         }
215                                         return this.cachedapp;
216                                 }
217                         }
218
219                         else, this is for Session:
220                         private MyNS.MyClass ses {
221                                 get {
222                                         return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
223                                 }
224                         }
225
226                         */
227
228                         CodeExpression result = null;
229
230                         CodeMemberProperty prop = new CodeMemberProperty ();
231                         prop.Type = new CodeTypeReference (type);
232                         prop.Name = propName;
233                         if (isPublic)
234                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
235                         else
236                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
237
238                         CodePropertyReferenceExpression p1;
239                         if (isApplication)
240                                 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
241                         else
242                                 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
243
244                         CodePropertyReferenceExpression p2;
245                         p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
246
247                         CodeMethodReferenceExpression getobject;
248                         getobject = new CodeMethodReferenceExpression (p2, "GetObject");
249
250                         CodeMethodInvokeExpression invoker;
251                         invoker = new CodeMethodInvokeExpression (getobject,
252                                                 new CodePrimitiveExpression (propName));
253
254                         CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
255
256                         if (isApplication) {
257                                 CodeFieldReferenceExpression field;
258                                 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
259
260                                 CodeConditionStatement stmt = new CodeConditionStatement();
261                                 stmt.Condition = new CodeBinaryOperatorExpression (field,
262                                                         CodeBinaryOperatorType.IdentityEquality,
263                                                         new CodePrimitiveExpression (null));
264
265                                 CodeAssignStatement assign = new CodeAssignStatement ();
266                                 assign.Left = field;
267                                 assign.Right = cast;
268                                 stmt.TrueStatements.Add (assign);
269                                 prop.GetStatements.Add (stmt);
270                                 result = field;
271                         } else {
272                                 result = cast;
273                         }
274                                                 
275                         prop.GetStatements.Add (new CodeMethodReturnStatement (result));
276                         mainClass.Members.Add (prop);
277                 }
278
279                 protected string CreateFieldForObject (Type type, string name)
280                 {
281                         string fieldName = "cached" + name;
282                         CodeMemberField f = new CodeMemberField (type, fieldName);
283                         f.Attributes = MemberAttributes.Private;
284                         mainClass.Members.Add (f);
285                         return fieldName;
286                 }
287
288                 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
289                 {
290                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
291                         CodeMemberProperty prop = new CodeMemberProperty ();
292                         prop.Type = new CodeTypeReference (type);
293                         prop.Name = propName;
294                         if (isPublic)
295                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
296                         else
297                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
298
299                         CodeConditionStatement stmt = new CodeConditionStatement();
300                         stmt.Condition = new CodeBinaryOperatorExpression (field,
301                                                 CodeBinaryOperatorType.IdentityEquality,
302                                                 new CodePrimitiveExpression (null));
303
304                         CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type); 
305                         stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
306                         prop.GetStatements.Add (stmt);
307                         prop.GetStatements.Add (new CodeMethodReturnStatement (field));
308
309                         mainClass.Members.Add (prop);
310                 }
311                 /******/
312
313                 void CheckCompilerErrors (CompilerResults results)
314                 {
315                         if (results.NativeCompilerReturnValue == 0)
316                                 return;
317
318                         StringWriter writer = new StringWriter();
319                         provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
320                         throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
321                 }
322
323                 protected string DynamicDir ()
324                 {
325                         return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
326                 }
327
328                 public virtual Type GetCompiledType () 
329                 {
330                         Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
331                         if (type != null)
332                                 return type;
333
334                         Init ();
335                         string lang = parser.Language;
336 #if NET_2_0
337                         CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
338                         Compiler comp = config.Compilers[lang];
339                         Type t = Type.GetType (comp.Type, true);
340                         provider = Activator.CreateInstance (t) as CodeDomProvider;
341
342                         string compilerOptions = comp.CompilerOptions;
343                         int warningLevel = comp.WarningLevel;
344 #else
345                         CompilationConfiguration config;
346
347                         config = CompilationConfiguration.GetInstance (parser.Context);
348                         provider = config.GetProvider (lang);
349
350                         string compilerOptions = config.GetCompilerOptions (lang);
351                         int warningLevel = config.GetWarningLevel (lang);
352 #endif
353                         if (provider == null)
354                                 throw new HttpException ("Configuration error. Language not supported: " +
355                                                           lang, 500);
356
357                         compiler = provider.CreateCompiler ();
358
359                         CreateMethods ();
360                         compilerParameters.IncludeDebugInformation = parser.Debug;
361                         compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
362
363                         compilerParameters.WarningLevel = warningLevel;
364                         bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
365
366                         string tempdir = config.TempDirectory;
367                         if (tempdir == null || tempdir == "")
368                                 tempdir = DynamicDir ();
369                                 
370                         TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
371                         compilerParameters.TempFiles = tempcoll;
372                         string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
373                         compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
374
375                         CompilerResults results = CachingCompiler.Compile (this);
376                         CheckCompilerErrors (results);
377                         Assembly assembly = results.CompiledAssembly;
378                         if (assembly == null) {
379                                 if (!File.Exists (compilerParameters.OutputAssembly)) {
380                                         results.TempFiles.Delete ();
381                                         throw new CompilationException (parser.InputFile, results.Errors,
382                                                 "No assembly returned after compilation!?");
383                                 }
384
385                                 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
386                         }
387
388                         results.TempFiles.Delete ();
389                         Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
390
391 #if NET_2_0
392                         if (parser.IsPartial) {
393                                 // With the partial classes, we need to make sure we
394                                 // don't have any methods that should have not been
395                                 // created (because they are accessible from the base
396                                 // types). We cannot do this normally because the
397                                 // codebehind file is actually a partial class and we
398                                 // have no way of identifying the partial class' base
399                                 // type until now.
400                                 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
401                                         isRebuilding = true;
402                                         parser.RootBuilder.ResetState ();
403                                         return GetCompiledType ();
404                                 }
405                         }
406 #endif
407
408                         return mainClassType;
409                 }
410
411 #if NET_2_0
412                 internal bool IsRebuildingPartial
413                 {
414                         get { return isRebuilding; }
415                 }
416
417                 internal bool CheckPartialBaseType (Type type)
418                 {
419                         // Get the base type. If we don't have any (bad thing), we
420                         // don't need to replace ourselves. Also check for the
421                         // core file, since that won't have any either.
422                         Type baseType = type.BaseType;
423                         if (baseType == null || baseType == typeof(System.Web.UI.Page))
424                                 return false;
425
426                         bool rebuild = false;
427
428                         if (CheckPartialBaseFields (type, baseType))
429                                 rebuild = true;
430
431                         if (CheckPartialBaseProperties (type, baseType))
432                                 rebuild = true;
433
434                         return rebuild;
435                 }
436
437                 internal bool CheckPartialBaseFields (Type type, Type baseType)
438                 {
439                         bool rebuild = false;
440
441                         foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
442                                 if (baseInfo.IsPrivate)
443                                         continue;
444
445                                 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
446
447                                 if (typeInfo != null && typeInfo.DeclaringType == type) {
448                                         partialNameOverride [typeInfo.Name] = true;
449                                         rebuild = true;
450                                 }
451                         }
452
453                         return rebuild;
454                 }
455
456                 internal bool CheckPartialBaseProperties (Type type, Type baseType)
457                 {
458                         bool rebuild = false;
459
460                         foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
461                                 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
462
463                                 if (typeInfo != null && typeInfo.DeclaringType == type) {
464                                         partialNameOverride [typeInfo.Name] = true;
465                                         rebuild = true;
466                                 }
467                         }
468
469                         return rebuild;
470                 }
471 #endif
472
473                 internal CompilerParameters CompilerParameters {
474                         get { return compilerParameters; }
475                 }
476
477                 internal CodeCompileUnit Unit {
478                         get { return unit; }
479                 }
480
481                 internal virtual ICodeCompiler Compiler {
482                         get { return compiler; }
483                 }
484
485                 internal TemplateParser Parser {
486                         get { return parser; }
487                 }
488         }
489 }
490