BaseCompiler.cs 24 KB

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