2004-09-01 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System.Web / System.Web.Compilation / BaseCompiler.cs
1 //
2 // System.Web.Compilation.BaseCompiler
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (c) Copyright 2002,2003 Ximian, Inc (http://www.ximian.com)
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.CodeDom;
33 using System.CodeDom.Compiler;
34 using System.Collections;
35 using System.Reflection;
36 using System.Text;
37 using System.Web.UI;
38 using System.Web.Configuration;
39 using System.IO;
40
41 namespace System.Web.Compilation
42 {
43         abstract class BaseCompiler
44         {
45                 protected static string dynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
46                 TemplateParser parser;
47                 CodeDomProvider provider;
48                 ICodeCompiler compiler;
49                 CodeCompileUnit unit;
50                 CodeNamespace mainNS;
51                 CompilerParameters compilerParameters;
52                 protected CodeTypeDeclaration mainClass;
53                 protected CodeTypeReferenceExpression mainClassExpr;
54                 protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
55
56                 protected BaseCompiler (TemplateParser parser)
57                 {
58                         compilerParameters = new CompilerParameters ();
59                         this.parser = parser;
60                 }
61
62                 void Init ()
63                 {
64                         unit = new CodeCompileUnit ();
65                         mainNS = new CodeNamespace ("ASP");
66                         unit.Namespaces.Add (mainNS);
67                         mainClass = new CodeTypeDeclaration (parser.ClassName);
68                         mainClass.TypeAttributes = TypeAttributes.Public;
69                         mainNS.Types.Add (mainClass);
70                         mainClass.BaseTypes.Add (new CodeTypeReference (parser.BaseType.FullName));
71                         mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName);
72                         foreach (object o in parser.Imports) {
73                                 if (o is string)
74                                         mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
75                         }
76
77                         if (parser.Assemblies != null) {
78                                 foreach (object o in parser.Assemblies) {
79                                         if (o is string)
80                                                 unit.ReferencedAssemblies.Add ((string) o);
81                                 }
82                         }
83
84                         AddInterfaces ();
85                         AddClassAttributes ();
86                         CreateStaticFields ();
87                         AddApplicationAndSessionObjects ();
88                         AddScripts ();
89                         CreateConstructor (null, null);
90                 }
91
92                 protected virtual void CreateStaticFields ()
93                 {
94                         CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
95                         fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
96                         fld.InitExpression = new CodePrimitiveExpression (false);
97                         mainClass.Members.Add (fld);
98                 }
99
100                 protected virtual void CreateConstructor (CodeStatementCollection localVars,
101                                                           CodeStatementCollection trueStmt)
102                 {
103                         CodeConstructor ctor = new CodeConstructor ();
104                         ctor.Attributes = MemberAttributes.Public;
105                         mainClass.Members.Add (ctor);
106
107                         if (localVars != null)
108                                 ctor.Statements.AddRange (localVars);
109
110                         CodeTypeReferenceExpression r;
111                         r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
112                         CodeFieldReferenceExpression intialized;
113                         intialized = new CodeFieldReferenceExpression (r, "__intialized");
114                         
115                         CodeBinaryOperatorExpression bin;
116                         bin = new CodeBinaryOperatorExpression (intialized,
117                                                                 CodeBinaryOperatorType.ValueEquality,
118                                                                 new CodePrimitiveExpression (false));
119
120                         CodeAssignStatement assign = new CodeAssignStatement (intialized,
121                                                                               new CodePrimitiveExpression (true));
122
123                         CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
124                         if (trueStmt != null)
125                                 cond.TrueStatements.AddRange (trueStmt);
126                         
127                         ctor.Statements.Add (cond);
128                 }
129                 
130                 void AddScripts ()
131                 {
132                         if (parser.Scripts == null || parser.Scripts.Count == 0)
133                                 return;
134
135                         foreach (object o in parser.Scripts) {
136                                 if (o is string)
137                                         mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
138                         }
139                 }
140                 
141                 protected virtual void CreateMethods ()
142                 {
143                 }
144
145                 protected virtual void AddInterfaces ()
146                 {
147                         if (parser.Interfaces == null)
148                                 return;
149
150                         foreach (object o in parser.Interfaces) {
151                                 if (o is string)
152                                         mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
153                         }
154                 }
155
156                 protected virtual void AddClassAttributes ()
157                 {
158                 }
159                 
160                 protected virtual void AddApplicationAndSessionObjects ()
161                 {
162                 }
163
164                 /* Utility methods for <object> stuff */
165                 protected void CreateApplicationOrSessionPropertyForObject (Type type,
166                                                                             string propName,
167                                                                             bool isApplication,
168                                                                             bool isPublic)
169                 {
170                         /* if isApplication this generates (the 'cachedapp' field is created earlier):
171                         private MyNS.MyClass app {
172                                 get {
173                                         if ((this.cachedapp == null)) {
174                                                 this.cachedapp = ((MyNS.MyClass)
175                                                         (this.Application.StaticObjects.GetObject("app")));
176                                         }
177                                         return this.cachedapp;
178                                 }
179                         }
180
181                         else, this is for Session:
182                         private MyNS.MyClass ses {
183                                 get {
184                                         return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
185                                 }
186                         }
187
188                         */
189
190                         CodeExpression result = null;
191
192                         CodeMemberProperty prop = new CodeMemberProperty ();
193                         prop.Type = new CodeTypeReference (type);
194                         prop.Name = propName;
195                         if (isPublic)
196                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
197                         else
198                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
199
200                         CodePropertyReferenceExpression p1;
201                         if (isApplication)
202                                 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
203                         else
204                                 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
205
206                         CodePropertyReferenceExpression p2;
207                         p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
208
209                         CodeMethodReferenceExpression getobject;
210                         getobject = new CodeMethodReferenceExpression (p2, "GetObject");
211
212                         CodeMethodInvokeExpression invoker;
213                         invoker = new CodeMethodInvokeExpression (getobject,
214                                                 new CodePrimitiveExpression (propName));
215
216                         CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
217
218                         if (isApplication) {
219                                 CodeFieldReferenceExpression field;
220                                 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
221
222                                 CodeConditionStatement stmt = new CodeConditionStatement();
223                                 stmt.Condition = new CodeBinaryOperatorExpression (field,
224                                                         CodeBinaryOperatorType.IdentityEquality,
225                                                         new CodePrimitiveExpression (null));
226
227                                 CodeAssignStatement assign = new CodeAssignStatement ();
228                                 assign.Left = field;
229                                 assign.Right = cast;
230                                 stmt.TrueStatements.Add (assign);
231                                 prop.GetStatements.Add (stmt);
232                                 result = field;
233                         } else {
234                                 result = cast;
235                         }
236                                                 
237                         prop.GetStatements.Add (new CodeMethodReturnStatement (result));
238                         mainClass.Members.Add (prop);
239                 }
240
241                 protected string CreateFieldForObject (Type type, string name)
242                 {
243                         string fieldName = "cached" + name;
244                         CodeMemberField f = new CodeMemberField (type, fieldName);
245                         f.Attributes = MemberAttributes.Private;
246                         mainClass.Members.Add (f);
247                         return fieldName;
248                 }
249
250                 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
251                 {
252                         CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
253                         CodeMemberProperty prop = new CodeMemberProperty ();
254                         prop.Type = new CodeTypeReference (type);
255                         prop.Name = propName;
256                         if (isPublic)
257                                 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
258                         else
259                                 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
260
261                         CodeConditionStatement stmt = new CodeConditionStatement();
262                         stmt.Condition = new CodeBinaryOperatorExpression (field,
263                                                 CodeBinaryOperatorType.IdentityEquality,
264                                                 new CodePrimitiveExpression (null));
265
266                         CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type); 
267                         stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
268                         prop.GetStatements.Add (stmt);
269                         prop.GetStatements.Add (new CodeMethodReturnStatement (field));
270
271                         mainClass.Members.Add (prop);
272                 }
273                 /******/
274
275                 void CheckCompilerErrors (CompilerResults results)
276                 {
277                         if (results.NativeCompilerReturnValue == 0)
278                                 return;
279
280                         StringWriter writer = new StringWriter();
281                         provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
282                         throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
283                 }
284
285                 public virtual Type GetCompiledType () 
286                 {
287                         Type type = CachingCompiler.GetTypeFromCache (parser.InputFile, parser.ClassName);
288                         if (type != null)
289                                 return type;
290
291                         Init ();
292                         string lang = parser.Language;
293                         CompilationConfiguration config;
294
295                         config = CompilationConfiguration.GetInstance (parser.Context);
296                         provider = config.GetProvider (lang);
297                         if (provider == null)
298                                 throw new HttpException ("Configuration error. Language not supported: " +
299                                                           lang, 500);
300
301                         compiler = provider.CreateCompiler ();
302
303                         CreateMethods ();
304                         compilerParameters.IncludeDebugInformation = parser.Debug;
305                         compilerParameters.CompilerOptions = config.GetCompilerOptions (lang) + " " +
306                                                              parser.CompilerOptions;
307
308                         compilerParameters.WarningLevel = config.GetWarningLevel (lang);
309                         bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
310                         TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, keepFiles);
311                         compilerParameters.TempFiles = tempcoll;
312                         string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
313                         if (!Directory.Exists (dynamicBase))
314                                 Directory.CreateDirectory (dynamicBase);
315
316                         compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename);
317
318                         CompilerResults results = CachingCompiler.Compile (this);
319                         CheckCompilerErrors (results);
320                         if (results.CompiledAssembly == null)
321                                 throw new CompilationException (parser.InputFile, results.Errors,
322                                         "No assembly returned after compilation!?");
323
324                         results.TempFiles.Delete ();
325                         return results.CompiledAssembly.GetType (mainClassExpr.Type.BaseType, true);
326                 }
327
328                 internal CompilerParameters CompilerParameters {
329                         get { return compilerParameters; }
330                 }
331
332                 internal CodeCompileUnit Unit {
333                         get { return unit; }
334                 }
335
336                 internal virtual ICodeCompiler Compiler {
337                         get { return compiler; }
338                 }
339
340                 internal TemplateParser Parser {
341                         get { return parser; }
342                 }
343         }
344 }
345