BaseCompiler.cs 18 KB

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