BaseCompiler.cs 16 KB

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