BaseCompiler.cs 15 KB

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