BaseCompiler.cs 11 KB

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