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