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);
123 // Late-bound generators specifics (as for MonoBASIC/VB.NET)
124 unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
125 unit.UserData["AllowLateBound"] = !parser.StrictOn;
128 AddClassAttributes ();
129 CreateStaticFields ();
130 AddApplicationAndSessionObjects ();
133 CreateConstructor (null, null);
137 internal CodeDomProvider Provider {
138 get { return provider; }
141 internal CodeCompileUnit CompileUnit {
145 protected virtual void CreateStaticFields ()
147 CodeMemberField fld = new CodeMemberField (typeof (bool), "__initialized");
148 fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
149 fld.InitExpression = new CodePrimitiveExpression (false);
150 mainClass.Members.Add (fld);
153 protected virtual void CreateConstructor (CodeStatementCollection localVars,
154 CodeStatementCollection trueStmt)
156 CodeConstructor ctor = new CodeConstructor ();
157 ctor.Attributes = MemberAttributes.Public;
158 mainClass.Members.Add (ctor);
160 if (localVars != null)
161 ctor.Statements.AddRange (localVars);
163 CodeTypeReferenceExpression r;
165 if (parser.IsPartial)
166 r = new CodeTypeReferenceExpression (mainClass.Name);
169 r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
170 CodeFieldReferenceExpression initialized;
171 initialized = new CodeFieldReferenceExpression (r, "__initialized");
173 CodeBinaryOperatorExpression bin;
174 bin = new CodeBinaryOperatorExpression (initialized,
175 CodeBinaryOperatorType.ValueEquality,
176 new CodePrimitiveExpression (false));
178 CodeAssignStatement assign = new CodeAssignStatement (initialized,
179 new CodePrimitiveExpression (true));
181 CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
182 if (trueStmt != null)
183 cond.TrueStatements.AddRange (trueStmt);
185 ctor.Statements.Add (cond);
190 if (parser.Scripts == null || parser.Scripts.Count == 0)
193 foreach (object o in parser.Scripts) {
195 mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
199 protected internal virtual void CreateMethods ()
203 protected virtual void AddInterfaces ()
205 if (parser.Interfaces == null)
208 foreach (object o in parser.Interfaces) {
210 mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
214 protected virtual void AddClassAttributes ()
218 protected virtual void AddApplicationAndSessionObjects ()
222 /* Utility methods for <object> stuff */
223 protected void CreateApplicationOrSessionPropertyForObject (Type type,
228 /* if isApplication this generates (the 'cachedapp' field is created earlier):
229 private MyNS.MyClass app {
231 if ((this.cachedapp == null)) {
232 this.cachedapp = ((MyNS.MyClass)
233 (this.Application.StaticObjects.GetObject("app")));
235 return this.cachedapp;
239 else, this is for Session:
240 private MyNS.MyClass ses {
242 return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
248 CodeExpression result = null;
250 CodeMemberProperty prop = new CodeMemberProperty ();
251 prop.Type = new CodeTypeReference (type);
252 prop.Name = propName;
254 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
256 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
258 CodePropertyReferenceExpression p1;
260 p1 = new CodePropertyReferenceExpression (thisRef, "Application");
262 p1 = new CodePropertyReferenceExpression (thisRef, "Session");
264 CodePropertyReferenceExpression p2;
265 p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
267 CodeMethodReferenceExpression getobject;
268 getobject = new CodeMethodReferenceExpression (p2, "GetObject");
270 CodeMethodInvokeExpression invoker;
271 invoker = new CodeMethodInvokeExpression (getobject,
272 new CodePrimitiveExpression (propName));
274 CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
277 CodeFieldReferenceExpression field;
278 field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
280 CodeConditionStatement stmt = new CodeConditionStatement();
281 stmt.Condition = new CodeBinaryOperatorExpression (field,
282 CodeBinaryOperatorType.IdentityEquality,
283 new CodePrimitiveExpression (null));
285 CodeAssignStatement assign = new CodeAssignStatement ();
288 stmt.TrueStatements.Add (assign);
289 prop.GetStatements.Add (stmt);
295 prop.GetStatements.Add (new CodeMethodReturnStatement (result));
296 mainClass.Members.Add (prop);
299 protected string CreateFieldForObject (Type type, string name)
301 string fieldName = "cached" + name;
302 CodeMemberField f = new CodeMemberField (type, fieldName);
303 f.Attributes = MemberAttributes.Private;
304 mainClass.Members.Add (f);
308 protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
310 CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
311 CodeMemberProperty prop = new CodeMemberProperty ();
312 prop.Type = new CodeTypeReference (type);
313 prop.Name = propName;
315 prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
317 prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
319 CodeConditionStatement stmt = new CodeConditionStatement();
320 stmt.Condition = new CodeBinaryOperatorExpression (field,
321 CodeBinaryOperatorType.IdentityEquality,
322 new CodePrimitiveExpression (null));
324 CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
325 stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
326 prop.GetStatements.Add (stmt);
327 prop.GetStatements.Add (new CodeMethodReturnStatement (field));
329 mainClass.Members.Add (prop);
333 void CheckCompilerErrors (CompilerResults results)
335 if (results.NativeCompilerReturnValue == 0)
338 StringWriter writer = new StringWriter();
339 provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
340 throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
343 protected string DynamicDir ()
345 return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
348 [MonoTODO ("find out how to extract the warningLevel and compilerOptions in the <system.codedom> case")]
349 public virtual Type GetCompiledType ()
351 Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
356 string lang = parser.Language;
358 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
359 Compiler comp = config.Compilers[lang];
361 string compilerOptions = "";
362 int warningLevel = 0;
365 CompilerInfo info = CodeDomProvider.GetCompilerInfo (lang);
366 if (info != null && info.IsCodeDomProviderTypeValid)
367 provider = info.CreateProvider ();
369 // XXX there's no way to get
370 // warningLevel or compilerOptions out
371 // of the provider.. they're in the
372 // configuration section, though.
375 Type t = Type.GetType (comp.Type, true);
376 provider = Activator.CreateInstance (t) as CodeDomProvider;
378 compilerOptions = comp.CompilerOptions;
379 warningLevel = comp.WarningLevel;
383 CompilationConfiguration config;
385 config = CompilationConfiguration.GetInstance (parser.Context);
386 provider = config.GetProvider (lang);
388 string compilerOptions = config.GetCompilerOptions (lang);
389 int warningLevel = config.GetWarningLevel (lang);
391 if (provider == null)
392 throw new HttpException ("Configuration error. Language not supported: " +
395 compiler = provider.CreateCompiler ();
397 compilerParameters.IncludeDebugInformation = parser.Debug;
398 compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
400 compilerParameters.WarningLevel = warningLevel;
401 bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
403 string tempdir = config.TempDirectory;
404 if (tempdir == null || tempdir == "")
405 tempdir = DynamicDir ();
407 TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
408 compilerParameters.TempFiles = tempcoll;
409 string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
410 compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
412 CompilerResults results = CachingCompiler.Compile (this);
413 CheckCompilerErrors (results);
414 Assembly assembly = results.CompiledAssembly;
415 if (assembly == null) {
416 if (!File.Exists (compilerParameters.OutputAssembly)) {
417 results.TempFiles.Delete ();
418 throw new CompilationException (parser.InputFile, results.Errors,
419 "No assembly returned after compilation!?");
422 assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
425 results.TempFiles.Delete ();
426 Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
429 if (parser.IsPartial) {
430 // With the partial classes, we need to make sure we
431 // don't have any methods that should have not been
432 // created (because they are accessible from the base
433 // types). We cannot do this normally because the
434 // codebehind file is actually a partial class and we
435 // have no way of identifying the partial class' base
437 if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
439 parser.RootBuilder.ResetState ();
440 return GetCompiledType ();
445 return mainClassType;
449 internal bool IsRebuildingPartial
451 get { return isRebuilding; }
454 internal bool CheckPartialBaseType (Type type)
456 // Get the base type. If we don't have any (bad thing), we
457 // don't need to replace ourselves. Also check for the
458 // core file, since that won't have any either.
459 Type baseType = type.BaseType;
460 if (baseType == null || baseType == typeof(System.Web.UI.Page))
463 bool rebuild = false;
465 if (CheckPartialBaseFields (type, baseType))
468 if (CheckPartialBaseProperties (type, baseType))
474 internal bool CheckPartialBaseFields (Type type, Type baseType)
476 bool rebuild = false;
478 foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
479 if (baseInfo.IsPrivate)
482 FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
484 if (typeInfo != null && typeInfo.DeclaringType == type) {
485 partialNameOverride [typeInfo.Name] = true;
493 internal bool CheckPartialBaseProperties (Type type, Type baseType)
495 bool rebuild = false;
497 foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
498 PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
500 if (typeInfo != null && typeInfo.DeclaringType == type) {
501 partialNameOverride [typeInfo.Name] = true;
510 internal CompilerParameters CompilerParameters {
511 get { return compilerParameters; }
514 internal CodeCompileUnit Unit {
518 internal virtual ICodeCompiler Compiler {
519 get { return compiler; }
522 internal TemplateParser Parser {
523 get { return parser; }