BaseCompiler.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. const string DEFAULT_NAMESPACE = "ASP";
  44. internal static Guid HashMD5 = new Guid(0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
  45. static BindingFlags replaceableFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  46. TemplateParser parser;
  47. CodeDomProvider provider;
  48. ICodeCompiler compiler;
  49. CodeCompileUnit unit;
  50. CodeNamespace mainNS;
  51. CompilerParameters compilerParameters;
  52. bool isRebuilding = false;
  53. protected Hashtable partialNameOverride = new Hashtable();
  54. protected CodeTypeDeclaration partialClass;
  55. protected CodeTypeReferenceExpression partialClassExpr;
  56. protected CodeTypeDeclaration mainClass;
  57. protected CodeTypeReferenceExpression mainClassExpr;
  58. protected static CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression ();
  59. VirtualPath inputVirtualPath;
  60. public VirtualPath InputVirtualPath {
  61. get {
  62. if (inputVirtualPath == null)
  63. inputVirtualPath = new VirtualPath (VirtualPathUtility.Combine (parser.BaseVirtualDir, Path.GetFileName (parser.InputFile)));
  64. return inputVirtualPath;
  65. }
  66. }
  67. protected BaseCompiler (TemplateParser parser)
  68. {
  69. this.parser = parser;
  70. }
  71. protected void AddReferencedAssembly (Assembly asm)
  72. {
  73. if (unit == null || asm == null)
  74. return;
  75. StringCollection refAsm = unit.ReferencedAssemblies;
  76. string asmLocation = asm.Location;
  77. if (!refAsm.Contains (asmLocation))
  78. refAsm.Add (asmLocation);
  79. }
  80. internal CodeStatement AddLinePragma (CodeExpression expression, ControlBuilder builder)
  81. {
  82. return AddLinePragma (new CodeExpressionStatement (expression), builder);
  83. }
  84. internal CodeStatement AddLinePragma (CodeStatement statement, ControlBuilder builder)
  85. {
  86. if (builder == null || statement == null)
  87. return statement;
  88. ILocation location = null;
  89. if (!(builder is CodeRenderBuilder))
  90. location = builder.Location;
  91. if (location != null)
  92. return AddLinePragma (statement, location);
  93. else
  94. return AddLinePragma (statement, builder.Line, builder.FileName);
  95. }
  96. internal CodeStatement AddLinePragma (CodeStatement statement, ILocation location)
  97. {
  98. if (location == null || statement == null)
  99. return statement;
  100. return AddLinePragma (statement, location.BeginLine, location.Filename);
  101. }
  102. bool IgnoreFile (string fileName)
  103. {
  104. if (parser != null && !parser.LinePragmasOn)
  105. return true;
  106. return String.Compare (fileName, "@@inner_string@@", StringComparison.OrdinalIgnoreCase) == 0;
  107. }
  108. internal CodeStatement AddLinePragma (CodeStatement statement, int line, string fileName)
  109. {
  110. if (statement == null || IgnoreFile (fileName))
  111. return statement;
  112. statement.LinePragma = new CodeLinePragma (fileName, line);
  113. return statement;
  114. }
  115. internal CodeTypeMember AddLinePragma (CodeTypeMember member, ControlBuilder builder)
  116. {
  117. if (builder == null || member == null)
  118. return member;
  119. ILocation location = builder.Location;
  120. if (location != null)
  121. return AddLinePragma (member, location);
  122. else
  123. return AddLinePragma (member, builder.Line, builder.FileName);
  124. }
  125. internal CodeTypeMember AddLinePragma (CodeTypeMember member, ILocation location)
  126. {
  127. if (location == null || member == null)
  128. return member;
  129. return AddLinePragma (member, location.BeginLine, location.Filename);
  130. }
  131. internal CodeTypeMember AddLinePragma (CodeTypeMember member, int line, string fileName)
  132. {
  133. if (member == null || IgnoreFile (fileName))
  134. return member;
  135. member.LinePragma = new CodeLinePragma (fileName, line);
  136. return member;
  137. }
  138. internal void ConstructType ()
  139. {
  140. unit = new CodeCompileUnit ();
  141. byte[] md5checksum = parser.MD5Checksum;
  142. if (md5checksum != null) {
  143. CodeChecksumPragma pragma = new CodeChecksumPragma ();
  144. pragma.FileName = parser.InputFile;
  145. pragma.ChecksumAlgorithmId = HashMD5;
  146. pragma.ChecksumData = md5checksum;
  147. unit.StartDirectives.Add (pragma);
  148. }
  149. if (parser.IsPartial) {
  150. string partialns = null;
  151. string partialclasstype = parser.PartialClassName;
  152. int partialdot = partialclasstype.LastIndexOf ('.');
  153. if (partialdot != -1) {
  154. partialns = partialclasstype.Substring (0, partialdot);
  155. partialclasstype = partialclasstype.Substring (partialdot + 1);
  156. }
  157. CodeNamespace partialNS = new CodeNamespace (partialns);
  158. partialClass = new CodeTypeDeclaration (partialclasstype);
  159. partialClass.IsPartial = true;
  160. partialClassExpr = new CodeTypeReferenceExpression (parser.PartialClassName);
  161. unit.Namespaces.Add (partialNS);
  162. partialClass.TypeAttributes = TypeAttributes.Public;
  163. partialNS.Types.Add (partialClass);
  164. }
  165. string mainclasstype = parser.ClassName;
  166. string mainns = DEFAULT_NAMESPACE;
  167. int maindot = mainclasstype.LastIndexOf ('.');
  168. if (maindot != -1) {
  169. mainns = mainclasstype.Substring (0, maindot);
  170. mainclasstype = mainclasstype.Substring (maindot + 1);
  171. }
  172. mainNS = new CodeNamespace (mainns);
  173. mainClass = new CodeTypeDeclaration (mainclasstype);
  174. CodeTypeReference baseTypeRef;
  175. if (partialClass != null) {
  176. baseTypeRef = new CodeTypeReference (parser.PartialClassName);
  177. baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  178. } else {
  179. baseTypeRef = new CodeTypeReference (parser.BaseType.FullName);
  180. if (parser.BaseTypeIsGlobal)
  181. baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  182. }
  183. mainClass.BaseTypes.Add (baseTypeRef);
  184. mainClassExpr = new CodeTypeReferenceExpression (mainns + "." + mainclasstype);
  185. unit.Namespaces.Add (mainNS);
  186. mainClass.TypeAttributes = TypeAttributes.Public;
  187. mainNS.Types.Add (mainClass);
  188. foreach (object o in parser.Imports.Keys) {
  189. if (o is string)
  190. mainNS.Imports.Add (new CodeNamespaceImport ((string) o));
  191. }
  192. // StringCollection.Contains has O(n) complexity, but
  193. // considering the number of comparisons we make on
  194. // average and the fact that using an intermediate array
  195. // would be even more costly, this is fine here.
  196. StringCollection refAsm = unit.ReferencedAssemblies;
  197. string asmName;
  198. if (parser.Assemblies != null) {
  199. foreach (object o in parser.Assemblies) {
  200. asmName = o as string;
  201. if (asmName != null && !refAsm.Contains (asmName))
  202. refAsm.Add (asmName);
  203. }
  204. }
  205. ArrayList al = WebConfigurationManager.ExtraAssemblies;
  206. if (al != null && al.Count > 0) {
  207. foreach (object o in al) {
  208. asmName = o as string;
  209. if (asmName != null && !refAsm.Contains (asmName))
  210. refAsm.Add (asmName);
  211. }
  212. }
  213. IList list = BuildManager.CodeAssemblies;
  214. if (list != null && list.Count > 0) {
  215. Assembly asm;
  216. foreach (object o in list) {
  217. asm = o as Assembly;
  218. if (o == null)
  219. continue;
  220. asmName = asm.Location;
  221. if (asmName != null && !refAsm.Contains (asmName))
  222. refAsm.Add (asmName);
  223. }
  224. }
  225. // Late-bound generators specifics (as for MonoBASIC/VB.NET)
  226. unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
  227. unit.UserData["AllowLateBound"] = !parser.StrictOn;
  228. InitializeType ();
  229. AddInterfaces ();
  230. AddClassAttributes ();
  231. CreateStaticFields ();
  232. AddApplicationAndSessionObjects ();
  233. AddScripts ();
  234. CreateMethods ();
  235. CreateConstructor (null, null);
  236. }
  237. internal CodeFieldReferenceExpression GetMainClassFieldReferenceExpression (string fieldName)
  238. {
  239. CodeTypeReference mainClassTypeRef;
  240. mainClassTypeRef = new CodeTypeReference (mainNS.Name + "." + mainClass.Name);
  241. mainClassTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  242. return new CodeFieldReferenceExpression (
  243. new CodeTypeReferenceExpression (mainClassTypeRef), fieldName);
  244. }
  245. protected virtual void InitializeType ()
  246. {}
  247. protected virtual void CreateStaticFields ()
  248. {
  249. CodeMemberField fld = new CodeMemberField (typeof (bool), "__initialized");
  250. fld.Attributes = MemberAttributes.Private | MemberAttributes.Static;
  251. fld.InitExpression = new CodePrimitiveExpression (false);
  252. mainClass.Members.Add (fld);
  253. }
  254. void AssignAppRelativeVirtualPath (CodeConstructor ctor)
  255. {
  256. if (String.IsNullOrEmpty (parser.InputFile))
  257. return;
  258. Type baseType = parser.CodeFileBaseClassType;
  259. if (baseType == null)
  260. baseType = parser.BaseType;
  261. if (baseType == null)
  262. return;
  263. if (!baseType.IsSubclassOf (typeof (System.Web.UI.TemplateControl)))
  264. return;
  265. CodeTypeReference baseTypeRef = new CodeTypeReference (baseType.FullName);
  266. if (parser.BaseTypeIsGlobal)
  267. baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
  268. CodeExpression cast = new CodeCastExpression (baseTypeRef, new CodeThisReferenceExpression ());
  269. CodePropertyReferenceExpression arvpProp = new CodePropertyReferenceExpression (cast, "AppRelativeVirtualPath");
  270. CodeAssignStatement arvpAssign = new CodeAssignStatement ();
  271. arvpAssign.Left = arvpProp;
  272. arvpAssign.Right = new CodePrimitiveExpression (VirtualPathUtility.RemoveTrailingSlash (InputVirtualPath.AppRelative));
  273. ctor.Statements.Add (arvpAssign);
  274. }
  275. protected virtual void CreateConstructor (CodeStatementCollection localVars,
  276. CodeStatementCollection trueStmt)
  277. {
  278. CodeConstructor ctor = new CodeConstructor ();
  279. ctor.Attributes = MemberAttributes.Public;
  280. mainClass.Members.Add (ctor);
  281. if (localVars != null)
  282. ctor.Statements.AddRange (localVars);
  283. AssignAppRelativeVirtualPath (ctor);
  284. CodeFieldReferenceExpression initialized = GetMainClassFieldReferenceExpression ("__initialized");
  285. CodeBinaryOperatorExpression bin;
  286. bin = new CodeBinaryOperatorExpression (initialized,
  287. CodeBinaryOperatorType.ValueEquality,
  288. new CodePrimitiveExpression (false));
  289. CodeAssignStatement assign = new CodeAssignStatement (initialized,
  290. new CodePrimitiveExpression (true));
  291. CodeConditionStatement cond = new CodeConditionStatement ();
  292. cond.Condition = bin;
  293. if (trueStmt != null)
  294. cond.TrueStatements.AddRange (trueStmt);
  295. cond.TrueStatements.Add (assign);
  296. ctor.Statements.Add (cond);
  297. AddStatementsToConstructor (ctor);
  298. }
  299. protected virtual void AddStatementsToConstructor (CodeConstructor ctor)
  300. {
  301. }
  302. void AddScripts ()
  303. {
  304. if (parser.Scripts == null || parser.Scripts.Count == 0)
  305. return;
  306. ServerSideScript sss;
  307. foreach (object o in parser.Scripts) {
  308. sss = o as ServerSideScript;
  309. if (sss == null)
  310. continue;
  311. mainClass.Members.Add (AddLinePragma (new CodeSnippetTypeMember (sss.Script), sss.Location));
  312. }
  313. }
  314. protected internal virtual void CreateMethods ()
  315. {
  316. }
  317. void InternalCreatePageProperty (string retType, string name, string contextProperty)
  318. {
  319. CodeMemberProperty property = new CodeMemberProperty ();
  320. property.Name = name;
  321. property.Type = new CodeTypeReference (retType);
  322. property.Attributes = MemberAttributes.Family | MemberAttributes.Final;
  323. CodeMethodReturnStatement ret = new CodeMethodReturnStatement ();
  324. CodeCastExpression cast = new CodeCastExpression ();
  325. ret.Expression = cast;
  326. CodePropertyReferenceExpression refexp = new CodePropertyReferenceExpression ();
  327. refexp.TargetObject = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Context");
  328. refexp.PropertyName = contextProperty;
  329. cast.TargetType = new CodeTypeReference (retType);
  330. cast.Expression = refexp;
  331. property.GetStatements.Add (ret);
  332. if (partialClass == null)
  333. mainClass.Members.Add (property);
  334. else
  335. partialClass.Members.Add (property);
  336. }
  337. protected void CreateProfileProperty ()
  338. {
  339. string retType;
  340. if (AppCodeCompiler.HaveCustomProfile (WebConfigurationManager.GetWebApplicationSection ("system.web/profile") as ProfileSection))
  341. retType = "ProfileCommon";
  342. else
  343. retType = "System.Web.Profile.DefaultProfile";
  344. InternalCreatePageProperty (retType, "Profile", "Profile");
  345. }
  346. protected virtual void AddInterfaces ()
  347. {
  348. if (parser.Interfaces == null)
  349. return;
  350. foreach (object o in parser.Interfaces) {
  351. if (o is string)
  352. mainClass.BaseTypes.Add (new CodeTypeReference ((string) o));
  353. }
  354. }
  355. protected virtual void AddClassAttributes ()
  356. {
  357. }
  358. protected virtual void AddApplicationAndSessionObjects ()
  359. {
  360. }
  361. /* Utility methods for <object> stuff */
  362. protected void CreateApplicationOrSessionPropertyForObject (Type type,
  363. string propName,
  364. bool isApplication,
  365. bool isPublic)
  366. {
  367. /* if isApplication this generates (the 'cachedapp' field is created earlier):
  368. private MyNS.MyClass app {
  369. get {
  370. if ((this.cachedapp == null)) {
  371. this.cachedapp = ((MyNS.MyClass)
  372. (this.Application.StaticObjects.GetObject("app")));
  373. }
  374. return this.cachedapp;
  375. }
  376. }
  377. else, this is for Session:
  378. private MyNS.MyClass ses {
  379. get {
  380. return ((MyNS.MyClass) (this.Session.StaticObjects.GetObject("ses")));
  381. }
  382. }
  383. */
  384. CodeExpression result = null;
  385. CodeMemberProperty prop = new CodeMemberProperty ();
  386. prop.Type = new CodeTypeReference (type);
  387. prop.Name = propName;
  388. if (isPublic)
  389. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  390. else
  391. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  392. CodePropertyReferenceExpression p1;
  393. if (isApplication)
  394. p1 = new CodePropertyReferenceExpression (thisRef, "Application");
  395. else
  396. p1 = new CodePropertyReferenceExpression (thisRef, "Session");
  397. CodePropertyReferenceExpression p2;
  398. p2 = new CodePropertyReferenceExpression (p1, "StaticObjects");
  399. CodeMethodReferenceExpression getobject;
  400. getobject = new CodeMethodReferenceExpression (p2, "GetObject");
  401. CodeMethodInvokeExpression invoker;
  402. invoker = new CodeMethodInvokeExpression (getobject,
  403. new CodePrimitiveExpression (propName));
  404. CodeCastExpression cast = new CodeCastExpression (prop.Type, invoker);
  405. if (isApplication) {
  406. CodeFieldReferenceExpression field;
  407. field = new CodeFieldReferenceExpression (thisRef, "cached" + propName);
  408. CodeConditionStatement stmt = new CodeConditionStatement();
  409. stmt.Condition = new CodeBinaryOperatorExpression (field,
  410. CodeBinaryOperatorType.IdentityEquality,
  411. new CodePrimitiveExpression (null));
  412. CodeAssignStatement assign = new CodeAssignStatement ();
  413. assign.Left = field;
  414. assign.Right = cast;
  415. stmt.TrueStatements.Add (assign);
  416. prop.GetStatements.Add (stmt);
  417. result = field;
  418. } else {
  419. result = cast;
  420. }
  421. prop.GetStatements.Add (new CodeMethodReturnStatement (result));
  422. mainClass.Members.Add (prop);
  423. }
  424. protected string CreateFieldForObject (Type type, string name)
  425. {
  426. string fieldName = "cached" + name;
  427. CodeMemberField f = new CodeMemberField (type, fieldName);
  428. f.Attributes = MemberAttributes.Private;
  429. mainClass.Members.Add (f);
  430. return fieldName;
  431. }
  432. protected void CreatePropertyForObject (Type type, string propName, string fieldName, bool isPublic)
  433. {
  434. CodeFieldReferenceExpression field = new CodeFieldReferenceExpression (thisRef, fieldName);
  435. CodeMemberProperty prop = new CodeMemberProperty ();
  436. prop.Type = new CodeTypeReference (type);
  437. prop.Name = propName;
  438. if (isPublic)
  439. prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  440. else
  441. prop.Attributes = MemberAttributes.Private | MemberAttributes.Final;
  442. CodeConditionStatement stmt = new CodeConditionStatement();
  443. stmt.Condition = new CodeBinaryOperatorExpression (field,
  444. CodeBinaryOperatorType.IdentityEquality,
  445. new CodePrimitiveExpression (null));
  446. CodeObjectCreateExpression create = new CodeObjectCreateExpression (prop.Type);
  447. stmt.TrueStatements.Add (new CodeAssignStatement (field, create));
  448. prop.GetStatements.Add (stmt);
  449. prop.GetStatements.Add (new CodeMethodReturnStatement (field));
  450. mainClass.Members.Add (prop);
  451. }
  452. /******/
  453. void CheckCompilerErrors (CompilerResults results)
  454. {
  455. if (results.NativeCompilerReturnValue == 0)
  456. return;
  457. string fileText = null;
  458. CompilerErrorCollection errors = results.Errors;
  459. CompilerError ce = (errors != null && errors.Count > 0) ? errors [0] : null;
  460. string inFile = (ce != null) ? ce.FileName : null;
  461. if (inFile != null && File.Exists (inFile)) {
  462. using (StreamReader sr = File.OpenText (inFile)) {
  463. fileText = sr.ReadToEnd ();
  464. }
  465. } else {
  466. StringWriter writer = new StringWriter();
  467. provider.CreateGenerator().GenerateCodeFromCompileUnit (unit, writer, null);
  468. fileText = writer.ToString ();
  469. }
  470. throw new CompilationException (parser.InputFile, errors, fileText);
  471. }
  472. protected string DynamicDir ()
  473. {
  474. return AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  475. }
  476. internal static CodeDomProvider CreateProvider (string lang)
  477. {
  478. CompilerParameters par;
  479. string tempdir;
  480. return CreateProvider (HttpContext.Current, lang, out par, out tempdir);
  481. }
  482. internal static CodeDomProvider CreateProvider (string lang, out string compilerOptions, out int warningLevel, out string tempdir)
  483. {
  484. return CreateProvider (HttpContext.Current, lang, out compilerOptions, out warningLevel, out tempdir);
  485. }
  486. internal static CodeDomProvider CreateProvider (HttpContext context, string lang, out string compilerOptions, out int warningLevel, out string tempdir)
  487. {
  488. CodeDomProvider ret;
  489. CompilerParameters par;
  490. ret = CreateProvider (context, lang, out par, out tempdir);
  491. if (par != null){
  492. warningLevel = par.WarningLevel;
  493. compilerOptions = par.CompilerOptions;
  494. } else {
  495. warningLevel = 2;
  496. compilerOptions = String.Empty;
  497. }
  498. return ret;
  499. }
  500. internal static CodeDomProvider CreateProvider (HttpContext context, string lang, out CompilerParameters par, out string tempdir)
  501. {
  502. CodeDomProvider ret = null;
  503. par = null;
  504. CompilationSection config = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  505. Compiler comp = config.Compilers[lang];
  506. if (comp == null) {
  507. CompilerInfo info = CodeDomProvider.GetCompilerInfo (lang);
  508. if (info != null && info.IsCodeDomProviderTypeValid) {
  509. ret = info.CreateProvider ();
  510. par = info.CreateDefaultCompilerParameters ();
  511. }
  512. } else {
  513. Type t = HttpApplication.LoadType (comp.Type, true);
  514. ret = Activator.CreateInstance (t) as CodeDomProvider;
  515. par = new CompilerParameters ();
  516. par.CompilerOptions = comp.CompilerOptions;
  517. par.WarningLevel = comp.WarningLevel;
  518. }
  519. tempdir = config.TempDirectory;
  520. return ret;
  521. }
  522. [MonoTODO ("find out how to extract the warningLevel and compilerOptions in the <system.codedom> case")]
  523. public virtual Type GetCompiledType ()
  524. {
  525. Type type = CachingCompiler.GetTypeFromCache (parser.InputFile);
  526. if (type != null)
  527. return type;
  528. ConstructType ();
  529. string lang = parser.Language;
  530. string tempdir;
  531. string compilerOptions;
  532. int warningLevel;
  533. Provider = CreateProvider (parser.Context, lang, out compilerOptions, out warningLevel, out tempdir);
  534. if (Provider == null)
  535. throw new HttpException ("Configuration error. Language not supported: " +
  536. lang, 500);
  537. CompilerParameters parameters = CompilerParameters;
  538. parameters.IncludeDebugInformation = parser.Debug;
  539. parameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions;
  540. parameters.WarningLevel = warningLevel;
  541. bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
  542. if (tempdir == null || tempdir == "")
  543. tempdir = DynamicDir ();
  544. TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles);
  545. parameters.TempFiles = tempcoll;
  546. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  547. parameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename);
  548. CompilerResults results = CachingCompiler.Compile (this);
  549. CheckCompilerErrors (results);
  550. Assembly assembly = results.CompiledAssembly;
  551. if (assembly == null) {
  552. if (!File.Exists (parameters.OutputAssembly)) {
  553. results.TempFiles.Delete ();
  554. throw new CompilationException (parser.InputFile, results.Errors,
  555. "No assembly returned after compilation!?");
  556. }
  557. assembly = Assembly.LoadFrom (parameters.OutputAssembly);
  558. }
  559. results.TempFiles.Delete ();
  560. Type mainClassType = assembly.GetType (MainClassType, true);
  561. if (parser.IsPartial) {
  562. // With the partial classes, we need to make sure we
  563. // don't have any methods that should have not been
  564. // created (because they are accessible from the base
  565. // types). We cannot do this normally because the
  566. // codebehind file is actually a partial class and we
  567. // have no way of identifying the partial class' base
  568. // type until now.
  569. if (!isRebuilding && CheckPartialBaseType (mainClassType)) {
  570. isRebuilding = true;
  571. parser.RootBuilder.ResetState ();
  572. return GetCompiledType ();
  573. }
  574. }
  575. return mainClassType;
  576. }
  577. internal string MainClassType {
  578. get {
  579. if (mainClassExpr == null)
  580. return null;
  581. return mainClassExpr.Type.BaseType;
  582. }
  583. }
  584. internal bool IsRebuildingPartial
  585. {
  586. get { return isRebuilding; }
  587. }
  588. internal bool CheckPartialBaseType (Type type)
  589. {
  590. // Get the base type. If we don't have any (bad thing), we
  591. // don't need to replace ourselves. Also check for the
  592. // core file, since that won't have any either.
  593. Type baseType = type.BaseType;
  594. if (baseType == null || baseType == typeof(System.Web.UI.Page))
  595. return false;
  596. bool rebuild = false;
  597. if (CheckPartialBaseFields (type, baseType))
  598. rebuild = true;
  599. if (CheckPartialBaseProperties (type, baseType))
  600. rebuild = true;
  601. return rebuild;
  602. }
  603. internal bool CheckPartialBaseFields (Type type, Type baseType)
  604. {
  605. bool rebuild = false;
  606. foreach (FieldInfo baseInfo in baseType.GetFields (replaceableFlags)) {
  607. if (baseInfo.IsPrivate)
  608. continue;
  609. FieldInfo typeInfo = type.GetField (baseInfo.Name, replaceableFlags);
  610. if (typeInfo != null && typeInfo.DeclaringType == type) {
  611. partialNameOverride [typeInfo.Name] = true;
  612. rebuild = true;
  613. }
  614. }
  615. return rebuild;
  616. }
  617. internal bool CheckPartialBaseProperties (Type type, Type baseType)
  618. {
  619. bool rebuild = false;
  620. foreach (PropertyInfo baseInfo in baseType.GetProperties ()) {
  621. PropertyInfo typeInfo = type.GetProperty (baseInfo.Name);
  622. if (typeInfo != null && typeInfo.DeclaringType == type) {
  623. partialNameOverride [typeInfo.Name] = true;
  624. rebuild = true;
  625. }
  626. }
  627. return rebuild;
  628. }
  629. internal CodeDomProvider Provider {
  630. get { return provider; }
  631. set { provider = value; }
  632. }
  633. internal ICodeCompiler Compiler {
  634. get { return compiler; }
  635. set { compiler = value; }
  636. }
  637. internal CompilerParameters CompilerParameters {
  638. get {
  639. if (compilerParameters == null)
  640. compilerParameters = new CompilerParameters ();
  641. return compilerParameters;
  642. }
  643. set { compilerParameters = value; }
  644. }
  645. internal CodeCompileUnit CompileUnit {
  646. get { return unit; }
  647. }
  648. internal CodeTypeDeclaration DerivedType {
  649. get { return mainClass; }
  650. }
  651. internal CodeTypeDeclaration BaseType {
  652. get {
  653. if (partialClass == null)
  654. return DerivedType;
  655. return partialClass;
  656. }
  657. }
  658. internal TemplateParser Parser {
  659. get { return parser; }
  660. }
  661. }
  662. }