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) {
76 string classtype = parser.PartialClassName;
78 if (classtype.Contains (".")) {
79 int dot = classtype.LastIndexOf (".");
80 ns = classtype.Substring (0, dot);
81 classtype = classtype.Substring (dot + 1);
84 mainNS = new CodeNamespace (ns);
85 mainClass = new CodeTypeDeclaration (classtype);
86 mainClass.IsPartial = true;
87 mainClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
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);
97 unit.Namespaces.Add (mainNS);
98 mainClass.TypeAttributes = TypeAttributes.Public;
99 mainNS.Types.Add (mainClass);
101 foreach (object o in parser.Imports) {
103 mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
106 if (parser.Assemblies != null) {
107 foreach (object o in parser.Assemblies) {
109 unit.ReferencedAssemblies.Add ((string) o);
113 // Late-bound generators specifics (as for MonoBASIC/VB.NET)
114 unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
115 unit.UserData["AllowLateBound"] = !parser.StrictOn;
118 AddClassAttributes ();
119 CreateStaticFields ();
120 AddApplicationAndSessionObjects ();
123 CreateConstructor (null, null);
127 internal CodeDomProvider Provider {
128 get { return provider; }
131 internal CodeCompileUnit CompileUnit {
135 protected virtual void CreateStaticFields ()
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);
143 protected virtual void CreateConstructor (CodeStatementCollection localVars,
144 CodeStatementCollection trueStmt)
146 CodeConstructor ctor = new CodeConstructor ();
147 ctor.Attributes = MemberAttributes.Public;
148 mainClass.Members.Add (ctor);
150 if (localVars != null)
151 ctor.Statements.AddRange (localVars);
153 CodeTypeReferenceExpression r;
155 if (parser.IsPartial)
156 r = new CodeTypeReferenceExpression (mainClass.Name);
159 r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
160 CodeFieldReferenceExpression initialized;
161 initialized = new CodeFieldReferenceExpression (r, "__initialized");
163 CodeBinaryOperatorExpression bin;
164 bin = new CodeBinaryOperatorExpression (initialized,
165 CodeBinaryOperatorType.ValueEquality,
166 new CodePrimitiveExpression (false));
168 CodeAssignStatement assign = new CodeAssignStatement (initialized,
169 new CodePrimitiveExpression (true));
171 CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
172 if (trueStmt != null)
173 cond.TrueStatements.AddRange (trueStmt);
175 ctor.Statements.Add (cond);
180 if (parser.Scripts == null || parser.Scripts.Count == 0)
183 foreach (object o in parser.Scripts) {
185 mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
189 protected internal virtual void CreateMethods ()
193 protected virtual void AddInterfaces ()
195 if (parser.Interfaces == null)
198 foreach (object o in parser.Interfaces) {
200 mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
204 protected virtual void AddClassAttributes ()
208 protected virtual void AddApplicationAndSessionObjects ()
212 /* Utility methods for <object> stuff */
213 protected void CreateApplicationOrSessionPropertyForObject (Type type,
218 /* if isApplication this generates (the 'cachedapp' field is created earlier):
219 private MyNS.MyClass app {
221 if ((this.cachedapp == null)) {
222 this.cachedapp = ((MyNS.MyClass)
223 (this.Application.StaticObjects.GetObject("app")));
225 return this.cachedapp;
229 else, this is for Session:
230 private MyNS.MyClass ses {
232 return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
238 CodeExpression result = null;
240 CodeMemberProperty prop = new CodeMemberProperty ();
241 prop.Type = new CodeTypeReference (type);
242 prop.Name = propName;
244 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
246 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
248 CodePropertyReferenceExpression p1;
250 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
252 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
254 CodePropertyReferenceExpression p2;
255 p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
257 CodeMethodReferenceExpression getobject;
258 getobject = new CodeMethodReferenceExpression (p2, "GetObject");
260 CodeMethodInvokeExpression invoker;
261 invoker = new CodeMethodInvokeExpression (getobject,
262 new CodePrimitiveExpression (propName));
264 CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
267 CodeFieldReferenceExpression field;
268 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
270 CodeConditionStatement stmt = new CodeConditionStatement();
271 stmt.Condition = new CodeBinaryOperatorExpression (field,
272 CodeBinaryOperatorType.IdentityEquality,
273 new CodePrimitiveExpression (null));
275 CodeAssignStatement assign = new CodeAssignStatement ();
278 stmt.TrueStatements.Add (assign);
279 prop.GetStatements.Add (stmt);
285 prop.GetStatements.Add (new CodeMethodReturnStatement (result));
286 mainClass.Members.Add (prop);
289 protected string CreateFieldForObject (Type type, string name)
291 string fieldName = "cached" + name;
292 CodeMemberField f = new CodeMemberField (type, fieldName);
293 f.Attributes = MemberAttributes.Private;
294 mainClass.Members.Add (f);
298 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
300 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
301 CodeMemberProperty prop = new CodeMemberProperty ();
302 prop.Type = new CodeTypeReference (type);
303 prop.Name = propName;
305 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
307 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
309 CodeConditionStatement stmt = new CodeConditionStatement();
310 stmt.Condition = new CodeBinaryOperatorExpression (field,
311 CodeBinaryOperatorType.IdentityEquality,
312 new CodePrimitiveExpression (null));
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));
319 mainClass.Members.Add (prop);
323 void CheckCompilerErrors (CompilerResults results)
325 if (results.NativeCompilerReturnValue == 0)
328 StringWriter writer = new StringWriter();
329 provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
330 throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
333 protected string DynamicDir ()
335 return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
338 [MonoTODO ("find out how to extract the warningLevel and compilerOptions in the <system.codedom> case")]
339 public virtual Type GetCompiledType ()
341 Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
346 string lang = parser.Language;
348 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
349 Compiler comp = config.Compilers[lang];
351 string compilerOptions = "";
352 int warningLevel = 0;
355 CompilerInfo info = CodeDomProvider.GetCompilerInfo (lang);
356 if (info != null && info.IsCodeDomProviderTypeValid)
357 provider = info.CreateProvider ();
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.
365 Type t = Type.GetType (comp.Type, true);
366 provider = Activator.CreateInstance (t) as CodeDomProvider;
368 compilerOptions = comp.CompilerOptions;
369 warningLevel = comp.WarningLevel;
373 CompilationConfiguration config;
375 config = CompilationConfiguration.GetInstance (parser.Context);
376 provider = config.GetProvider (lang);
378 string compilerOptions = config.GetCompilerOptions (lang);
379 int warningLevel = config.GetWarningLevel (lang);
381 if (provider == null)
382 throw new HttpException ("Configuration error. Language not supported: " +
385 compiler = provider.CreateCompiler ();
387 compilerParameters.IncludeDebugInformation = parser.Debug;
388 compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
390 compilerParameters.WarningLevel = warningLevel;
391 bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
393 string tempdir = config.TempDirectory;
394 if (tempdir == null || tempdir == "")
395 tempdir = DynamicDir ();
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);
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!?");
412 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
415 results.TempFiles.Delete ();
416 Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
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
427 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
429 parser.RootBuilder.ResetState ();
430 return GetCompiledType ();
435 return mainClassType;
439 internal bool IsRebuildingPartial
441 get { return isRebuilding; }
444 internal bool CheckPartialBaseType (Type type)
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))
453 bool rebuild = false;
455 if (CheckPartialBaseFields (type, baseType))
458 if (CheckPartialBaseProperties (type, baseType))
464 internal bool CheckPartialBaseFields (Type type, Type baseType)
466 bool rebuild = false;
468 foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
469 if (baseInfo.IsPrivate)
472 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
474 if (typeInfo != null && typeInfo.DeclaringType == type) {
475 partialNameOverride [typeInfo.Name] = true;
483 internal bool CheckPartialBaseProperties (Type type, Type baseType)
485 bool rebuild = false;
487 foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
488 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
490 if (typeInfo != null && typeInfo.DeclaringType == type) {
491 partialNameOverride [typeInfo.Name] = true;
500 internal CompilerParameters CompilerParameters {
501 get { return compilerParameters; }
504 internal CodeCompileUnit Unit {
508 internal virtual ICodeCompiler Compiler {
509 get { return compiler; }
512 internal TemplateParser Parser {
513 get { return parser; }