BaseCompiler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. //
  2. // System.Web.Compilation.BaseCompiler
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (c) Copyright 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.CodeDom;
  31. using System.CodeDom.Compiler;
  32. using System.Collections;
  33. using System.Reflection;
  34. using System.Text;
  35. using System.Web.UI;
  36. using System.Web.Configuration;
  37. using System.IO;
  38. namespace System.Web.Compilation
  39. {
  40. abstract class BaseCompiler
  41. {
  42. #if NET_2_0
  43. static BindingFlags replaceableFlags = BindingFlags.Public | BindingFlags.NonPublic |
  44. BindingFlags.Instance;
  45. #endif
  46. TemplateParser parser;
  47. CodeDomProvider provider;
  48. ICodeCompiler compiler;
  49. CodeCompileUnit unit;
  50. CodeNamespace mainNS;
  51. CompilerParameters compilerParameters;
  52. #if NET_2_0
  53. bool isRebuilding = false;
  54. protected Hashtable partialNameOverride = new Hashtable();
  55. #endif
  56. protected CodeTypeDeclaration mainClass;
  57. protected CodeTypeReferenceExpression mainClassExpr;
  58. protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
  59. protected BaseCompiler (TemplateParser parser)
  60. {
  61. compilerParameters = new CompilerParameters ();
  62. this.parser = parser;
  63. }
  64. void Init ()
  65. {
  66. unit = new CodeCompileUnit ();
  67. #if NET_2_0
  68. if (parser.IsPartial) {
  69. mainNS = new CodeNamespace ();
  70. mainClass = new CodeTypeDeclaration (parser.PartialClassName);
  71. mainClass.IsPartial = true;
  72. mainClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
  73. } else {
  74. #endif
  75. mainNS = new CodeNamespace ("ASP");
  76. mainClass = new CodeTypeDeclaration (parser.ClassName);
  77. mainClass.BaseTypes.Add (new CodeTypeReference (parser.BaseType.FullName));
  78. mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName);
  79. #if NET_2_0
  80. }
  81. #endif
  82. unit.Namespaces.Add (mainNS);
  83. mainClass.TypeAttributes = TypeAttributes.Public;
  84. mainNS.Types.Add (mainClass);
  85. foreach (object o in parser.Imports) {
  86. if (o is string)
  87. mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
  88. }
  89. if (parser.Assemblies != null) {
  90. foreach (object o in parser.Assemblies) {
  91. if (o is string)
  92. unit.ReferencedAssemblies.Add ((string) o);
  93. }
  94. }
  95. // Late-bound generators specifics (as for MonoBASIC/VB.NET)
  96. unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
  97. unit.UserData["AllowLateBound"] = !parser.StrictOn;
  98. AddInterfaces ();
  99. AddClassAttributes ();
  100. CreateStaticFields ();
  101. AddApplicationAndSessionObjects ();
  102. AddScripts ();
  103. CreateConstructor (null, null);
  104. }
  105. protected virtual void CreateStaticFields ()
  106. {
  107. CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
  108. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  109. fld.InitExpression = new CodePrimitiveExpression (false);
  110. mainClass.Members.Add (fld);
  111. }
  112. protected virtual void CreateConstructor (CodeStatementCollection localVars,
  113. CodeStatementCollection trueStmt)
  114. {
  115. CodeConstructor ctor = new CodeConstructor ();
  116. ctor.Attributes = MemberAttributes.Public;
  117. mainClass.Members.Add (ctor);
  118. if (localVars != null)
  119. ctor.Statements.AddRange (localVars);
  120. CodeTypeReferenceExpression r;
  121. #if NET_2_0
  122. if (parser.IsPartial)
  123. r = new CodeTypeReferenceExpression (mainClass.Name);
  124. else
  125. #endif
  126. r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
  127. CodeFieldReferenceExpression intialized;
  128. intialized = new CodeFieldReferenceExpression (r, "__intialized");
  129. CodeBinaryOperatorExpression bin;
  130. bin = new CodeBinaryOperatorExpression (intialized,
  131. CodeBinaryOperatorType.ValueEquality,
  132. new CodePrimitiveExpression (false));
  133. CodeAssignStatement assign = new CodeAssignStatement (intialized,
  134. new CodePrimitiveExpression (true));
  135. CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
  136. if (trueStmt != null)
  137. cond.TrueStatements.AddRange (trueStmt);
  138. ctor.Statements.Add (cond);
  139. }
  140. void AddScripts ()
  141. {
  142. if (parser.Scripts == null || parser.Scripts.Count == 0)
  143. return;
  144. foreach (object o in parser.Scripts) {
  145. if (o is string)
  146. mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
  147. }
  148. }
  149. protected virtual void CreateMethods ()
  150. {
  151. }
  152. protected virtual void AddInterfaces ()
  153. {
  154. if (parser.Interfaces == null)
  155. return;
  156. foreach (object o in parser.Interfaces) {
  157. if (o is string)
  158. mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
  159. }
  160. }
  161. protected virtual void AddClassAttributes ()
  162. {
  163. }
  164. protected virtual void AddApplicationAndSessionObjects ()
  165. {
  166. }
  167. /* Utility methods for <object> stuff */
  168. protected void CreateApplicationOrSessionPropertyForObject (Type type,
  169. string propName,
  170. bool isApplication,
  171. bool isPublic)
  172. {
  173. /* if isApplication this generates (the 'cachedapp' field is created earlier):
  174. private MyNS.MyClass app {
  175. get {
  176. if ((this.cachedapp == null)) {
  177. this.cachedapp = ((MyNS.MyClass)
  178. (this.Application.StaticObjects.GetObject("app")));
  179. }
  180. return this.cachedapp;
  181. }
  182. }
  183. else, this is for Session:
  184. private MyNS.MyClass ses {
  185. get {
  186. return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
  187. }
  188. }
  189. */
  190. CodeExpression result = null;
  191. CodeMemberProperty prop = new CodeMemberProperty ();
  192. prop.Type = new CodeTypeReference (type);
  193. prop.Name = propName;
  194. if (isPublic)
  195. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  196. else
  197. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  198. CodePropertyReferenceExpression p1;
  199. if (isApplication)
  200. p1 = new CodePropertyReferenceExpression (thisRef, "Application");
  201. else
  202. p1 = new CodePropertyReferenceExpression (thisRef, "Session");
  203. CodePropertyReferenceExpression p2;
  204. p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
  205. CodeMethodReferenceExpression getobject;
  206. getobject = new CodeMethodReferenceExpression (p2, "GetObject");
  207. CodeMethodInvokeExpression invoker;
  208. invoker = new CodeMethodInvokeExpression (getobject,
  209. new CodePrimitiveExpression (propName));
  210. CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
  211. if (isApplication) {
  212. CodeFieldReferenceExpression field;
  213. field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
  214. CodeConditionStatement stmt = new CodeConditionStatement();
  215. stmt.Condition = new CodeBinaryOperatorExpression (field,
  216. CodeBinaryOperatorType.IdentityEquality,
  217. new CodePrimitiveExpression (null));
  218. CodeAssignStatement assign = new CodeAssignStatement ();
  219. assign.Left = field;
  220. assign.Right = cast;
  221. stmt.TrueStatements.Add (assign);
  222. prop.GetStatements.Add (stmt);
  223. result = field;
  224. } else {
  225. result = cast;
  226. }
  227. prop.GetStatements.Add (new CodeMethodReturnStatement (result));
  228. mainClass.Members.Add (prop);
  229. }
  230. protected string CreateFieldForObject (Type type, string name)
  231. {
  232. string fieldName = "cached" + name;
  233. CodeMemberField f = new CodeMemberField (type, fieldName);
  234. f.Attributes = MemberAttributes.Private;
  235. mainClass.Members.Add (f);
  236. return fieldName;
  237. }
  238. protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
  239. {
  240. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
  241. CodeMemberProperty prop = new CodeMemberProperty ();
  242. prop.Type = new CodeTypeReference (type);
  243. prop.Name = propName;
  244. if (isPublic)
  245. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  246. else
  247. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  248. CodeConditionStatement stmt = new CodeConditionStatement();
  249. stmt.Condition = new CodeBinaryOperatorExpression (field,
  250. CodeBinaryOperatorType.IdentityEquality,
  251. new CodePrimitiveExpression (null));
  252. CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
  253. stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
  254. prop.GetStatements.Add (stmt);
  255. prop.GetStatements.Add (new CodeMethodReturnStatement (field));
  256. mainClass.Members.Add (prop);
  257. }
  258. /******/
  259. void CheckCompilerErrors (CompilerResults results)
  260. {
  261. if (results.NativeCompilerReturnValue == 0)
  262. return;
  263. StringWriter writer = new StringWriter();
  264. provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
  265. throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
  266. }
  267. protected string DynamicDir ()
  268. {
  269. return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  270. }
  271. public virtual Type GetCompiledType ()
  272. {
  273. Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
  274. if (type != null)
  275. return type;
  276. Init ();
  277. string lang = parser.Language;
  278. #if CONFIGURATION_2_0
  279. CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  280. Compiler comp = config.Compilers[lang];
  281. provider = comp.Provider;
  282. string compilerOptions = comp.CompilerOptions;
  283. int warningLevel = comp.WarningLevel;
  284. #else
  285. CompilationConfiguration config;
  286. config = CompilationConfiguration.GetInstance (parser.Context);
  287. provider = config.GetProvider (lang);
  288. string compilerOptions = config.GetCompilerOptions (lang);
  289. int warningLevel = config.GetWarningLevel (lang);
  290. #endif
  291. if (provider == null)
  292. throw new HttpException ("Configuration error. Language not supported: " +
  293. lang, 500);
  294. compiler = provider.CreateCompiler ();
  295. CreateMethods ();
  296. compilerParameters.IncludeDebugInformation = parser.Debug;
  297. compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
  298. compilerParameters.WarningLevel = warningLevel;
  299. bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
  300. string tempdir = config.TempDirectory;
  301. if (tempdir == null || tempdir == "")
  302. tempdir = DynamicDir ();
  303. TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
  304. compilerParameters.TempFiles = tempcoll;
  305. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  306. compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
  307. CompilerResults results = CachingCompiler.Compile (this);
  308. CheckCompilerErrors (results);
  309. Assembly assembly = results.CompiledAssembly;
  310. if (assembly == null) {
  311. if (!File.Exists (compilerParameters.OutputAssembly))
  312. throw new CompilationException (parser.InputFile, results.Errors,
  313. "No assembly returned after compilation!?");
  314. assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
  315. }
  316. results.TempFiles.Delete ();
  317. Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
  318. #if NET_2_0
  319. if (parser.IsPartial) {
  320. // With the partial classes, we need to make sure we
  321. // don't have any methods that should have not been
  322. // created (because they are accessible from the base
  323. // types). We cannot do this normally because the
  324. // codebehind file is actually a partial class and we
  325. // have no way of identifying the partial class' base
  326. // type until now.
  327. if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
  328. isRebuilding = true;
  329. parser.RootBuilder.ResetState ();
  330. return GetCompiledType ();
  331. }
  332. }
  333. #endif
  334. return mainClassType;
  335. }
  336. #if NET_2_0
  337. internal bool IsRebuildingPartial
  338. {
  339. get { return isRebuilding; }
  340. }
  341. internal bool CheckPartialBaseType (Type type)
  342. {
  343. // Get the base type. If we don't have any (bad thing), we
  344. // don't need to replace ourselves. Also check for the
  345. // core file, since that won't have any either.
  346. Type baseType = type.BaseType;
  347. if (baseType == null || baseType == typeof(System.Web.UI.Page))
  348. return false;
  349. bool rebuild = false;
  350. if (CheckPartialBaseFields (type, baseType))
  351. rebuild = true;
  352. if (CheckPartialBaseProperties (type, baseType))
  353. rebuild = true;
  354. return rebuild;
  355. }
  356. internal bool CheckPartialBaseFields (Type type, Type baseType)
  357. {
  358. bool rebuild = false;
  359. foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
  360. if (baseInfo.IsPrivate)
  361. continue;
  362. FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
  363. if (typeInfo != null && typeInfo.DeclaringType == type) {
  364. partialNameOverride [typeInfo.Name] = true;
  365. rebuild = true;
  366. }
  367. }
  368. return rebuild;
  369. }
  370. internal bool CheckPartialBaseProperties (Type type, Type baseType)
  371. {
  372. bool rebuild = false;
  373. foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
  374. PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
  375. if (typeInfo != null && typeInfo.DeclaringType == type) {
  376. partialNameOverride [typeInfo.Name] = true;
  377. rebuild = true;
  378. }
  379. }
  380. return rebuild;
  381. }
  382. #endif
  383. internal CompilerParameters CompilerParameters {
  384. get { return compilerParameters; }
  385. }
  386. internal CodeCompileUnit Unit {
  387. get { return unit; }
  388. }
  389. internal virtual ICodeCompiler Compiler {
  390. get { return compiler; }
  391. }
  392. internal TemplateParser Parser {
  393. get { return parser; }
  394. }
  395. }
  396. }