BaseCompiler.cs 16 KB

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