2
0

BaseCompiler.cs 11 KB

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