BaseCompiler.cs 16 KB

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