BaseCompiler.cs 24 KB

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