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. CreateMethods ();
  104. CreateConstructor (null, null);
  105. }
  106. #if NET_2_0
  107. internal CodeDomProvider Provider {
  108. get { return provider; }
  109. }
  110. internal CodeCompileUnit CompileUnit {
  111. get { return unit; }
  112. }
  113. #endif
  114. protected virtual void CreateStaticFields ()
  115. {
  116. CodeMemberField fld = new CodeMemberField (typeof (bool), "__initialized");
  117. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  118. fld.InitExpression = new CodePrimitiveExpression (false);
  119. mainClass.Members.Add (fld);
  120. }
  121. protected virtual void CreateConstructor (CodeStatementCollection localVars,
  122. CodeStatementCollection trueStmt)
  123. {
  124. CodeConstructor ctor = new CodeConstructor ();
  125. ctor.Attributes = MemberAttributes.Public;
  126. mainClass.Members.Add (ctor);
  127. if (localVars != null)
  128. ctor.Statements.AddRange (localVars);
  129. CodeTypeReferenceExpression r;
  130. #if NET_2_0
  131. if (parser.IsPartial)
  132. r = new CodeTypeReferenceExpression (mainClass.Name);
  133. else
  134. #endif
  135. r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
  136. CodeFieldReferenceExpression initialized;
  137. initialized = new CodeFieldReferenceExpression (r, "__initialized");
  138. CodeBinaryOperatorExpression bin;
  139. bin = new CodeBinaryOperatorExpression (initialized,
  140. CodeBinaryOperatorType.ValueEquality,
  141. new CodePrimitiveExpression (false));
  142. CodeAssignStatement assign = new CodeAssignStatement (initialized,
  143. new CodePrimitiveExpression (true));
  144. CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
  145. if (trueStmt != null)
  146. cond.TrueStatements.AddRange (trueStmt);
  147. ctor.Statements.Add (cond);
  148. }
  149. void AddScripts ()
  150. {
  151. if (parser.Scripts == null || parser.Scripts.Count == 0)
  152. return;
  153. foreach (object o in parser.Scripts) {
  154. if (o is string)
  155. mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
  156. }
  157. }
  158. protected internal virtual void CreateMethods ()
  159. {
  160. }
  161. protected virtual void AddInterfaces ()
  162. {
  163. if (parser.Interfaces == null)
  164. return;
  165. foreach (object o in parser.Interfaces) {
  166. if (o is string)
  167. mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
  168. }
  169. }
  170. protected virtual void AddClassAttributes ()
  171. {
  172. }
  173. protected virtual void AddApplicationAndSessionObjects ()
  174. {
  175. }
  176. /* Utility methods for <object> stuff */
  177. protected void CreateApplicationOrSessionPropertyForObject (Type type,
  178. string propName,
  179. bool isApplication,
  180. bool isPublic)
  181. {
  182. /* if isApplication this generates (the 'cachedapp' field is created earlier):
  183. private MyNS.MyClass app {
  184. get {
  185. if ((this.cachedapp == null)) {
  186. this.cachedapp = ((MyNS.MyClass)
  187. (this.Application.StaticObjects.GetObject("app")));
  188. }
  189. return this.cachedapp;
  190. }
  191. }
  192. else, this is for Session:
  193. private MyNS.MyClass ses {
  194. get {
  195. return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
  196. }
  197. }
  198. */
  199. CodeExpression result = null;
  200. CodeMemberProperty prop = new CodeMemberProperty ();
  201. prop.Type = new CodeTypeReference (type);
  202. prop.Name = propName;
  203. if (isPublic)
  204. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  205. else
  206. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  207. CodePropertyReferenceExpression p1;
  208. if (isApplication)
  209. p1 = new CodePropertyReferenceExpression (thisRef, "Application");
  210. else
  211. p1 = new CodePropertyReferenceExpression (thisRef, "Session");
  212. CodePropertyReferenceExpression p2;
  213. p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
  214. CodeMethodReferenceExpression getobject;
  215. getobject = new CodeMethodReferenceExpression (p2, "GetObject");
  216. CodeMethodInvokeExpression invoker;
  217. invoker = new CodeMethodInvokeExpression (getobject,
  218. new CodePrimitiveExpression (propName));
  219. CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
  220. if (isApplication) {
  221. CodeFieldReferenceExpression field;
  222. field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
  223. CodeConditionStatement stmt = new CodeConditionStatement();
  224. stmt.Condition = new CodeBinaryOperatorExpression (field,
  225. CodeBinaryOperatorType.IdentityEquality,
  226. new CodePrimitiveExpression (null));
  227. CodeAssignStatement assign = new CodeAssignStatement ();
  228. assign.Left = field;
  229. assign.Right = cast;
  230. stmt.TrueStatements.Add (assign);
  231. prop.GetStatements.Add (stmt);
  232. result = field;
  233. } else {
  234. result = cast;
  235. }
  236. prop.GetStatements.Add (new CodeMethodReturnStatement (result));
  237. mainClass.Members.Add (prop);
  238. }
  239. protected string CreateFieldForObject (Type type, string name)
  240. {
  241. string fieldName = "cached" + name;
  242. CodeMemberField f = new CodeMemberField (type, fieldName);
  243. f.Attributes = MemberAttributes.Private;
  244. mainClass.Members.Add (f);
  245. return fieldName;
  246. }
  247. protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
  248. {
  249. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
  250. CodeMemberProperty prop = new CodeMemberProperty ();
  251. prop.Type = new CodeTypeReference (type);
  252. prop.Name = propName;
  253. if (isPublic)
  254. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  255. else
  256. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  257. CodeConditionStatement stmt = new CodeConditionStatement();
  258. stmt.Condition = new CodeBinaryOperatorExpression (field,
  259. CodeBinaryOperatorType.IdentityEquality,
  260. new CodePrimitiveExpression (null));
  261. CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
  262. stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
  263. prop.GetStatements.Add (stmt);
  264. prop.GetStatements.Add (new CodeMethodReturnStatement (field));
  265. mainClass.Members.Add (prop);
  266. }
  267. /******/
  268. void CheckCompilerErrors (CompilerResults results)
  269. {
  270. if (results.NativeCompilerReturnValue == 0)
  271. return;
  272. StringWriter writer = new StringWriter();
  273. provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
  274. throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
  275. }
  276. protected string DynamicDir ()
  277. {
  278. return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  279. }
  280. public virtual Type GetCompiledType ()
  281. {
  282. Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
  283. if (type != null)
  284. return type;
  285. Init ();
  286. string lang = parser.Language;
  287. #if NET_2_0
  288. CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  289. Compiler comp = config.Compilers[lang];
  290. Type t = Type.GetType (comp.Type, true);
  291. provider = Activator.CreateInstance (t) as CodeDomProvider;
  292. string compilerOptions = comp.CompilerOptions;
  293. int warningLevel = comp.WarningLevel;
  294. #else
  295. CompilationConfiguration config;
  296. config = CompilationConfiguration.GetInstance (parser.Context);
  297. provider = config.GetProvider (lang);
  298. string compilerOptions = config.GetCompilerOptions (lang);
  299. int warningLevel = config.GetWarningLevel (lang);
  300. #endif
  301. if (provider == null)
  302. throw new HttpException ("Configuration error. Language not supported: " +
  303. lang, 500);
  304. compiler = provider.CreateCompiler ();
  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. }