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