This should fix #76928. This fix incorporates ideas from a patch
[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                 protected virtual void CreateStaticFields ()
117                 {
118                         CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
119                         fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
120                         fld.InitExpression = new CodePrimitiveExpression (false);
121                         mainClass.Members.Add (fld);
122                 }
123
124                 protected virtual void CreateConstructor (CodeStatementCollection localVars,
125                                                           CodeStatementCollection trueStmt)
126                 {
127                         CodeConstructor ctor = new CodeConstructor ();
128                         ctor.Attributes = MemberAttributes.Public;
129                         mainClass.Members.Add (ctor);
130
131                         if (localVars != null)
132                                 ctor.Statements.AddRange (localVars);
133
134                         CodeTypeReferenceExpression r;
135 #if NET_2_0
136                         if (parser.IsPartial)
137                                 r = new CodeTypeReferenceExpression (mainClass.Name);
138                         else
139 #endif
140                         r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
141                         CodeFieldReferenceExpression intialized;
142                         intialized = new CodeFieldReferenceExpression (r, "__intialized");
143                         
144                         CodeBinaryOperatorExpression bin;
145                         bin = new CodeBinaryOperatorExpression (intialized,
146                                                                 CodeBinaryOperatorType.ValueEquality,
147                                                                 new CodePrimitiveExpression (false));
148
149                         CodeAssignStatement assign = new CodeAssignStatement (intialized,
150                                                                               new CodePrimitiveExpression (true));
151
152                         CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
153                         if (trueStmt != null)
154                                 cond.TrueStatements.AddRange (trueStmt);
155                         
156                         ctor.Statements.Add (cond);
157                 }
158                 
159                 void AddScripts ()
160                 {
161                         if (parser.Scripts == null || parser.Scripts.Count == 0)
162                                 return;
163
164                         foreach (object o in parser.Scripts) {
165                                 if (o is string)
166                                         mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
167                         }
168                 }
169                 
170                 protected virtual void CreateMethods ()
171                 {
172                 }
173
174                 protected virtual void AddInterfaces ()
175                 {
176                         if (parser.Interfaces == null)
177                                 return;
178
179                         foreach (object o in parser.Interfaces) {
180                                 if (o is string)
181                                         mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
182                         }
183                 }
184
185                 protected virtual void AddClassAttributes ()
186                 {
187                 }
188                 
189                 protected virtual void AddApplicationAndSessionObjects ()
190                 {
191                 }
192
193                 /* Utility methods for <object> stuff */
194                 protected void CreateApplicationOrSessionPropertyForObject (Type type,
195                                                                             string propName,
196                                                                             bool isApplication,
197                                                                             bool isPublic)
198                 {
199                         /* if isApplication this generates (the 'cachedapp' field is created earlier):
200                         private MyNS.MyClass app {
201                                 get {
202                                         if ((this.cachedapp == null)) {
203                                                 this.cachedapp = ((MyNS.MyClass)
204                                                         (this.Application.StaticObjects.GetObject("app")));
205                                         }
206                                         return this.cachedapp;
207                                 }
208                         }
209
210                         else, this is for Session:
211                         private MyNS.MyClass ses {
212                                 get {
213                                         return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
214                                 }
215                         }
216
217                         */
218
219                         CodeExpression result = null;
220
221                         CodeMemberProperty prop = new CodeMemberProperty ();
222                         prop.Type = new CodeTypeReference (type);
223                         prop.Name = propName;
224                         if (isPublic)
225                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
226                         else
227                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
228
229                         CodePropertyReferenceExpression p1;
230                         if (isApplication)
231                                 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
232                         else
233                                 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
234
235                         CodePropertyReferenceExpression p2;
236                         p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
237
238                         CodeMethodReferenceExpression getobject;
239                         getobject = new CodeMethodReferenceExpression (p2, "GetObject");
240
241                         CodeMethodInvokeExpression invoker;
242                         invoker = new CodeMethodInvokeExpression (getobject,
243                                                 new CodePrimitiveExpression (propName));
244
245                         CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
246
247                         if (isApplication) {
248                                 CodeFieldReferenceExpression field;
249                                 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
250
251                                 CodeConditionStatement stmt = new CodeConditionStatement();
252                                 stmt.Condition = new CodeBinaryOperatorExpression (field,
253                                                         CodeBinaryOperatorType.IdentityEquality,
254                                                         new CodePrimitiveExpression (null));
255
256                                 CodeAssignStatement assign = new CodeAssignStatement ();
257                                 assign.Left = field;
258                                 assign.Right = cast;
259                                 stmt.TrueStatements.Add (assign);
260                                 prop.GetStatements.Add (stmt);
261                                 result = field;
262                         } else {
263                                 result = cast;
264                         }
265                                                 
266                         prop.GetStatements.Add (new CodeMethodReturnStatement (result));
267                         mainClass.Members.Add (prop);
268                 }
269
270                 protected string CreateFieldForObject (Type type, string name)
271                 {
272                         string fieldName = "cached" + name;
273                         CodeMemberField f = new CodeMemberField (type, fieldName);
274                         f.Attributes = MemberAttributes.Private;
275                         mainClass.Members.Add (f);
276                         return fieldName;
277                 }
278
279                 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
280                 {
281                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
282                         CodeMemberProperty prop = new CodeMemberProperty ();
283                         prop.Type = new CodeTypeReference (type);
284                         prop.Name = propName;
285                         if (isPublic)
286                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
287                         else
288                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
289
290                         CodeConditionStatement stmt = new CodeConditionStatement();
291                         stmt.Condition = new CodeBinaryOperatorExpression (field,
292                                                 CodeBinaryOperatorType.IdentityEquality,
293                                                 new CodePrimitiveExpression (null));
294
295                         CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type); 
296                         stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
297                         prop.GetStatements.Add (stmt);
298                         prop.GetStatements.Add (new CodeMethodReturnStatement (field));
299
300                         mainClass.Members.Add (prop);
301                 }
302                 /******/
303
304                 void CheckCompilerErrors (CompilerResults results)
305                 {
306                         if (results.NativeCompilerReturnValue == 0)
307                                 return;
308
309                         StringWriter writer = new StringWriter();
310                         provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
311                         throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
312                 }
313
314                 protected string DynamicDir ()
315                 {
316                         return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
317                 }
318                 
319                 public virtual Type GetCompiledType () 
320                 {
321                         Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
322                         if (type != null)
323                                 return type;
324
325                         Init ();
326                         string lang = parser.Language;
327 #if CONFIGURATION_2_0
328                         CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
329                         Compiler comp = config.Compilers[lang];
330                         provider = comp.Provider;
331
332                         string compilerOptions = comp.CompilerOptions;
333                         int warningLevel = comp.WarningLevel;
334 #else
335                         CompilationConfiguration config;
336
337                         config = CompilationConfiguration.GetInstance (parser.Context);
338                         provider = config.GetProvider (lang);
339
340                         string compilerOptions = config.GetCompilerOptions (lang);
341                         int warningLevel = config.GetWarningLevel (lang);
342 #endif
343                         if (provider == null)
344                                 throw new HttpException ("Configuration error. Language not supported: " +
345                                                           lang, 500);
346
347                         compiler = provider.CreateCompiler ();
348
349                         CreateMethods ();
350                         compilerParameters.IncludeDebugInformation = parser.Debug;
351                         compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
352
353                         compilerParameters.WarningLevel = warningLevel;
354                         bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
355
356                         string tempdir = config.TempDirectory;
357                         if (tempdir == null || tempdir == "")
358                                 tempdir = DynamicDir ();
359                                 
360                         TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
361                         compilerParameters.TempFiles = tempcoll;
362                         string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
363                         compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
364
365                         CompilerResults results = CachingCompiler.Compile (this);
366                         CheckCompilerErrors (results);
367                         Assembly assembly = results.CompiledAssembly;
368                         if (assembly == null) {
369                                 if (!File.Exists (compilerParameters.OutputAssembly))
370                                         throw new CompilationException (parser.InputFile, results.Errors,
371                                                 "No assembly returned after compilation!?");
372
373                                 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
374                         }
375
376                         results.TempFiles.Delete ();
377                         Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
378
379 #if NET_2_0
380                         if (parser.IsPartial) {
381                                 // With the partial classes, we need to make sure we
382                                 // don't have any methods that should have not been
383                                 // created (because they are accessible from the base
384                                 // types). We cannot do this normally because the
385                                 // codebehind file is actually a partial class and we
386                                 // have no way of identifying the partial class' base
387                                 // type until now.
388                                 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
389                                         isRebuilding = true;
390                                         parser.RootBuilder.ResetState ();
391                                         return GetCompiledType ();
392                                 }
393                         }
394 #endif
395
396                         return mainClassType;
397                 }
398
399 #if NET_2_0
400                 internal bool IsRebuildingPartial
401                 {
402                         get { return isRebuilding; }
403                 }
404
405                 internal bool CheckPartialBaseType (Type type)
406                 {
407                         // Get the base type. If we don't have any (bad thing), we
408                         // don't need to replace ourselves. Also check for the
409                         // core file, since that won't have any either.
410                         Type baseType = type.BaseType;
411                         if (baseType == null || baseType == typeof(System.Web.UI.Page))
412                                 return false;
413
414                         bool rebuild = false;
415
416                         if (CheckPartialBaseFields (type, baseType))
417                                 rebuild = true;
418
419                         if (CheckPartialBaseProperties (type, baseType))
420                                 rebuild = true;
421
422                         return rebuild;
423                 }
424
425                 internal bool CheckPartialBaseFields (Type type, Type baseType)
426                 {
427                         bool rebuild = false;
428
429                         foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
430                                 if (baseInfo.IsPrivate)
431                                         continue;
432
433                                 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
434
435                                 if (typeInfo != null && typeInfo.DeclaringType == type) {
436                                         partialNameOverride [typeInfo.Name] = true;
437                                         rebuild = true;
438                                 }
439                         }
440
441                         return rebuild;
442                 }
443
444                 internal bool CheckPartialBaseProperties (Type type, Type baseType)
445                 {
446                         bool rebuild = false;
447
448                         foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
449                                 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
450
451                                 if (typeInfo != null && typeInfo.DeclaringType == type) {
452                                         partialNameOverride [typeInfo.Name] = true;
453                                         rebuild = true;
454                                 }
455                         }
456
457                         return rebuild;
458                 }
459 #endif
460
461                 internal CompilerParameters CompilerParameters {
462                         get { return compilerParameters; }
463                 }
464
465                 internal CodeCompileUnit Unit {
466                         get { return unit; }
467                 }
468
469                 internal virtual ICodeCompiler Compiler {
470                         get { return compiler; }
471                 }
472
473                 internal TemplateParser Parser {
474                         get { return parser; }
475                 }
476         }
477 }
478