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);
114 ArrayList al = WebConfigurationManager.ExtraAssemblies;
115 if (al != null && al.Count > 0) {
116 foreach (object o in al)
118 unit.ReferencedAssemblies.Add ((string) o);
121 IList list = BuildManager.CodeAssemblies;
122 if (list != null && list.Count > 0) {
123 foreach (object o in list)
125 unit.ReferencedAssemblies.Add ((string) o);
128 // Late-bound generators specifics (as for MonoBASIC/VB.NET)
129 unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
130 unit.UserData["AllowLateBound"] = !parser.StrictOn;
133 AddClassAttributes ();
134 CreateStaticFields ();
135 AddApplicationAndSessionObjects ();
138 CreateConstructor (null, null);
142 internal CodeDomProvider Provider {
143 get { return provider; }
146 internal CodeCompileUnit CompileUnit {
150 protected virtual void CreateStaticFields ()
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);
158 protected virtual void CreateConstructor (CodeStatementCollection localVars,
159 CodeStatementCollection trueStmt)
161 CodeConstructor ctor = new CodeConstructor ();
162 ctor.Attributes = MemberAttributes.Public;
163 mainClass.Members.Add (ctor);
165 if (localVars != null)
166 ctor.Statements.AddRange (localVars);
168 CodeTypeReferenceExpression r;
170 if (parser.IsPartial)
171 r = new CodeTypeReferenceExpression (mainClass.Name);
174 r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
175 CodeFieldReferenceExpression initialized;
176 initialized = new CodeFieldReferenceExpression (r, "__initialized");
178 CodeBinaryOperatorExpression bin;
179 bin = new CodeBinaryOperatorExpression (initialized,
180 CodeBinaryOperatorType.ValueEquality,
181 new CodePrimitiveExpression (false));
183 CodeAssignStatement assign = new CodeAssignStatement (initialized,
184 new CodePrimitiveExpression (true));
186 CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
187 if (trueStmt != null)
188 cond.TrueStatements.AddRange (trueStmt);
190 ctor.Statements.Add (cond);
195 if (parser.Scripts == null || parser.Scripts.Count == 0)
198 foreach (object o in parser.Scripts) {
200 mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
204 protected internal virtual void CreateMethods ()
208 protected virtual void AddInterfaces ()
210 if (parser.Interfaces == null)
213 foreach (object o in parser.Interfaces) {
215 mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
219 protected virtual void AddClassAttributes ()
223 protected virtual void AddApplicationAndSessionObjects ()
227 /* Utility methods for <object> stuff */
228 protected void CreateApplicationOrSessionPropertyForObject (Type type,
233 /* if isApplication this generates (the 'cachedapp' field is created earlier):
234 private MyNS.MyClass app {
236 if ((this.cachedapp == null)) {
237 this.cachedapp = ((MyNS.MyClass)
238 (this.Application.StaticObjects.GetObject("app")));
240 return this.cachedapp;
244 else, this is for Session:
245 private MyNS.MyClass ses {
247 return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
253 CodeExpression result = null;
255 CodeMemberProperty prop = new CodeMemberProperty ();
256 prop.Type = new CodeTypeReference (type);
257 prop.Name = propName;
259 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
261 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
263 CodePropertyReferenceExpression p1;
265 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
267 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
269 CodePropertyReferenceExpression p2;
270 p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
272 CodeMethodReferenceExpression getobject;
273 getobject = new CodeMethodReferenceExpression (p2, "GetObject");
275 CodeMethodInvokeExpression invoker;
276 invoker = new CodeMethodInvokeExpression (getobject,
277 new CodePrimitiveExpression (propName));
279 CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
282 CodeFieldReferenceExpression field;
283 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
285 CodeConditionStatement stmt = new CodeConditionStatement();
286 stmt.Condition = new CodeBinaryOperatorExpression (field,
287 CodeBinaryOperatorType.IdentityEquality,
288 new CodePrimitiveExpression (null));
290 CodeAssignStatement assign = new CodeAssignStatement ();
293 stmt.TrueStatements.Add (assign);
294 prop.GetStatements.Add (stmt);
300 prop.GetStatements.Add (new CodeMethodReturnStatement (result));
301 mainClass.Members.Add (prop);
304 protected string CreateFieldForObject (Type type, string name)
306 string fieldName = "cached" + name;
307 CodeMemberField f = new CodeMemberField (type, fieldName);
308 f.Attributes = MemberAttributes.Private;
309 mainClass.Members.Add (f);
313 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
315 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
316 CodeMemberProperty prop = new CodeMemberProperty ();
317 prop.Type = new CodeTypeReference (type);
318 prop.Name = propName;
320 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
322 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
324 CodeConditionStatement stmt = new CodeConditionStatement();
325 stmt.Condition = new CodeBinaryOperatorExpression (field,
326 CodeBinaryOperatorType.IdentityEquality,
327 new CodePrimitiveExpression (null));
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));
334 mainClass.Members.Add (prop);
338 void CheckCompilerErrors (CompilerResults results)
340 if (results.NativeCompilerReturnValue == 0)
343 StringWriter writer = new StringWriter();
344 provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
345 throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
348 protected string DynamicDir ()
350 return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
353 [MonoTODO ("find out how to extract the warningLevel and compilerOptions in the <system.codedom> case")]
354 public virtual Type GetCompiledType ()
356 Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
361 string lang = parser.Language;
363 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
364 Compiler comp = config.Compilers[lang];
366 string compilerOptions = "";
367 int warningLevel = 0;
370 CompilerInfo info = CodeDomProvider.GetCompilerInfo (lang);
371 if (info != null && info.IsCodeDomProviderTypeValid)
372 provider = info.CreateProvider ();
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.
380 Type t = Type.GetType (comp.Type, true);
381 provider = Activator.CreateInstance (t) as CodeDomProvider;
383 compilerOptions = comp.CompilerOptions;
384 warningLevel = comp.WarningLevel;
388 CompilationConfiguration config;
390 config = CompilationConfiguration.GetInstance (parser.Context);
391 provider = config.GetProvider (lang);
393 string compilerOptions = config.GetCompilerOptions (lang);
394 int warningLevel = config.GetWarningLevel (lang);
396 if (provider == null)
397 throw new HttpException ("Configuration error. Language not supported: " +
400 compiler = provider.CreateCompiler ();
402 compilerParameters.IncludeDebugInformation = parser.Debug;
403 compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
405 compilerParameters.WarningLevel = warningLevel;
406 bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
408 string tempdir = config.TempDirectory;
409 if (tempdir == null || tempdir == "")
410 tempdir = DynamicDir ();
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);
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!?");
427 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
430 results.TempFiles.Delete ();
431 Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
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
442 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
444 parser.RootBuilder.ResetState ();
445 return GetCompiledType ();
450 return mainClassType;
454 internal bool IsRebuildingPartial
456 get { return isRebuilding; }
459 internal bool CheckPartialBaseType (Type type)
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))
468 bool rebuild = false;
470 if (CheckPartialBaseFields (type, baseType))
473 if (CheckPartialBaseProperties (type, baseType))
479 internal bool CheckPartialBaseFields (Type type, Type baseType)
481 bool rebuild = false;
483 foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
484 if (baseInfo.IsPrivate)
487 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
489 if (typeInfo != null && typeInfo.DeclaringType == type) {
490 partialNameOverride [typeInfo.Name] = true;
498 internal bool CheckPartialBaseProperties (Type type, Type baseType)
500 bool rebuild = false;
502 foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
503 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
505 if (typeInfo != null && typeInfo.DeclaringType == type) {
506 partialNameOverride [typeInfo.Name] = true;
515 internal CompilerParameters CompilerParameters {
516 get { return compilerParameters; }
519 internal CodeCompileUnit Unit {
523 internal virtual ICodeCompiler Compiler {
524 get { return compiler; }
527 internal TemplateParser Parser {
528 get { return parser; }