BaseCompiler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. #if NET_2_0
  106. internal CodeDomProvider Provider {
  107. get { return provider; }
  108. }
  109. internal CodeCompileUnit CompileUnit {
  110. get { return unit; }
  111. }
  112. #endif
  113. protected virtual void CreateStaticFields ()
  114. {
  115. CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
  116. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  117. fld.InitExpression = new CodePrimitiveExpression (false);
  118. mainClass.Members.Add (fld);
  119. }
  120. protected virtual void CreateConstructor (CodeStatementCollection localVars,
  121. CodeStatementCollection trueStmt)
  122. {
  123. CodeConstructor ctor = new CodeConstructor ();
  124. ctor.Attributes = MemberAttributes.Public;
  125. mainClass.Members.Add (ctor);
  126. if (localVars != null)
  127. ctor.Statements.AddRange (localVars);
  128. CodeTypeReferenceExpression r;
  129. #if NET_2_0
  130. if (parser.IsPartial)
  131. r = new CodeTypeReferenceExpression (mainClass.Name);
  132. else
  133. #endif
  134. r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
  135. CodeFieldReferenceExpression intialized;
  136. intialized = new CodeFieldReferenceExpression (r, "__intialized");
  137. CodeBinaryOperatorExpression bin;
  138. bin = new CodeBinaryOperatorExpression (intialized,
  139. CodeBinaryOperatorType.ValueEquality,
  140. new CodePrimitiveExpression (false));
  141. CodeAssignStatement assign = new CodeAssignStatement (intialized,
  142. new CodePrimitiveExpression (true));
  143. CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
  144. if (trueStmt != null)
  145. cond.TrueStatements.AddRange (trueStmt);
  146. ctor.Statements.Add (cond);
  147. }
  148. void AddScripts ()
  149. {
  150. if (parser.Scripts == null || parser.Scripts.Count == 0)
  151. return;
  152. foreach (object o in parser.Scripts) {
  153. if (o is string)
  154. mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
  155. }
  156. }
  157. protected internal virtual void CreateMethods ()
  158. {
  159. }
  160. protected virtual void AddInterfaces ()
  161. {
  162. if (parser.Interfaces == null)
  163. return;
  164. foreach (object o in parser.Interfaces) {
  165. if (o is string)
  166. mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
  167. }
  168. }
  169. protected virtual void AddClassAttributes ()
  170. {
  171. }
  172. protected virtual void AddApplicationAndSessionObjects ()
  173. {
  174. }
  175. /* Utility methods for <object> stuff */
  176. protected void CreateApplicationOrSessionPropertyForObject (Type type,
  177. string propName,
  178. bool isApplication,
  179. bool isPublic)
  180. {
  181. /* if isApplication this generates (the 'cachedapp' field is created earlier):
  182. private MyNS.MyClass app {
  183. get {
  184. if ((this.cachedapp == null)) {
  185. this.cachedapp = ((MyNS.MyClass)
  186. (this.Application.StaticObjects.GetObject("app")));
  187. }
  188. return this.cachedapp;
  189. }
  190. }
  191. else, this is for Session:
  192. private MyNS.MyClass ses {
  193. get {
  194. return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
  195. }
  196. }
  197. */
  198. CodeExpression result = null;
  199. CodeMemberProperty prop = new CodeMemberProperty ();
  200. prop.Type = new CodeTypeReference (type);
  201. prop.Name = propName;
  202. if (isPublic)
  203. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  204. else
  205. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  206. CodePropertyReferenceExpression p1;
  207. if (isApplication)
  208. p1 = new CodePropertyReferenceExpression (thisRef, "Application");
  209. else
  210. p1 = new CodePropertyReferenceExpression (thisRef, "Session");
  211. CodePropertyReferenceExpression p2;
  212. p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
  213. CodeMethodReferenceExpression getobject;
  214. getobject = new CodeMethodReferenceExpression (p2, "GetObject");
  215. CodeMethodInvokeExpression invoker;
  216. invoker = new CodeMethodInvokeExpression (getobject,
  217. new CodePrimitiveExpression (propName));
  218. CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
  219. if (isApplication) {
  220. CodeFieldReferenceExpression field;
  221. field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
  222. CodeConditionStatement stmt = new CodeConditionStatement();
  223. stmt.Condition = new CodeBinaryOperatorExpression (field,
  224. CodeBinaryOperatorType.IdentityEquality,
  225. new CodePrimitiveExpression (null));
  226. CodeAssignStatement assign = new CodeAssignStatement ();
  227. assign.Left = field;
  228. assign.Right = cast;
  229. stmt.TrueStatements.Add (assign);
  230. prop.GetStatements.Add (stmt);
  231. result = field;
  232. } else {
  233. result = cast;
  234. }
  235. prop.GetStatements.Add (new CodeMethodReturnStatement (result));
  236. mainClass.Members.Add (prop);
  237. }
  238. protected string CreateFieldForObject (Type type, string name)
  239. {
  240. string fieldName = "cached" + name;
  241. CodeMemberField f = new CodeMemberField (type, fieldName);
  242. f.Attributes = MemberAttributes.Private;
  243. mainClass.Members.Add (f);
  244. return fieldName;
  245. }
  246. protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
  247. {
  248. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
  249. CodeMemberProperty prop = new CodeMemberProperty ();
  250. prop.Type = new CodeTypeReference (type);
  251. prop.Name = propName;
  252. if (isPublic)
  253. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  254. else
  255. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  256. CodeConditionStatement stmt = new CodeConditionStatement();
  257. stmt.Condition = new CodeBinaryOperatorExpression (field,
  258. CodeBinaryOperatorType.IdentityEquality,
  259. new CodePrimitiveExpression (null));
  260. CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
  261. stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
  262. prop.GetStatements.Add (stmt);
  263. prop.GetStatements.Add (new CodeMethodReturnStatement (field));
  264. mainClass.Members.Add (prop);
  265. }
  266. /******/
  267. void CheckCompilerErrors (CompilerResults results)
  268. {
  269. if (results.NativeCompilerReturnValue == 0)
  270. return;
  271. StringWriter writer = new StringWriter();
  272. provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
  273. throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
  274. }
  275. protected string DynamicDir ()
  276. {
  277. return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  278. }
  279. public virtual Type GetCompiledType ()
  280. {
  281. Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
  282. if (type != null)
  283. return type;
  284. Init ();
  285. string lang = parser.Language;
  286. #if NET_2_0
  287. CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  288. Compiler comp = config.Compilers[lang];
  289. Type t = Type.GetType (comp.Type, true);
  290. provider = Activator.CreateInstance (t) as CodeDomProvider;
  291. string compilerOptions = comp.CompilerOptions;
  292. int warningLevel = comp.WarningLevel;
  293. #else
  294. CompilationConfiguration config;
  295. config = CompilationConfiguration.GetInstance (parser.Context);
  296. provider = config.GetProvider (lang);
  297. string compilerOptions = config.GetCompilerOptions (lang);
  298. int warningLevel = config.GetWarningLevel (lang);
  299. #endif
  300. if (provider == null)
  301. throw new HttpException ("Configuration error. Language not supported: " +
  302. lang, 500);
  303. compiler = provider.CreateCompiler ();
  304. CreateMethods ();
  305. compilerParameters.IncludeDebugInformation = parser.Debug;
  306. compilerParameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
  307. compilerParameters.WarningLevel = warningLevel;
  308. bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
  309. string tempdir = config.TempDirectory;
  310. if (tempdir == null || tempdir == "")
  311. tempdir = DynamicDir ();
  312. TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
  313. compilerParameters.TempFiles = tempcoll;
  314. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  315. compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
  316. CompilerResults results = CachingCompiler.Compile (this);
  317. CheckCompilerErrors (results);
  318. Assembly assembly = results.CompiledAssembly;
  319. if (assembly == null) {
  320. if (!File.Exists (compilerParameters.OutputAssembly)) {
  321. results.TempFiles.Delete ();
  322. throw new CompilationException (parser.InputFile, results.Errors,
  323. "No assembly returned after compilation!?");
  324. }
  325. assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly);
  326. }
  327. results.TempFiles.Delete ();
  328. Type mainClassType = assembly.GetType (mainClassExpr.Type.BaseType, true);
  329. #if NET_2_0
  330. if (parser.IsPartial) {
  331. // With the partial classes, we need to make sure we
  332. // don't have any methods that should have not been
  333. // created (because they are accessible from the base
  334. // types). We cannot do this normally because the
  335. // codebehind file is actually a partial class and we
  336. // have no way of identifying the partial class' base
  337. // type until now.
  338. if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
  339. isRebuilding = true;
  340. parser.RootBuilder.ResetState ();
  341. return GetCompiledType ();
  342. }
  343. }
  344. #endif
  345. return mainClassType;
  346. }
  347. #if NET_2_0
  348. internal bool IsRebuildingPartial
  349. {
  350. get { return isRebuilding; }
  351. }
  352. internal bool CheckPartialBaseType (Type type)
  353. {
  354. // Get the base type. If we don't have any (bad thing), we
  355. // don't need to replace ourselves. Also check for the
  356. // core file, since that won't have any either.
  357. Type baseType = type.BaseType;
  358. if (baseType == null || baseType == typeof(System.Web.UI.Page))
  359. return false;
  360. bool rebuild = false;
  361. if (CheckPartialBaseFields (type, baseType))
  362. rebuild = true;
  363. if (CheckPartialBaseProperties (type, baseType))
  364. rebuild = true;
  365. return rebuild;
  366. }
  367. internal bool CheckPartialBaseFields (Type type, Type baseType)
  368. {
  369. bool rebuild = false;
  370. foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
  371. if (baseInfo.IsPrivate)
  372. continue;
  373. FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
  374. if (typeInfo != null && typeInfo.DeclaringType == type) {
  375. partialNameOverride [typeInfo.Name] = true;
  376. rebuild = true;
  377. }
  378. }
  379. return rebuild;
  380. }
  381. internal bool CheckPartialBaseProperties (Type type, Type baseType)
  382. {
  383. bool rebuild = false;
  384. foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
  385. PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
  386. if (typeInfo != null && typeInfo.DeclaringType == type) {
  387. partialNameOverride [typeInfo.Name] = true;
  388. rebuild = true;
  389. }
  390. }
  391. return rebuild;
  392. }
  393. #endif
  394. internal CompilerParameters CompilerParameters {
  395. get { return compilerParameters; }
  396. }
  397. internal CodeCompileUnit Unit {
  398. get { return unit; }
  399. }
  400. internal virtual ICodeCompiler Compiler {
  401. get { return compiler; }
  402. }
  403. internal TemplateParser Parser {
  404. get { return parser; }
  405. }
  406. }
  407. }