AspGenerator.cs 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. //
  2. // System.Web.Compilation.AspGenerator
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. // Copyright (c) 2004,2006 Novell, Inc (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.CodeDom.Compiler;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Text;
  36. using System.Text.RegularExpressions;
  37. using System.Web.Caching;
  38. using System.Web.Configuration;
  39. using System.Web.Hosting;
  40. using System.Web.UI;
  41. using System.Web.UI.HtmlControls;
  42. using System.Web.Util;
  43. namespace System.Web.Compilation
  44. {
  45. class BuilderLocation
  46. {
  47. public ControlBuilder Builder;
  48. public ILocation Location;
  49. public BuilderLocation (ControlBuilder builder, ILocation location)
  50. {
  51. this.Builder = builder;
  52. this.Location = location;
  53. }
  54. }
  55. class BuilderLocationStack : Stack
  56. {
  57. public override void Push (object o)
  58. {
  59. if (!(o is BuilderLocation))
  60. throw new InvalidOperationException ();
  61. base.Push (o);
  62. }
  63. public virtual void Push (ControlBuilder builder, ILocation location)
  64. {
  65. BuilderLocation bl = new BuilderLocation (builder, location);
  66. Push (bl);
  67. }
  68. public new BuilderLocation Peek ()
  69. {
  70. return (BuilderLocation) base.Peek ();
  71. }
  72. public new BuilderLocation Pop ()
  73. {
  74. return (BuilderLocation) base.Pop ();
  75. }
  76. public ControlBuilder Builder {
  77. get { return Peek ().Builder; }
  78. }
  79. }
  80. class ParserStack
  81. {
  82. Hashtable files;
  83. Stack parsers;
  84. AspParser current;
  85. public ParserStack ()
  86. {
  87. files = new Hashtable (); // may be this should be case sensitive for windows
  88. parsers = new Stack ();
  89. }
  90. public bool Push (AspParser parser)
  91. {
  92. if (files.Contains (parser.Filename))
  93. return false;
  94. files [parser.Filename] = true;
  95. parsers.Push (parser);
  96. current = parser;
  97. return true;
  98. }
  99. public AspParser Pop ()
  100. {
  101. if (parsers.Count == 0)
  102. return null;
  103. files.Remove (current.Filename);
  104. AspParser result = (AspParser) parsers.Pop ();
  105. if (parsers.Count > 0)
  106. current = (AspParser) parsers.Peek ();
  107. else
  108. current = null;
  109. return result;
  110. }
  111. public int Count {
  112. get { return parsers.Count; }
  113. }
  114. public AspParser Parser {
  115. get { return current; }
  116. }
  117. public string Filename {
  118. get { return current.Filename; }
  119. }
  120. }
  121. class TagStack
  122. {
  123. Stack tags;
  124. public TagStack ()
  125. {
  126. tags = new Stack ();
  127. }
  128. public void Push (string tagid)
  129. {
  130. tags.Push (tagid);
  131. }
  132. public string Pop ()
  133. {
  134. if (tags.Count == 0)
  135. return null;
  136. return (string) tags.Pop ();
  137. }
  138. public bool CompareTo (string tagid)
  139. {
  140. if (tags.Count == 0)
  141. return false;
  142. return 0 == String.Compare (tagid, (string) tags.Peek (), true, CultureInfo.InvariantCulture);
  143. }
  144. public int Count {
  145. get { return tags.Count; }
  146. }
  147. public string Current {
  148. get { return (string) tags.Peek (); }
  149. }
  150. }
  151. class AspGenerator
  152. {
  153. ParserStack pstack;
  154. BuilderLocationStack stack;
  155. TemplateParser tparser;
  156. StringBuilder text;
  157. RootBuilder rootBuilder;
  158. bool inScript, javascript, ignore_text;
  159. ILocation location;
  160. bool isApplication;
  161. StringBuilder tagInnerText = new StringBuilder ();
  162. static Hashtable emptyHash = new Hashtable ();
  163. bool inForm;
  164. bool useOtherTags;
  165. TagType lastTag;
  166. public AspGenerator (TemplateParser tparser)
  167. {
  168. this.tparser = tparser;
  169. text = new StringBuilder ();
  170. stack = new BuilderLocationStack ();
  171. rootBuilder = new RootBuilder (tparser);
  172. stack.Push (rootBuilder, null);
  173. tparser.RootBuilder = rootBuilder;
  174. pstack = new ParserStack ();
  175. }
  176. public RootBuilder RootBuilder {
  177. get { return tparser.RootBuilder; }
  178. }
  179. public AspParser Parser {
  180. get { return pstack.Parser; }
  181. }
  182. public string Filename {
  183. get { return pstack.Filename; }
  184. }
  185. #if NET_2_0
  186. PageParserFilter PageParserFilter {
  187. get {
  188. if (tparser == null)
  189. return null;
  190. return tparser.PageParserFilter;
  191. }
  192. }
  193. #endif
  194. BaseCompiler GetCompilerFromType ()
  195. {
  196. Type type = tparser.GetType ();
  197. if (type == typeof (PageParser))
  198. return new PageCompiler ((PageParser) tparser);
  199. if (type == typeof (ApplicationFileParser))
  200. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  201. if (type == typeof (UserControlParser))
  202. return new UserControlCompiler ((UserControlParser) tparser);
  203. #if NET_2_0
  204. if (type == typeof(MasterPageParser))
  205. return new MasterPageCompiler ((MasterPageParser) tparser);
  206. #endif
  207. throw new Exception ("Got type: " + type);
  208. }
  209. void InitParser (TextReader reader, string filename)
  210. {
  211. AspParser parser = new AspParser (filename, reader);
  212. parser.Error += new ParseErrorHandler (ParseError);
  213. parser.TagParsed += new TagParsedHandler (TagParsed);
  214. parser.TextParsed += new TextParsedHandler (TextParsed);
  215. #if NET_2_0
  216. parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
  217. tparser.AspGenerator = this;
  218. #endif
  219. if (!pstack.Push (parser))
  220. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  221. if (filename != "@@inner_string@@") {
  222. string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
  223. if (VirtualPathUtility.IsAbsolute (arvp))
  224. arvp = VirtualPathUtility.ToAppRelative (arvp);
  225. tparser.AddDependency (arvp);
  226. }
  227. #if NET_2_0
  228. tparser.MD5Checksum = parser.MD5Checksum;
  229. #endif
  230. }
  231. #if NET_2_0
  232. void InitParser (string filename)
  233. {
  234. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  235. InitParser (reader, filename);
  236. }
  237. #endif
  238. public void Parse (string file)
  239. {
  240. #if ONLY_1_1
  241. Parse (file, true);
  242. #else
  243. Parse (file, false);
  244. #endif
  245. }
  246. public void Parse (TextReader reader, string filename, bool doInitParser)
  247. {
  248. try {
  249. isApplication = tparser.DefaultDirectiveName == "application";
  250. if (doInitParser)
  251. InitParser (reader, filename);
  252. pstack.Parser.Parse ();
  253. if (text.Length > 0)
  254. FlushText ();
  255. pstack.Pop ();
  256. #if DEBUG
  257. PrintTree (rootBuilder, 0);
  258. #endif
  259. if (stack.Count > 1 && pstack.Count == 0)
  260. throw new ParseException (stack.Builder.Location,
  261. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  262. } finally {
  263. if (reader != null)
  264. reader.Close ();
  265. }
  266. }
  267. public void Parse (Stream stream, string filename, bool doInitParser)
  268. {
  269. Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
  270. }
  271. public void Parse (string filename, bool doInitParser)
  272. {
  273. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  274. Parse (reader, filename, doInitParser);
  275. }
  276. public void Parse ()
  277. {
  278. #if NET_2_0
  279. string inputFile = tparser.InputFile;
  280. TextReader inputReader = tparser.Reader;
  281. try {
  282. if (String.IsNullOrEmpty (inputFile)) {
  283. StreamReader sr = inputReader as StreamReader;
  284. if (sr != null) {
  285. FileStream fr = sr.BaseStream as FileStream;
  286. if (fr != null)
  287. inputFile = fr.Name;
  288. }
  289. if (String.IsNullOrEmpty (inputFile))
  290. inputFile = "@@inner_string@@";
  291. }
  292. if (inputReader != null) {
  293. Parse (inputReader, inputFile, true);
  294. } else {
  295. if (String.IsNullOrEmpty (inputFile))
  296. throw new HttpException ("Parser input file is empty, cannot continue.");
  297. inputFile = Path.GetFullPath (inputFile);
  298. InitParser (inputFile);
  299. Parse (inputFile);
  300. }
  301. } finally {
  302. if (inputReader != null)
  303. inputReader.Close ();
  304. }
  305. #else
  306. Parse (Path.GetFullPath (tparser.InputFile));
  307. #endif
  308. }
  309. internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
  310. {
  311. if (type == null || inputFile == null || inputFile.Length == 0)
  312. return;
  313. if (dependencies != null && dependencies.Count > 0) {
  314. string [] deps = (string []) dependencies.ToArray (typeof (string));
  315. HttpContext ctx = HttpContext.Current;
  316. HttpRequest req = ctx != null ? ctx.Request : null;
  317. if (req == null)
  318. throw new HttpException ("No current context, cannot compile.");
  319. for (int i = 0; i < deps.Length; i++)
  320. deps [i] = req.MapPath (deps [i]);
  321. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
  322. } else
  323. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
  324. }
  325. public Type GetCompiledType ()
  326. {
  327. Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
  328. if (type != null) {
  329. return type;
  330. }
  331. Parse ();
  332. BaseCompiler compiler = GetCompilerFromType ();
  333. type = compiler.GetCompiledType ();
  334. AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
  335. return type;
  336. }
  337. #if DEBUG
  338. static void PrintTree (ControlBuilder builder, int indent)
  339. {
  340. if (builder == null)
  341. return;
  342. string i = new string ('\t', indent);
  343. Console.Write (i);
  344. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  345. builder, builder.ID, builder.ControlType, builder.ParentBuilder);
  346. if (builder.Children != null)
  347. foreach (object o in builder.Children) {
  348. if (o is ControlBuilder)
  349. PrintTree ((ControlBuilder) o, indent++);
  350. }
  351. }
  352. static void PrintLocation (ILocation loc)
  353. {
  354. Console.WriteLine ("\tFile name: " + loc.Filename);
  355. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  356. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  357. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  358. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  359. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  360. Console.WriteLine ();
  361. }
  362. #endif
  363. void ParseError (ILocation location, string message)
  364. {
  365. throw new ParseException (location, message);
  366. }
  367. // KLUDGE WARNING!!
  368. //
  369. // The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
  370. // around a limitation of the current asp.net parser which is unable to parse server
  371. // controls inside client tag attributes. Since the architecture of the current
  372. // parser does not allow for clean solution of this problem, hence the kludge
  373. // below. It will be gone as soon as the parser is rewritten.
  374. //
  375. // The kludge supports only self-closing tags inside attributes.
  376. //
  377. // KLUDGE WARNING!!
  378. static readonly Regex runatServer=new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/>",
  379. RegexOptions.Compiled | RegexOptions.Singleline |
  380. RegexOptions.Multiline | RegexOptions.IgnoreCase |
  381. RegexOptions.CultureInvariant);
  382. bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
  383. {
  384. if (attributes == null || attributes.Count == 0)
  385. return false;
  386. Match match;
  387. Group group;
  388. string value;
  389. bool retval = false;
  390. int index, length;
  391. StringBuilder sb = new StringBuilder ();
  392. sb.AppendFormat ("\t<{0}", tagid);
  393. foreach (string key in attributes.Keys) {
  394. value = attributes [key] as string;
  395. if (value == null || value.Length < 16) { // optimization
  396. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  397. continue;
  398. }
  399. match = runatServer.Match (attributes [key] as string);
  400. if (!match.Success) {
  401. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  402. continue;
  403. }
  404. if (sb.Length > 0) {
  405. TextParsed (location, sb.ToString ());
  406. sb.Length = 0;
  407. }
  408. retval = true;
  409. group = match.Groups [0];
  410. index = group.Index;
  411. length = group.Length;
  412. TextParsed (location, String.Format (" {0}=\"{1}", key, index > 0 ? value.Substring (0, index) : String.Empty));;
  413. FlushText ();
  414. ParseAttributeTag (group.Value);
  415. if (index + length < value.Length)
  416. TextParsed (location, value.Substring (index + length) + "\"");
  417. else
  418. TextParsed (location, "\"");
  419. }
  420. if (type == TagType.SelfClosing)
  421. sb.Append ("/>");
  422. else
  423. sb.Append (">");
  424. if (retval && sb.Length > 0)
  425. TextParsed (location, sb.ToString ());
  426. return retval;
  427. }
  428. void ParseAttributeTag (string code)
  429. {
  430. AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code));
  431. parser.Error += new ParseErrorHandler (ParseError);
  432. parser.TagParsed += new TagParsedHandler (TagParsed);
  433. parser.TextParsed += new TextParsedHandler (TextParsed);
  434. parser.Parse ();
  435. if (text.Length > 0)
  436. FlushText ();
  437. }
  438. #if NET_2_0
  439. void ParsingCompleted ()
  440. {
  441. PageParserFilter pfilter = PageParserFilter;
  442. if (pfilter == null)
  443. return;
  444. pfilter.ParseComplete (rootBuilder);
  445. }
  446. #endif
  447. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  448. {
  449. this.location = new Location (location);
  450. if (tparser != null)
  451. tparser.Location = location;
  452. if (text.Length != 0)
  453. FlushText (lastTag == TagType.CodeRender);
  454. if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
  455. bool in_script = (inScript || ignore_text);
  456. if (in_script) {
  457. if (ProcessScript (tagtype, attributes))
  458. return;
  459. } else
  460. if (ProcessScript (tagtype, attributes))
  461. return;
  462. }
  463. lastTag = tagtype;
  464. switch (tagtype) {
  465. case TagType.Directive:
  466. if (tagid.Length == 0)
  467. tagid = tparser.DefaultDirectiveName;
  468. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  469. break;
  470. case TagType.Tag:
  471. if (ProcessTag (location, tagid, attributes, tagtype)) {
  472. useOtherTags = true;
  473. break;
  474. }
  475. if (useOtherTags) {
  476. stack.Builder.EnsureOtherTags ();
  477. stack.Builder.OtherTags.Add (tagid);
  478. }
  479. {
  480. string plainText = location.PlainText;
  481. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
  482. TextParsed (location, plainText);
  483. }
  484. break;
  485. case TagType.Close:
  486. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  487. if (!notServer && CloseControl (tagid))
  488. break;
  489. TextParsed (location, location.PlainText);
  490. break;
  491. case TagType.SelfClosing:
  492. int count = stack.Count;
  493. if (!ProcessTag (location, tagid, attributes, tagtype)) {
  494. string plainText = location.PlainText;
  495. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
  496. TextParsed (location, plainText);
  497. } else if (stack.Count != count) {
  498. CloseControl (tagid);
  499. }
  500. break;
  501. case TagType.DataBinding:
  502. goto case TagType.CodeRender;
  503. case TagType.CodeRenderExpression:
  504. goto case TagType.CodeRender;
  505. case TagType.CodeRender:
  506. if (isApplication)
  507. throw new ParseException (location, "Invalid content for application file.");
  508. ProcessCode (tagtype, tagid, location);
  509. break;
  510. case TagType.Include:
  511. if (isApplication)
  512. throw new ParseException (location, "Invalid content for application file.");
  513. string file = attributes ["virtual"] as string;
  514. bool isvirtual = (file != null);
  515. if (!isvirtual)
  516. file = attributes ["file"] as string;
  517. if (isvirtual) {
  518. bool parsed = false;
  519. #if NET_2_0
  520. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  521. if (vpp.FileExists (file)) {
  522. VirtualFile vf = vpp.GetFile (file);
  523. if (vf != null) {
  524. Parse (vf.Open (), file, true);
  525. parsed = true;
  526. }
  527. }
  528. #endif
  529. if (!parsed)
  530. Parse (tparser.MapPath (file), true);
  531. } else {
  532. string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
  533. tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
  534. try {
  535. Parse (includeFilePath, true);
  536. } finally {
  537. tparser.PopIncludeDir ();
  538. }
  539. }
  540. break;
  541. default:
  542. break;
  543. }
  544. //PrintLocation (location);
  545. }
  546. static bool TryRemoveTag (string tagid, ArrayList otags)
  547. {
  548. if (otags == null || otags.Count == 0)
  549. return false;
  550. for (int idx = otags.Count - 1; idx >= 0; idx--) {
  551. string otagid = (string) otags [idx];
  552. if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
  553. do {
  554. otags.RemoveAt (idx);
  555. } while (otags.Count - 1 >= idx);
  556. return true;
  557. }
  558. }
  559. return false;
  560. }
  561. static string GetIncludeFilePath (string basedir, string filename)
  562. {
  563. if (Path.DirectorySeparatorChar == '/')
  564. filename = filename.Replace ("\\", "/");
  565. return Path.GetFullPath (Path.Combine (basedir, filename));
  566. }
  567. void TextParsed (ILocation location, string text)
  568. {
  569. if (ignore_text)
  570. return;
  571. if (text.IndexOf ("<%") != -1 && !inScript) {
  572. if (this.text.Length > 0)
  573. FlushText (true);
  574. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  575. r.AddChildren (this);
  576. return;
  577. }
  578. this.text.Append (text);
  579. //PrintLocation (location);
  580. }
  581. void FlushText ()
  582. {
  583. FlushText (false);
  584. }
  585. void FlushText (bool ignoreEmptyString)
  586. {
  587. string t = text.ToString ();
  588. text.Length = 0;
  589. if (ignoreEmptyString && t.Trim ().Length == 0)
  590. return;
  591. if (inScript) {
  592. #if NET_2_0
  593. PageParserFilter pfilter = PageParserFilter;
  594. if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
  595. return;
  596. #endif
  597. tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
  598. return;
  599. }
  600. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  601. throw new ParseException (location, "Content not valid for application file.");
  602. ControlBuilder current = stack.Builder;
  603. current.AppendLiteralString (t);
  604. if (current.NeedsTagInnerText ()) {
  605. tagInnerText.Append (t);
  606. }
  607. }
  608. #if NET_2_0
  609. bool BuilderHasOtherThan (Type type, ControlBuilder cb)
  610. {
  611. ArrayList al = cb.OtherTags;
  612. if (al != null && al.Count > 0)
  613. return true;
  614. al = cb.Children;
  615. if (al != null) {
  616. ControlBuilder tmp;
  617. foreach (object o in al) {
  618. if (o == null)
  619. continue;
  620. tmp = o as ControlBuilder;
  621. if (tmp == null) {
  622. string s = o as string;
  623. if (s != null && String.IsNullOrEmpty (s.Trim ()))
  624. continue;
  625. return true;
  626. }
  627. if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
  628. continue;
  629. if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
  630. return true;
  631. }
  632. }
  633. return false;
  634. }
  635. bool OtherControlsAllowed (ControlBuilder cb)
  636. {
  637. if (cb == null)
  638. return true;
  639. if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
  640. return true;
  641. if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), rootBuilder))
  642. return false;
  643. return true;
  644. }
  645. #endif
  646. public void AddControl (Type type, IDictionary attributes)
  647. {
  648. ControlBuilder parent = stack.Builder;
  649. ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
  650. attributes, location.BeginLine,
  651. location.Filename);
  652. if (builder != null)
  653. parent.AppendSubBuilder (builder);
  654. }
  655. bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype)
  656. {
  657. if (isApplication) {
  658. if (String.Compare (tagid, "object", true, CultureInfo.InvariantCulture) != 0)
  659. throw new ParseException (location, "Invalid tag for application file.");
  660. }
  661. ControlBuilder parent = stack.Builder;
  662. ControlBuilder builder = null;
  663. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  664. if (stack.Count > 1) {
  665. try {
  666. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  667. } catch (TypeLoadException e) {
  668. throw new ParseException (Location, "Type not found.", e);
  669. } catch (Exception e) {
  670. throw new ParseException (Location, e.Message, e);
  671. }
  672. }
  673. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  674. string id = htable ["id"] as string;
  675. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  676. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  677. try {
  678. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  679. } catch (TypeLoadException e) {
  680. throw new ParseException (Location, "Type not found.", e);
  681. } catch (Exception e) {
  682. throw new ParseException (Location, e.Message, e);
  683. }
  684. }
  685. if (builder == null)
  686. return false;
  687. #if NET_2_0
  688. PageParserFilter pfilter = PageParserFilter;
  689. if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
  690. throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
  691. if (!OtherControlsAllowed (builder))
  692. throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
  693. #endif
  694. builder.Location = location;
  695. builder.ID = htable ["id"] as string;
  696. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  697. if (inForm)
  698. throw new ParseException (location, "Only one <form> allowed.");
  699. inForm = true;
  700. }
  701. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  702. if (builder is TemplateBuilder) {
  703. // push the id list
  704. }
  705. stack.Push (builder, location);
  706. } else {
  707. if (!isApplication && builder is ObjectTagBuilder) {
  708. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  709. if (ot.Scope != null && ot.Scope != "")
  710. throw new ParseException (location, "Scope not allowed here");
  711. if (tagtype == TagType.Tag) {
  712. stack.Push (builder, location);
  713. return true;
  714. }
  715. }
  716. parent.AppendSubBuilder (builder);
  717. builder.CloseControl ();
  718. }
  719. return true;
  720. }
  721. string ReadFile (string filename)
  722. {
  723. string realpath = tparser.MapPath (filename);
  724. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  725. string content = sr.ReadToEnd ();
  726. return content;
  727. }
  728. }
  729. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  730. {
  731. if (tagtype != TagType.Close) {
  732. if (attributes != null && attributes.IsRunAtServer ()) {
  733. string language = (string) attributes ["language"];
  734. if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
  735. tparser.SetLanguage (language);
  736. CheckLanguage (language);
  737. string src = (string) attributes ["src"];
  738. if (src != null) {
  739. if (src == "")
  740. throw new ParseException (Parser,
  741. "src cannot be an empty string");
  742. string content = ReadFile (src);
  743. inScript = true;
  744. TextParsed (Parser, content);
  745. FlushText ();
  746. inScript = false;
  747. if (tagtype != TagType.SelfClosing) {
  748. ignore_text = true;
  749. Parser.VerbatimID = "script";
  750. }
  751. } else if (tagtype == TagType.Tag) {
  752. Parser.VerbatimID = "script";
  753. inScript = true;
  754. }
  755. return true;
  756. } else {
  757. if (tagtype != TagType.SelfClosing) {
  758. Parser.VerbatimID = "script";
  759. javascript = true;
  760. }
  761. TextParsed (location, location.PlainText);
  762. return true;
  763. }
  764. }
  765. bool result;
  766. if (inScript) {
  767. result = inScript;
  768. inScript = false;
  769. } else if (!ignore_text) {
  770. result = javascript;
  771. javascript = false;
  772. TextParsed (location, location.PlainText);
  773. } else {
  774. ignore_text = false;
  775. result = true;
  776. }
  777. return result;
  778. }
  779. bool CloseControl (string tagid)
  780. {
  781. ControlBuilder current = stack.Builder;
  782. string btag = current.OriginalTagName;
  783. if (String.Compare (btag, "tbody", true, CultureInfo.InvariantCulture) != 0 &&
  784. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0) {
  785. if (!current.ChildrenAsProperties) {
  786. try {
  787. TextParsed (location, location.PlainText);
  788. FlushText ();
  789. } catch {}
  790. }
  791. return true;
  792. }
  793. if (0 != String.Compare (tagid, btag, true, CultureInfo.InvariantCulture))
  794. return false;
  795. // if (current is TemplateBuilder)
  796. // pop from the id list
  797. if (current.NeedsTagInnerText ()) {
  798. try {
  799. current.SetTagInnerText (tagInnerText.ToString ());
  800. } catch (Exception e) {
  801. throw new ParseException (current.Location, e.Message, e);
  802. }
  803. tagInnerText.Length = 0;
  804. }
  805. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  806. inForm = false;
  807. }
  808. current.CloseControl ();
  809. stack.Pop ();
  810. stack.Builder.AppendSubBuilder (current);
  811. return true;
  812. }
  813. #if NET_2_0
  814. CodeConstructType MapTagTypeToConstructType (TagType tagtype)
  815. {
  816. switch (tagtype) {
  817. case TagType.DataBinding:
  818. return CodeConstructType.ExpressionSnippet;
  819. case TagType.CodeRender:
  820. return CodeConstructType.CodeSnippet;
  821. case TagType.CodeRenderExpression:
  822. return CodeConstructType.DataBindingSnippet;
  823. default:
  824. throw new InvalidOperationException ("Unexpected tag type.");
  825. }
  826. }
  827. #endif
  828. bool ProcessCode (TagType tagtype, string code, ILocation location)
  829. {
  830. #if NET_2_0
  831. PageParserFilter pfilter = PageParserFilter;
  832. if (pfilter != null && (!pfilter.AllowCode || !pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
  833. return true;
  834. #endif
  835. ControlBuilder b = null;
  836. if (tagtype == TagType.CodeRender)
  837. b = new CodeRenderBuilder (code, false, location);
  838. else if (tagtype == TagType.CodeRenderExpression)
  839. b = new CodeRenderBuilder (code, true, location);
  840. else if (tagtype == TagType.DataBinding)
  841. b = new DataBindingBuilder (code, location);
  842. else
  843. throw new HttpException ("Should never happen");
  844. stack.Builder.AppendSubBuilder (b);
  845. return true;
  846. }
  847. public ILocation Location {
  848. get { return location; }
  849. }
  850. void CheckLanguage (string lang)
  851. {
  852. if (lang == null || lang == "")
  853. return;
  854. if (String.Compare (lang, tparser.Language, true, CultureInfo.InvariantCulture) == 0)
  855. return;
  856. #if NET_2_0
  857. CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  858. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  859. #else
  860. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  861. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
  862. #endif
  863. throw new ParseException (Location,
  864. String.Format ("Trying to mix language '{0}' and '{1}'.",
  865. tparser.Language, lang));
  866. }
  867. // Used to get CodeRender tags in attribute values
  868. class CodeRenderParser
  869. {
  870. string str;
  871. ControlBuilder builder;
  872. AspGenerator generator;
  873. public CodeRenderParser (string str, ControlBuilder builder)
  874. {
  875. this.str = str;
  876. this.builder = builder;
  877. }
  878. public void AddChildren (AspGenerator generator)
  879. {
  880. this.generator = generator;
  881. int index = str.IndexOf ("<%");
  882. if (index > 0)
  883. DoParseExpressions (str);
  884. else
  885. DoParse (str);
  886. }
  887. void DoParseExpressions (string str)
  888. {
  889. int startIndex = 0, index = 0;
  890. Regex codeDirective = new Regex ("(<%(?!@)(?<code>.*?)%>)|(<[\\w:\\.]+.*?runat=[\"']?server[\"']?.*?/>)",
  891. RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  892. Match match;
  893. int strLen = str.Length;
  894. while (index > -1 && startIndex < strLen) {
  895. match = codeDirective.Match (str, index);
  896. if (match.Success) {
  897. string value = match.Value;
  898. index = match.Index;
  899. if (index > startIndex)
  900. TextParsed (null, str.Substring (startIndex, index - startIndex));
  901. DoParse (value);
  902. index += value.Length;
  903. startIndex = index;
  904. } else
  905. break;
  906. if (index < strLen)
  907. index = str.IndexOf ('<', index);
  908. else
  909. break;
  910. }
  911. if (startIndex < strLen)
  912. TextParsed (null, str.Substring (startIndex));
  913. }
  914. void DoParse (string str)
  915. {
  916. AspParser parser = new AspParser ("@@nested_tag@@", new StringReader (str));
  917. parser.Error += new ParseErrorHandler (ParseError);
  918. parser.TagParsed += new TagParsedHandler (TagParsed);
  919. parser.TextParsed += new TextParsedHandler (TextParsed);
  920. parser.Parse ();
  921. }
  922. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  923. {
  924. switch (tagtype) {
  925. case TagType.CodeRender:
  926. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  927. break;
  928. case TagType.CodeRenderExpression:
  929. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  930. break;
  931. case TagType.DataBinding:
  932. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  933. break;
  934. case TagType.Tag:
  935. case TagType.SelfClosing:
  936. case TagType.Close:
  937. if (generator != null)
  938. generator.TagParsed (location, tagtype, tagid, attributes);
  939. else
  940. goto default;
  941. break;
  942. default:
  943. builder.AppendLiteralString (location.PlainText);
  944. break;
  945. }
  946. }
  947. void TextParsed (ILocation location, string text)
  948. {
  949. builder.AppendLiteralString (text);
  950. }
  951. void ParseError (ILocation location, string message)
  952. {
  953. throw new ParseException (location, message);
  954. }
  955. }
  956. }
  957. }