2 // System.Web.Compilation.BaseCompiler
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (c) Copyright 2002,2003 Ximian, Inc (http://www.ximian.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
33 using System.CodeDom.Compiler;
34 using System.Collections;
35 using System.Reflection;
38 using System.Web.Configuration;
41 namespace System.Web.Compilation
43 abstract class BaseCompiler
46 static BindingFlags replaceableFlags = BindingFlags.Public | BindingFlags.NonPublic |
47 BindingFlags.Instance;
50 TemplateParser parser;
51 CodeDomProvider provider;
52 ICodeCompiler compiler;
55 CompilerParameters compilerParameters;
57 bool isRebuilding = false;
58 protected Hashtable partialNameOverride = new Hashtable();
60 protected CodeTypeDeclaration mainClass;
61 protected CodeTypeReferenceExpression mainClassExpr;
62 protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
64 protected BaseCompiler (TemplateParser parser)
66 compilerParameters = new CompilerParameters ();
72 unit = new CodeCompileUnit ();
74 if (parser.IsPartial) {
75 mainNS = new CodeNamespace ();
76 mainClass = new CodeTypeDeclaration (parser.PartialClassName);
77 mainClass.IsPartial = true;
78 mainClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
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);
88 unit.Namespaces.Add (mainNS);
89 mainClass.TypeAttributes = TypeAttributes.Public;
90 mainNS.Types.Add (mainClass);
92 foreach (object o in parser.Imports) {
94 mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
97 if (parser.Assemblies != null) {
98 foreach (object o in parser.Assemblies) {
100 unit.ReferencedAssemblies.Add ((string) o);
104 // Late-bound generators specifics (as for MonoBASIC/VB.NET)
105 unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
106 unit.UserData["AllowLateBound"] = !parser.StrictOn;
109 AddClassAttributes ();
110 CreateStaticFields ();
111 AddApplicationAndSessionObjects ();
113 CreateConstructor (null, null);
117 internal CodeDomProvider Provider {
118 get { return provider; }
121 internal CodeCompileUnit CompileUnit {
125 protected virtual void CreateStaticFields ()
127 CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
128 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
129 fld.InitExpression = new CodePrimitiveExpression (false);
130 mainClass.Members.Add (fld);
133 protected virtual void CreateConstructor (CodeStatementCollection localVars,
134 CodeStatementCollection trueStmt)
136 CodeConstructor ctor = new CodeConstructor ();
137 ctor.Attributes = MemberAttributes.Public;
138 mainClass.Members.Add (ctor);
140 if (localVars != null)
141 ctor.Statements.AddRange (localVars);
143 CodeTypeReferenceExpression r;
145 if (parser.IsPartial)
146 r = new CodeTypeReferenceExpression (mainClass.Name);
149 r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
150 CodeFieldReferenceExpression intialized;
151 intialized = new CodeFieldReferenceExpression (r, "__intialized");
153 CodeBinaryOperatorExpression bin;
154 bin = new CodeBinaryOperatorExpression (intialized,
155 CodeBinaryOperatorType.ValueEquality,
156 new CodePrimitiveExpression (false));
158 CodeAssignStatement assign = new CodeAssignStatement (intialized,
159 new CodePrimitiveExpression (true));
161 CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
162 if (trueStmt != null)
163 cond.TrueStatements.AddRange (trueStmt);
165 ctor.Statements.Add (cond);
170 if (parser.Scripts == null || parser.Scripts.Count == 0)
173 foreach (object o in parser.Scripts) {
175 mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
179 protected internal virtual void CreateMethods ()
183 protected virtual void AddInterfaces ()
185 if (parser.Interfaces == null)
188 foreach (object o in parser.Interfaces) {
190 mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
194 protected virtual void AddClassAttributes ()
198 protected virtual void AddApplicationAndSessionObjects ()
202 /* Utility methods for <object> stuff */
203 protected void CreateApplicationOrSessionPropertyForObject (Type type,
208 /* if isApplication this generates (the 'cachedapp' field is created earlier):
209 private MyNS.MyClass app {
211 if ((this.cachedapp == null)) {
212 this.cachedapp = ((MyNS.MyClass)
213 (this.Application.StaticObjects.GetObject("app")));
215 return this.cachedapp;
219 else, this is for Session:
220 private MyNS.MyClass ses {
222 return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
228 CodeExpression result = null;
230 CodeMemberProperty prop = new CodeMemberProperty ();
231 prop.Type = new CodeTypeReference (type);
232 prop.Name = propName;
234 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
236 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
238 CodePropertyReferenceExpression p1;
240 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
242 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
244 CodePropertyReferenceExpression p2;
245 p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
247 CodeMethodReferenceExpression getobject;
248 getobject = new CodeMethodReferenceExpression (p2, "GetObject");
250 CodeMethodInvokeExpression invoker;
251 invoker = new CodeMethodInvokeExpression (getobject,
252 new CodePrimitiveExpression (propName));
254 CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
257 CodeFieldReferenceExpression field;
258 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
260 CodeConditionStatement stmt = new CodeConditionStatement();
261 stmt.Condition = new CodeBinaryOperatorExpression (field,
262 CodeBinaryOperatorType.IdentityEquality,
263 new CodePrimitiveExpression (null));
265 CodeAssignStatement assign = new CodeAssignStatement ();
268 stmt.TrueStatements.Add (assign);
269 prop.GetStatements.Add (stmt);
275 prop.GetStatements.Add (new CodeMethodReturnStatement (result));
276 mainClass.Members.Add (prop);
279 protected string CreateFieldForObject (Type type, string name)
281 string fieldName = "cached" + name;
282 CodeMemberField f = new CodeMemberField (type, fieldName);
283 f.Attributes = MemberAttributes.Private;
284 mainClass.Members.Add (f);
288 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
290 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
291 CodeMemberProperty prop = new CodeMemberProperty ();
292 prop.Type = new CodeTypeReference (type);
293 prop.Name = propName;
295 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
297 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
299 CodeConditionStatement stmt = new CodeConditionStatement();
300 stmt.Condition = new CodeBinaryOperatorExpression (field,
301 CodeBinaryOperatorType.IdentityEquality,
302 new CodePrimitiveExpression (null));
304 CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
305 stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
306 prop.GetStatements.Add (stmt);
307 prop.GetStatements.Add (new CodeMethodReturnStatement (field));
309 mainClass.Members.Add (prop);
313 void CheckCompilerErrors (CompilerResults results)
315 if (results.NativeCompilerReturnValue == 0)
318 StringWriter writer = new StringWriter();
319 provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
320 throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
323 protected string DynamicDir ()
325 return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
328 public virtual Type GetCompiledType ()
330 Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
335 string lang = parser.Language;
337 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
338 Compiler comp = config.Compilers[lang];
339 Type t = Type.GetType (comp.Type, true);
340 provider = Activator.CreateInstance (t) as CodeDomProvider;
342 string compilerOptions = comp.CompilerOptions;
343 int warningLevel = comp.WarningLevel;
345 CompilationConfiguration config;
347 config = CompilationConfiguration.GetInstance (parser.Context);
348 provider = config.GetProvider (lang);
350 string compilerOptions = config.GetCompilerOptions (lang);
351 int warningLevel = config.GetWarningLevel (lang);
353 if (provider == null)
354 throw new HttpException ("Configuration error. Language not supported: " +
357 compiler = provider.CreateCompiler ();
360 compilerParameters.IncludeDebugInformation = parser.Debug;
361 compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
363 compilerParameters.WarningLevel = warningLevel;
364 bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
366 string tempdir = config.TempDirectory;
367 if (tempdir == null || tempdir == "")
368 tempdir = DynamicDir ();
370 TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
371 compilerParameters.TempFiles = tempcoll;
372 string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
373 compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
375 CompilerResults results = CachingCompiler.Compile (this);
376 CheckCompilerErrors (results);
377 Assembly assembly = results.CompiledAssembly;
378 if (assembly == null) {
379 if (!File.Exists (compilerParameters.OutputAssembly)) {
380 results.TempFiles.Delete ();
381 throw new CompilationException (parser.InputFile, results.Errors,
382 "No assembly returned after compilation!?");
385 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
388 results.TempFiles.Delete ();
389 Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
392 if (parser.IsPartial) {
393 // With the partial classes, we need to make sure we
394 // don't have any methods that should have not been
395 // created (because they are accessible from the base
396 // types). We cannot do this normally because the
397 // codebehind file is actually a partial class and we
398 // have no way of identifying the partial class' base
400 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
402 parser.RootBuilder.ResetState ();
403 return GetCompiledType ();
408 return mainClassType;
412 internal bool IsRebuildingPartial
414 get { return isRebuilding; }
417 internal bool CheckPartialBaseType (Type type)
419 // Get the base type. If we don't have any (bad thing), we
420 // don't need to replace ourselves. Also check for the
421 // core file, since that won't have any either.
422 Type baseType = type.BaseType;
423 if (baseType == null || baseType == typeof(System.Web.UI.Page))
426 bool rebuild = false;
428 if (CheckPartialBaseFields (type, baseType))
431 if (CheckPartialBaseProperties (type, baseType))
437 internal bool CheckPartialBaseFields (Type type, Type baseType)
439 bool rebuild = false;
441 foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
442 if (baseInfo.IsPrivate)
445 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
447 if (typeInfo != null && typeInfo.DeclaringType == type) {
448 partialNameOverride [typeInfo.Name] = true;
456 internal bool CheckPartialBaseProperties (Type type, Type baseType)
458 bool rebuild = false;
460 foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
461 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
463 if (typeInfo != null && typeInfo.DeclaringType == type) {
464 partialNameOverride [typeInfo.Name] = true;
473 internal CompilerParameters CompilerParameters {
474 get { return compilerParameters; }
477 internal CodeCompileUnit Unit {
481 internal virtual ICodeCompiler Compiler {
482 get { return compiler; }
485 internal TemplateParser Parser {
486 get { return parser; }