2
0

BaseCompiler.cs 15 KB

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