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