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.Collections.Specialized;
36 using System.Reflection;
39 using System.Web.Configuration;
42 namespace System.Web.Compilation
44 abstract class BaseCompiler
47 static BindingFlags replaceableFlags = BindingFlags.Public | BindingFlags.NonPublic |
48 BindingFlags.Instance;
51 TemplateParser parser;
52 CodeDomProvider provider;
53 ICodeCompiler compiler;
56 CompilerParameters compilerParameters;
58 bool isRebuilding = false;
59 protected Hashtable partialNameOverride = new Hashtable();
61 protected CodeTypeDeclaration mainClass;
62 protected CodeTypeReferenceExpression mainClassExpr;
63 protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
65 protected BaseCompiler (TemplateParser parser)
67 compilerParameters = new CompilerParameters ();
73 unit = new CodeCompileUnit ();
75 if (parser.IsPartial) {
77 string classtype = parser.PartialClassName;
79 if (classtype.Contains (".")) {
80 int dot = classtype.LastIndexOf (".");
81 ns = classtype.Substring (0, dot);
82 classtype = classtype.Substring (dot + 1);
85 mainNS = new CodeNamespace (ns);
86 mainClass = new CodeTypeDeclaration (classtype);
87 mainClass.IsPartial = true;
88 mainClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
91 mainNS = new CodeNamespace ("ASP");
92 mainClass = new CodeTypeDeclaration (parser.ClassName);
93 CodeTypeReference baseTypeRef = new CodeTypeReference (parser.BaseType.FullName);
95 if (parser.BaseTypeIsGlobal)
96 baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
98 mainClass.BaseTypes.Add (baseTypeRef);
99 mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName);
103 unit.Namespaces.Add (mainNS);
104 mainClass.TypeAttributes = TypeAttributes.Public;
105 mainNS.Types.Add (mainClass);
107 foreach (object o in parser.Imports) {
109 mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
112 // StringCollection.Contains has O(n) complexity, but
113 // considering the number of comparisons we make on
114 // average and the fact that using an intermediate array
115 // would be even more costly, this is fine here.
116 StringCollection refAsm = unit.ReferencedAssemblies;
118 if (parser.Assemblies != null) {
119 foreach (object o in parser.Assemblies) {
120 asmName = o as string;
121 if (asmName != null && !refAsm.Contains (asmName))
122 refAsm.Add (asmName);
127 ArrayList al = WebConfigurationManager.ExtraAssemblies;
128 if (al != null && al.Count > 0) {
129 foreach (object o in al) {
130 asmName = o as string;
131 if (asmName != null && !refAsm.Contains (asmName))
132 refAsm.Add (asmName);
136 IList list = BuildManager.CodeAssemblies;
137 if (list != null && list.Count > 0) {
138 foreach (object o in list) {
139 asmName = o as string;
140 if (asmName != null && !refAsm.Contains (asmName))
141 refAsm.Add (asmName);
145 // Late-bound generators specifics (as for MonoBASIC/VB.NET)
146 unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
147 unit.UserData["AllowLateBound"] = !parser.StrictOn;
150 AddClassAttributes ();
151 CreateStaticFields ();
152 AddApplicationAndSessionObjects ();
155 CreateConstructor (null, null);
159 internal CodeDomProvider Provider {
160 get { return provider; }
163 internal CodeCompileUnit CompileUnit {
167 protected virtual void CreateStaticFields ()
169 CodeMemberField fld = new CodeMemberField (typeof (bool), "__initialized");
170 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
171 fld.InitExpression = new CodePrimitiveExpression (false);
172 mainClass.Members.Add (fld);
175 protected virtual void CreateConstructor (CodeStatementCollection localVars,
176 CodeStatementCollection trueStmt)
178 CodeConstructor ctor = new CodeConstructor ();
179 ctor.Attributes = MemberAttributes.Public;
180 mainClass.Members.Add (ctor);
182 if (localVars != null)
183 ctor.Statements.AddRange (localVars);
185 CodeTypeReferenceExpression r;
187 if (parser.IsPartial)
188 r = new CodeTypeReferenceExpression (mainClass.Name);
191 r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
192 CodeFieldReferenceExpression initialized;
193 initialized = new CodeFieldReferenceExpression (r, "__initialized");
195 CodeBinaryOperatorExpression bin;
196 bin = new CodeBinaryOperatorExpression (initialized,
197 CodeBinaryOperatorType.ValueEquality,
198 new CodePrimitiveExpression (false));
200 CodeAssignStatement assign = new CodeAssignStatement (initialized,
201 new CodePrimitiveExpression (true));
203 CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
204 if (trueStmt != null)
205 cond.TrueStatements.AddRange (trueStmt);
207 ctor.Statements.Add (cond);
212 if (parser.Scripts == null || parser.Scripts.Count == 0)
215 foreach (object o in parser.Scripts) {
217 mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
221 protected internal virtual void CreateMethods ()
225 protected virtual void AddInterfaces ()
227 if (parser.Interfaces == null)
230 foreach (object o in parser.Interfaces) {
232 mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
236 protected virtual void AddClassAttributes ()
240 protected virtual void AddApplicationAndSessionObjects ()
244 /* Utility methods for <object> stuff */
245 protected void CreateApplicationOrSessionPropertyForObject (Type type,
250 /* if isApplication this generates (the 'cachedapp' field is created earlier):
251 private MyNS.MyClass app {
253 if ((this.cachedapp == null)) {
254 this.cachedapp = ((MyNS.MyClass)
255 (this.Application.StaticObjects.GetObject("app")));
257 return this.cachedapp;
261 else, this is for Session:
262 private MyNS.MyClass ses {
264 return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
270 CodeExpression result = null;
272 CodeMemberProperty prop = new CodeMemberProperty ();
273 prop.Type = new CodeTypeReference (type);
274 prop.Name = propName;
276 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
278 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
280 CodePropertyReferenceExpression p1;
282 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
284 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
286 CodePropertyReferenceExpression p2;
287 p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
289 CodeMethodReferenceExpression getobject;
290 getobject = new CodeMethodReferenceExpression (p2, "GetObject");
292 CodeMethodInvokeExpression invoker;
293 invoker = new CodeMethodInvokeExpression (getobject,
294 new CodePrimitiveExpression (propName));
296 CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
299 CodeFieldReferenceExpression field;
300 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
302 CodeConditionStatement stmt = new CodeConditionStatement();
303 stmt.Condition = new CodeBinaryOperatorExpression (field,
304 CodeBinaryOperatorType.IdentityEquality,
305 new CodePrimitiveExpression (null));
307 CodeAssignStatement assign = new CodeAssignStatement ();
310 stmt.TrueStatements.Add (assign);
311 prop.GetStatements.Add (stmt);
317 prop.GetStatements.Add (new CodeMethodReturnStatement (result));
318 mainClass.Members.Add (prop);
321 protected string CreateFieldForObject (Type type, string name)
323 string fieldName = "cached" + name;
324 CodeMemberField f = new CodeMemberField (type, fieldName);
325 f.Attributes = MemberAttributes.Private;
326 mainClass.Members.Add (f);
330 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
332 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
333 CodeMemberProperty prop = new CodeMemberProperty ();
334 prop.Type = new CodeTypeReference (type);
335 prop.Name = propName;
337 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
339 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
341 CodeConditionStatement stmt = new CodeConditionStatement();
342 stmt.Condition = new CodeBinaryOperatorExpression (field,
343 CodeBinaryOperatorType.IdentityEquality,
344 new CodePrimitiveExpression (null));
346 CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
347 stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
348 prop.GetStatements.Add (stmt);
349 prop.GetStatements.Add (new CodeMethodReturnStatement (field));
351 mainClass.Members.Add (prop);
355 void CheckCompilerErrors (CompilerResults results)
357 if (results.NativeCompilerReturnValue == 0)
360 StringWriter writer = new StringWriter();
361 provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
362 throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
365 protected string DynamicDir ()
367 return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
370 [MonoTODO ("find out how to extract the warningLevel and compilerOptions in the <system.codedom> case")]
371 public virtual Type GetCompiledType ()
373 Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
378 string lang = parser.Language;
380 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
381 Compiler comp = config.Compilers[lang];
383 string compilerOptions = "";
384 int warningLevel = 0;
387 CompilerInfo info = CodeDomProvider.GetCompilerInfo (lang);
388 if (info != null && info.IsCodeDomProviderTypeValid)
389 provider = info.CreateProvider ();
391 // XXX there's no way to get
392 // warningLevel or compilerOptions out
393 // of the provider.. they're in the
394 // configuration section, though.
397 Type t = Type.GetType (comp.Type, true);
398 provider = Activator.CreateInstance (t) as CodeDomProvider;
400 compilerOptions = comp.CompilerOptions;
401 warningLevel = comp.WarningLevel;
405 CompilationConfiguration config;
407 config = CompilationConfiguration.GetInstance (parser.Context);
408 provider = config.GetProvider (lang);
410 string compilerOptions = config.GetCompilerOptions (lang);
411 int warningLevel = config.GetWarningLevel (lang);
413 if (provider == null)
414 throw new HttpException ("Configuration error. Language not supported: " +
417 compiler = provider.CreateCompiler ();
419 compilerParameters.IncludeDebugInformation = parser.Debug;
420 compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
422 compilerParameters.WarningLevel = warningLevel;
423 bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
425 string tempdir = config.TempDirectory;
426 if (tempdir == null || tempdir == "")
427 tempdir = DynamicDir ();
429 TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
430 compilerParameters.TempFiles = tempcoll;
431 string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
432 compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
434 CompilerResults results = CachingCompiler.Compile (this);
435 CheckCompilerErrors (results);
436 Assembly assembly = results.CompiledAssembly;
437 if (assembly == null) {
438 if (!File.Exists (compilerParameters.OutputAssembly)) {
439 results.TempFiles.Delete ();
440 throw new CompilationException (parser.InputFile, results.Errors,
441 "No assembly returned after compilation!?");
444 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
447 results.TempFiles.Delete ();
448 Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
451 if (parser.IsPartial) {
452 // With the partial classes, we need to make sure we
453 // don't have any methods that should have not been
454 // created (because they are accessible from the base
455 // types). We cannot do this normally because the
456 // codebehind file is actually a partial class and we
457 // have no way of identifying the partial class' base
459 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
461 parser.RootBuilder.ResetState ();
462 return GetCompiledType ();
467 return mainClassType;
471 internal bool IsRebuildingPartial
473 get { return isRebuilding; }
476 internal bool CheckPartialBaseType (Type type)
478 // Get the base type. If we don't have any (bad thing), we
479 // don't need to replace ourselves. Also check for the
480 // core file, since that won't have any either.
481 Type baseType = type.BaseType;
482 if (baseType == null || baseType == typeof(System.Web.UI.Page))
485 bool rebuild = false;
487 if (CheckPartialBaseFields (type, baseType))
490 if (CheckPartialBaseProperties (type, baseType))
496 internal bool CheckPartialBaseFields (Type type, Type baseType)
498 bool rebuild = false;
500 foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
501 if (baseInfo.IsPrivate)
504 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
506 if (typeInfo != null && typeInfo.DeclaringType == type) {
507 partialNameOverride [typeInfo.Name] = true;
515 internal bool CheckPartialBaseProperties (Type type, Type baseType)
517 bool rebuild = false;
519 foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
520 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
522 if (typeInfo != null && typeInfo.DeclaringType == type) {
523 partialNameOverride [typeInfo.Name] = true;
532 internal CompilerParameters CompilerParameters {
533 get { return compilerParameters; }
536 internal CodeCompileUnit Unit {
540 internal virtual ICodeCompiler Compiler {
541 get { return compiler; }
544 internal TemplateParser Parser {
545 get { return parser; }