BaseCompiler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. protected static string dynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  43. TemplateParser parser;
  44. CodeDomProvider provider;
  45. ICodeCompiler compiler;
  46. CodeCompileUnit unit;
  47. CodeNamespace mainNS;
  48. CompilerParameters compilerParameters;
  49. protected CodeTypeDeclaration mainClass;
  50. protected CodeTypeReferenceExpression mainClassExpr;
  51. protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
  52. protected BaseCompiler (TemplateParser parser)
  53. {
  54. compilerParameters = new CompilerParameters ();
  55. this.parser = parser;
  56. }
  57. void Init ()
  58. {
  59. unit = new CodeCompileUnit ();
  60. mainNS = new CodeNamespace ("ASP");
  61. unit.Namespaces.Add (mainNS);
  62. mainClass = new CodeTypeDeclaration (parser.ClassName);
  63. mainClass.TypeAttributes = TypeAttributes.Public;
  64. mainNS.Types.Add (mainClass);
  65. mainClass.BaseTypes.Add (new CodeTypeReference (parser.BaseType.FullName));
  66. mainClassExpr = new CodeTypeReferenceExpression ("ASP." + parser.ClassName);
  67. foreach (object o in parser.Imports) {
  68. if (o is string)
  69. mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
  70. }
  71. if (parser.Assemblies != null) {
  72. foreach (object o in parser.Assemblies) {
  73. if (o is string)
  74. unit.ReferencedAssemblies.Add ((string) o);
  75. }
  76. }
  77. AddInterfaces ();
  78. AddClassAttributes ();
  79. CreateStaticFields ();
  80. AddApplicationAndSessionObjects ();
  81. AddScripts ();
  82. CreateConstructor (null, null);
  83. }
  84. protected virtual void CreateStaticFields ()
  85. {
  86. CodeMemberField fld = new CodeMemberField (typeof (bool), "__intialized");
  87. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  88. fld.InitExpression = new CodePrimitiveExpression (false);
  89. mainClass.Members.Add (fld);
  90. }
  91. protected virtual void CreateConstructor (CodeStatementCollection localVars,
  92. CodeStatementCollection trueStmt)
  93. {
  94. CodeConstructor ctor = new CodeConstructor ();
  95. ctor.Attributes = MemberAttributes.Public;
  96. mainClass.Members.Add (ctor);
  97. if (localVars != null)
  98. ctor.Statements.AddRange (localVars);
  99. CodeTypeReferenceExpression r;
  100. r = new CodeTypeReferenceExpression (mainNS.Name + "." + mainClass.Name);
  101. CodeFieldReferenceExpression intialized;
  102. intialized = new CodeFieldReferenceExpression (r, "__intialized");
  103. CodeBinaryOperatorExpression bin;
  104. bin = new CodeBinaryOperatorExpression (intialized,
  105. CodeBinaryOperatorType.ValueEquality,
  106. new CodePrimitiveExpression (false));
  107. CodeAssignStatement assign = new CodeAssignStatement (intialized,
  108. new CodePrimitiveExpression (true));
  109. CodeConditionStatement cond = new CodeConditionStatement (bin, assign);
  110. if (trueStmt != null)
  111. cond.TrueStatements.AddRange (trueStmt);
  112. ctor.Statements.Add (cond);
  113. }
  114. void AddScripts ()
  115. {
  116. if (parser.Scripts == null || parser.Scripts.Count == 0)
  117. return;
  118. foreach (object o in parser.Scripts) {
  119. if (o is string)
  120. mainClass.Members.Add (new CodeSnippetTypeMember ((string) o));
  121. }
  122. }
  123. protected virtual void CreateMethods ()
  124. {
  125. }
  126. protected virtual void AddInterfaces ()
  127. {
  128. if (parser.Interfaces == null)
  129. return;
  130. foreach (object o in parser.Interfaces) {
  131. if (o is string)
  132. mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
  133. }
  134. }
  135. protected virtual void AddClassAttributes ()
  136. {
  137. }
  138. protected virtual void AddApplicationAndSessionObjects ()
  139. {
  140. }
  141. /* Utility methods for <object> stuff */
  142. protected void CreateApplicationOrSessionPropertyForObject (Type type,
  143. string propName,
  144. bool isApplication,
  145. bool isPublic)
  146. {
  147. /* if isApplication this generates (the 'cachedapp' field is created earlier):
  148. private MyNS.MyClass app {
  149. get {
  150. if ((this.cachedapp == null)) {
  151. this.cachedapp = ((MyNS.MyClass)
  152. (this.Application.StaticObjects.GetObject("app")));
  153. }
  154. return this.cachedapp;
  155. }
  156. }
  157. else, this is for Session:
  158. private MyNS.MyClass ses {
  159. get {
  160. return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
  161. }
  162. }
  163. */
  164. CodeExpression result = null;
  165. CodeMemberProperty prop = new CodeMemberProperty ();
  166. prop.Type = new CodeTypeReference (type);
  167. prop.Name = propName;
  168. if (isPublic)
  169. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  170. else
  171. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  172. CodePropertyReferenceExpression p1;
  173. if (isApplication)
  174. p1 = new CodePropertyReferenceExpression (thisRef, "Application");
  175. else
  176. p1 = new CodePropertyReferenceExpression (thisRef, "Session");
  177. CodePropertyReferenceExpression p2;
  178. p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
  179. CodeMethodReferenceExpression getobject;
  180. getobject = new CodeMethodReferenceExpression (p2, "GetObject");
  181. CodeMethodInvokeExpression invoker;
  182. invoker = new CodeMethodInvokeExpression (getobject,
  183. new CodePrimitiveExpression (propName));
  184. CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
  185. if (isApplication) {
  186. CodeFieldReferenceExpression field;
  187. field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
  188. CodeConditionStatement stmt = new CodeConditionStatement();
  189. stmt.Condition = new CodeBinaryOperatorExpression (field,
  190. CodeBinaryOperatorType.IdentityEquality,
  191. new CodePrimitiveExpression (null));
  192. CodeAssignStatement assign = new CodeAssignStatement ();
  193. assign.Left = field;
  194. assign.Right = cast;
  195. stmt.TrueStatements.Add (assign);
  196. prop.GetStatements.Add (stmt);
  197. result = field;
  198. } else {
  199. result = cast;
  200. }
  201. prop.GetStatements.Add (new CodeMethodReturnStatement (result));
  202. mainClass.Members.Add (prop);
  203. }
  204. protected string CreateFieldForObject (Type type, string name)
  205. {
  206. string fieldName = "cached" + name;
  207. CodeMemberField f = new CodeMemberField (type, fieldName);
  208. f.Attributes = MemberAttributes.Private;
  209. mainClass.Members.Add (f);
  210. return fieldName;
  211. }
  212. protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
  213. {
  214. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
  215. CodeMemberProperty prop = new CodeMemberProperty ();
  216. prop.Type = new CodeTypeReference (type);
  217. prop.Name = propName;
  218. if (isPublic)
  219. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  220. else
  221. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  222. CodeConditionStatement stmt = new CodeConditionStatement();
  223. stmt.Condition = new CodeBinaryOperatorExpression (field,
  224. CodeBinaryOperatorType.IdentityEquality,
  225. new CodePrimitiveExpression (null));
  226. CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
  227. stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
  228. prop.GetStatements.Add (stmt);
  229. prop.GetStatements.Add (new CodeMethodReturnStatement (field));
  230. mainClass.Members.Add (prop);
  231. }
  232. /******/
  233. void CheckCompilerErrors (CompilerResults results)
  234. {
  235. if (results.NativeCompilerReturnValue == 0)
  236. return;
  237. StringWriter writer = new StringWriter();
  238. provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
  239. throw new CompilationException (parser.InputFile, results.Errors, writer.ToString ());
  240. }
  241. public virtual Type GetCompiledType ()
  242. {
  243. Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
  244. if (type != null)
  245. return type;
  246. Init ();
  247. string lang = parser.Language;
  248. CompilationConfiguration config;
  249. config = CompilationConfiguration.GetInstance (parser.Context);
  250. provider = config.GetProvider (lang);
  251. if (provider == null)
  252. throw new HttpException ("Configuration error. Language not supported: " +
  253. lang, 500);
  254. compiler = provider.CreateCompiler ();
  255. CreateMethods ();
  256. compilerParameters.IncludeDebugInformation = parser.Debug;
  257. compilerParameters.CompilerOptions = config.GetCompilerOptions (lang) + " " +
  258. parser.CompilerOptions;
  259. compilerParameters.WarningLevel = config.GetWarningLevel (lang);
  260. bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
  261. TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, keepFiles);
  262. compilerParameters.TempFiles = tempcoll;
  263. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  264. if (!Directory.Exists (dynamicBase))
  265. Directory.CreateDirectory (dynamicBase);
  266. compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename);
  267. CompilerResults results = CachingCompiler.Compile (this);
  268. CheckCompilerErrors (results);
  269. if (results.CompiledAssembly == null)
  270. throw new CompilationException (parser.InputFile, results.Errors,
  271. "No assembly returned after compilation!?");
  272. results.TempFiles.Delete ();
  273. return results.CompiledAssembly.GetType (mainClassExpr.Type.BaseType, true);
  274. }
  275. internal CompilerParameters CompilerParameters {
  276. get { return compilerParameters; }
  277. }
  278. internal CodeCompileUnit Unit {
  279. get { return unit; }
  280. }
  281. internal virtual ICodeCompiler Compiler {
  282. get { return compiler; }
  283. }
  284. internal TemplateParser Parser {
  285. get { return parser; }
  286. }
  287. }
  288. }