AspGenerator.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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. #if NET_2_0
  154. const int READ_BUFFER_SIZE = 8192;
  155. internal static Regex DirectiveRegex = new Regex (@"<%\s*@(\s*(?<attrname>\w[\w:]*(?=\W))(\s*(?<equal>=)\s*""(?<attrval>[^""]*)""|\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  156. #endif
  157. ParserStack pstack;
  158. BuilderLocationStack stack;
  159. TemplateParser tparser;
  160. StringBuilder text;
  161. RootBuilder rootBuilder;
  162. bool inScript, javascript, ignore_text;
  163. ILocation location;
  164. bool isApplication;
  165. StringBuilder tagInnerText = new StringBuilder ();
  166. static Hashtable emptyHash = new Hashtable ();
  167. bool inForm;
  168. bool useOtherTags;
  169. TagType lastTag;
  170. #if NET_2_0
  171. AspComponentFoundry componentFoundry;
  172. Stream inputStream;
  173. public AspGenerator (TemplateParser tparser, AspComponentFoundry componentFoundry) : this (tparser)
  174. {
  175. this.componentFoundry = componentFoundry;
  176. }
  177. #endif
  178. public AspGenerator (TemplateParser tparser)
  179. {
  180. this.tparser = tparser;
  181. text = new StringBuilder ();
  182. stack = new BuilderLocationStack ();
  183. #if !NET_2_0
  184. rootBuilder = new RootBuilder (tparser);
  185. tparser.RootBuilder = rootBuilder;
  186. stack.Push (rootBuilder, null);
  187. #endif
  188. pstack = new ParserStack ();
  189. }
  190. public RootBuilder RootBuilder {
  191. get { return rootBuilder; }
  192. }
  193. public AspParser Parser {
  194. get { return pstack.Parser; }
  195. }
  196. public string Filename {
  197. get { return pstack.Filename; }
  198. }
  199. #if NET_2_0
  200. PageParserFilter PageParserFilter {
  201. get {
  202. if (tparser == null)
  203. return null;
  204. return tparser.PageParserFilter;
  205. }
  206. }
  207. // KLUDGE WARNING
  208. //
  209. // The kludge to determine the base type of the to-be-generated ASP.NET class is
  210. // very unfortunate but with our current parser it is, unfortunately, necessary. The
  211. // reason for reading the entire file into memory and parsing it with a regexp is
  212. // that we need to read the main directive (i.e. <%@Page %>, <%@Control %> etc),
  213. // pass it to the page parser filter if it exists, and finally read the inherits
  214. // attribute of the directive to get access to the base type of the class to be
  215. // generated. On that type we check whether it is decorated with the
  216. // FileLevelControlBuilder attribute and, if yes, use the indicated type as the
  217. // RootBuilder. This is necessary for the ASP.NET MVC views using the "generic"
  218. // inherits declaration to work properly. Our current parser is not able to parse
  219. // the input file out of sequence (i.e. directives first, then the rest) so we need
  220. // to do what we do below, alas.
  221. Hashtable GetDirectiveAttributesDictionary (string skipKeyName, CaptureCollection names, CaptureCollection values)
  222. {
  223. var ret = new Hashtable (StringComparer.InvariantCultureIgnoreCase);
  224. int index = 0;
  225. string keyName;
  226. foreach (Capture c in names) {
  227. keyName = c.Value;
  228. if (String.Compare (skipKeyName, keyName, StringComparison.OrdinalIgnoreCase) == 0) {
  229. index++;
  230. continue;
  231. }
  232. ret.Add (c.Value, values [index++].Value);
  233. }
  234. return ret;
  235. }
  236. string GetDirectiveName (CaptureCollection names)
  237. {
  238. string val;
  239. foreach (Capture c in names) {
  240. val = c.Value;
  241. if (Directive.IsDirective (val))
  242. return val;
  243. }
  244. return tparser.DefaultDirectiveName;
  245. }
  246. int GetLineNumberForIndex (string fileContents, int index)
  247. {
  248. int line = 1;
  249. char c;
  250. bool foundCR = false;
  251. for (int pos = 0; pos < index; pos++) {
  252. c = fileContents [pos];
  253. if (c == '\n' || foundCR) {
  254. line++;
  255. foundCR = false;
  256. }
  257. foundCR = (c == '\r');
  258. }
  259. return line;
  260. }
  261. int GetNumberOfLinesForRange (string fileContents, int index, int length)
  262. {
  263. int lines = 0;
  264. int stop = index + length;
  265. char c;
  266. bool foundCR = false;
  267. for (int pos = index; pos < stop; pos++) {
  268. c = fileContents [pos];
  269. if (c == '\n' || foundCR) {
  270. lines++;
  271. foundCR = false;
  272. }
  273. foundCR = (c == '\r');
  274. }
  275. return lines;
  276. }
  277. Type GetInheritedType (string fileContents, string filename)
  278. {
  279. MatchCollection matches = DirectiveRegex.Matches (fileContents);
  280. if (matches == null || matches.Count == 0)
  281. return null;
  282. string wantedDirectiveName = tparser.DefaultDirectiveName.ToLower ();
  283. string directiveName;
  284. GroupCollection groups;
  285. CaptureCollection ccNames;
  286. foreach (Match match in matches) {
  287. groups = match.Groups;
  288. if (groups.Count < 6)
  289. continue;
  290. ccNames = groups [3].Captures;
  291. directiveName = GetDirectiveName (ccNames);
  292. if (String.IsNullOrEmpty (directiveName))
  293. continue;
  294. if (String.Compare (directiveName.ToLower (), wantedDirectiveName, StringComparison.Ordinal) != 0)
  295. continue;
  296. var loc = new Location (null);
  297. int index = match.Index;
  298. loc.Filename = filename;
  299. loc.BeginLine = GetLineNumberForIndex (fileContents, index);
  300. loc.EndLine = loc.BeginLine + GetNumberOfLinesForRange (fileContents, index, match.Length);
  301. tparser.Location = loc;
  302. tparser.allowedMainDirectives = 2;
  303. tparser.AddDirective (wantedDirectiveName, GetDirectiveAttributesDictionary (wantedDirectiveName, ccNames, groups [5].Captures));
  304. return tparser.BaseType;
  305. }
  306. return null;
  307. }
  308. string ReadFileContents (Stream inputStream, string filename)
  309. {
  310. string ret = null;
  311. if (inputStream != null) {
  312. if (inputStream.CanSeek) {
  313. long curPos = inputStream.Position;
  314. inputStream.Seek (0, SeekOrigin.Begin);
  315. Encoding enc = WebEncoding.FileEncoding;
  316. StringBuilder sb = new StringBuilder ();
  317. byte[] buffer = new byte [READ_BUFFER_SIZE];
  318. int nbytes;
  319. while ((nbytes = inputStream.Read (buffer, 0, READ_BUFFER_SIZE)) > 0)
  320. sb.Append (enc.GetString (buffer, 0, nbytes));
  321. inputStream.Seek (curPos, SeekOrigin.Begin);
  322. ret = sb.ToString ();
  323. sb.Length = 0;
  324. sb.Capacity = 0;
  325. } else {
  326. FileStream fs = inputStream as FileStream;
  327. if (fs != null) {
  328. string fname = fs.Name;
  329. try {
  330. if (File.Exists (fname))
  331. ret = File.ReadAllText (fname);
  332. } catch {
  333. // ignore
  334. }
  335. }
  336. }
  337. }
  338. if (ret == null && !String.IsNullOrEmpty (filename) && String.Compare (filename, "@@inner_string@@", StringComparison.Ordinal) != 0) {
  339. try {
  340. if (File.Exists (filename))
  341. ret = File.ReadAllText (filename);
  342. } catch {
  343. // ignore
  344. }
  345. }
  346. return ret;
  347. }
  348. Type GetRootBuilderType (Stream inputStream, string filename)
  349. {
  350. Type ret = null;
  351. string fileContents;
  352. if (tparser != null)
  353. fileContents = ReadFileContents (inputStream, filename);
  354. else
  355. fileContents = null;
  356. if (!String.IsNullOrEmpty (fileContents)) {
  357. Type inheritedType = GetInheritedType (fileContents, filename);
  358. fileContents = null;
  359. if (inheritedType != null) {
  360. FileLevelControlBuilderAttribute attr;
  361. try {
  362. object[] attrs = inheritedType.GetCustomAttributes (typeof (FileLevelControlBuilderAttribute), true);
  363. if (attrs != null && attrs.Length > 0)
  364. attr = attrs [0] as FileLevelControlBuilderAttribute;
  365. else
  366. attr = null;
  367. } catch {
  368. attr = null;
  369. }
  370. ret = attr != null ? attr.BuilderType : null;
  371. }
  372. }
  373. if (ret == null) {
  374. if (tparser is PageParser)
  375. return typeof (FileLevelPageControlBuilder);
  376. else if (tparser is UserControlParser)
  377. return typeof (FileLevelUserControlBuilder);
  378. else
  379. return typeof (RootBuilder);
  380. } else
  381. return ret;
  382. }
  383. void CreateRootBuilder (Stream inputStream, string filename)
  384. {
  385. Type rootBuilderType = GetRootBuilderType (inputStream, filename);
  386. rootBuilder = Activator.CreateInstance (rootBuilderType) as RootBuilder;
  387. if (rootBuilder == null)
  388. throw new HttpException ("Cannot create an instance of file-level control builder.");
  389. rootBuilder.Init (tparser, null, null, null, null, null);
  390. if (componentFoundry != null)
  391. rootBuilder.Foundry = componentFoundry;
  392. stack.Push (rootBuilder, null);
  393. tparser.RootBuilder = rootBuilder;
  394. }
  395. #endif
  396. BaseCompiler GetCompilerFromType ()
  397. {
  398. Type type = tparser.GetType ();
  399. if (type == typeof (PageParser))
  400. return new PageCompiler ((PageParser) tparser);
  401. if (type == typeof (ApplicationFileParser))
  402. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  403. if (type == typeof (UserControlParser))
  404. return new UserControlCompiler ((UserControlParser) tparser);
  405. #if NET_2_0
  406. if (type == typeof(MasterPageParser))
  407. return new MasterPageCompiler ((MasterPageParser) tparser);
  408. #endif
  409. throw new Exception ("Got type: " + type);
  410. }
  411. void InitParser (TextReader reader, string filename)
  412. {
  413. AspParser parser = new AspParser (filename, reader);
  414. parser.Error += new ParseErrorHandler (ParseError);
  415. parser.TagParsed += new TagParsedHandler (TagParsed);
  416. parser.TextParsed += new TextParsedHandler (TextParsed);
  417. #if NET_2_0
  418. parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
  419. tparser.AspGenerator = this;
  420. CreateRootBuilder (inputStream, filename);
  421. #endif
  422. if (!pstack.Push (parser))
  423. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  424. if (filename != "@@inner_string@@") {
  425. string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
  426. if (VirtualPathUtility.IsAbsolute (arvp))
  427. arvp = VirtualPathUtility.ToAppRelative (arvp);
  428. tparser.AddDependency (arvp);
  429. }
  430. }
  431. #if NET_2_0
  432. void InitParser (string filename)
  433. {
  434. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  435. InitParser (reader, filename);
  436. }
  437. #endif
  438. public void Parse (string file)
  439. {
  440. #if ONLY_1_1
  441. Parse (file, true);
  442. #else
  443. Parse (file, false);
  444. #endif
  445. }
  446. public void Parse (TextReader reader, string filename, bool doInitParser)
  447. {
  448. try {
  449. isApplication = tparser.DefaultDirectiveName == "application";
  450. if (doInitParser)
  451. InitParser (reader, filename);
  452. pstack.Parser.Parse ();
  453. if (text.Length > 0)
  454. FlushText ();
  455. #if NET_2_0
  456. tparser.MD5Checksum = pstack.Parser.MD5Checksum;
  457. #endif
  458. pstack.Pop ();
  459. #if DEBUG
  460. PrintTree (RootBuilder, 0);
  461. #endif
  462. if (stack.Count > 1 && pstack.Count == 0)
  463. throw new ParseException (stack.Builder.Location,
  464. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  465. } finally {
  466. if (reader != null)
  467. reader.Close ();
  468. }
  469. }
  470. public void Parse (Stream stream, string filename, bool doInitParser)
  471. {
  472. #if NET_2_0
  473. inputStream = stream;
  474. #endif
  475. Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
  476. }
  477. public void Parse (string filename, bool doInitParser)
  478. {
  479. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  480. Parse (reader, filename, doInitParser);
  481. }
  482. public void Parse ()
  483. {
  484. #if NET_2_0
  485. string inputFile = tparser.InputFile;
  486. TextReader inputReader = tparser.Reader;
  487. try {
  488. if (String.IsNullOrEmpty (inputFile)) {
  489. StreamReader sr = inputReader as StreamReader;
  490. if (sr != null) {
  491. FileStream fr = sr.BaseStream as FileStream;
  492. if (fr != null)
  493. inputFile = fr.Name;
  494. }
  495. if (String.IsNullOrEmpty (inputFile))
  496. inputFile = "@@inner_string@@";
  497. }
  498. if (inputReader != null) {
  499. Parse (inputReader, inputFile, true);
  500. } else {
  501. if (String.IsNullOrEmpty (inputFile))
  502. throw new HttpException ("Parser input file is empty, cannot continue.");
  503. inputFile = Path.GetFullPath (inputFile);
  504. InitParser (inputFile);
  505. Parse (inputFile);
  506. }
  507. } finally {
  508. if (inputReader != null)
  509. inputReader.Close ();
  510. }
  511. #else
  512. Parse (Path.GetFullPath (tparser.InputFile));
  513. #endif
  514. }
  515. internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
  516. {
  517. if (type == null || inputFile == null || inputFile.Length == 0)
  518. return;
  519. if (dependencies != null && dependencies.Count > 0) {
  520. string [] deps = (string []) dependencies.ToArray (typeof (string));
  521. HttpContext ctx = HttpContext.Current;
  522. HttpRequest req = ctx != null ? ctx.Request : null;
  523. if (req == null)
  524. throw new HttpException ("No current context, cannot compile.");
  525. for (int i = 0; i < deps.Length; i++)
  526. deps [i] = req.MapPath (deps [i]);
  527. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
  528. } else
  529. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
  530. }
  531. public Type GetCompiledType ()
  532. {
  533. Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
  534. if (type != null) {
  535. return type;
  536. }
  537. Parse ();
  538. BaseCompiler compiler = GetCompilerFromType ();
  539. type = compiler.GetCompiledType ();
  540. AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
  541. return type;
  542. }
  543. #if DEBUG
  544. static void PrintTree (ControlBuilder builder, int indent)
  545. {
  546. if (builder == null)
  547. return;
  548. string i = new string ('\t', indent);
  549. Console.Write (i);
  550. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  551. builder, builder.ID, builder.ControlType, builder.ParentBuilder);
  552. if (builder.Children != null)
  553. foreach (object o in builder.Children) {
  554. if (o is ControlBuilder)
  555. PrintTree ((ControlBuilder) o, indent++);
  556. }
  557. }
  558. static void PrintLocation (ILocation loc)
  559. {
  560. Console.WriteLine ("\tFile name: " + loc.Filename);
  561. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  562. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  563. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  564. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  565. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  566. Console.WriteLine ();
  567. }
  568. #endif
  569. void ParseError (ILocation location, string message)
  570. {
  571. throw new ParseException (location, message);
  572. }
  573. // KLUDGE WARNING!!
  574. //
  575. // The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
  576. // around a limitation of the current asp.net parser which is unable to parse server
  577. // controls inside client tag attributes. Since the architecture of the current
  578. // parser does not allow for clean solution of this problem, hence the kludge
  579. // below. It will be gone as soon as the parser is rewritten.
  580. //
  581. // The kludge supports only self-closing tags inside attributes.
  582. //
  583. // KLUDGE WARNING!!
  584. static readonly Regex runatServer=new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/>",
  585. RegexOptions.Compiled | RegexOptions.Singleline |
  586. RegexOptions.Multiline | RegexOptions.IgnoreCase |
  587. RegexOptions.CultureInvariant);
  588. bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
  589. {
  590. if (attributes == null || attributes.Count == 0)
  591. return false;
  592. Match match;
  593. Group group;
  594. string value;
  595. bool retval = false;
  596. int index, length;
  597. StringBuilder sb = new StringBuilder ();
  598. sb.AppendFormat ("\t<{0}", tagid);
  599. foreach (string key in attributes.Keys) {
  600. value = attributes [key] as string;
  601. if (value == null || value.Length < 16) { // optimization
  602. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  603. continue;
  604. }
  605. match = runatServer.Match (attributes [key] as string);
  606. if (!match.Success) {
  607. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  608. continue;
  609. }
  610. if (sb.Length > 0) {
  611. TextParsed (location, sb.ToString ());
  612. sb.Length = 0;
  613. }
  614. retval = true;
  615. group = match.Groups [0];
  616. index = group.Index;
  617. length = group.Length;
  618. TextParsed (location, String.Format (" {0}=\"{1}", key, index > 0 ? value.Substring (0, index) : String.Empty));;
  619. FlushText ();
  620. ParseAttributeTag (group.Value);
  621. if (index + length < value.Length)
  622. TextParsed (location, value.Substring (index + length) + "\"");
  623. else
  624. TextParsed (location, "\"");
  625. }
  626. if (type == TagType.SelfClosing)
  627. sb.Append ("/>");
  628. else
  629. sb.Append (">");
  630. if (retval && sb.Length > 0)
  631. TextParsed (location, sb.ToString ());
  632. return retval;
  633. }
  634. void ParseAttributeTag (string code)
  635. {
  636. AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code));
  637. parser.Error += new ParseErrorHandler (ParseError);
  638. parser.TagParsed += new TagParsedHandler (TagParsed);
  639. parser.TextParsed += new TextParsedHandler (TextParsed);
  640. parser.Parse ();
  641. if (text.Length > 0)
  642. FlushText ();
  643. }
  644. #if NET_2_0
  645. void ParsingCompleted ()
  646. {
  647. PageParserFilter pfilter = PageParserFilter;
  648. if (pfilter == null)
  649. return;
  650. pfilter.ParseComplete (RootBuilder);
  651. }
  652. #endif
  653. void CheckIfIncludeFileIsSecure (string filePath)
  654. {
  655. if (filePath == null || filePath.Length == 0)
  656. return;
  657. // a bit slow, but fully portable
  658. string newdir = null;
  659. Exception exception = null;
  660. try {
  661. string origdir = Directory.GetCurrentDirectory ();
  662. Directory.SetCurrentDirectory (Path.GetDirectoryName (filePath));
  663. newdir = Directory.GetCurrentDirectory ();
  664. Directory.SetCurrentDirectory (origdir);
  665. if (newdir [newdir.Length - 1] != '/')
  666. newdir += "/";
  667. } catch (DirectoryNotFoundException ex) {
  668. return; // will be converted into 404
  669. } catch (FileNotFoundException ex) {
  670. return; // as above
  671. } catch (Exception ex) {
  672. // better safe than sorry
  673. exception = ex;
  674. }
  675. if (exception != null || !StrUtils.StartsWith (newdir, HttpRuntime.AppDomainAppPath))
  676. throw new ParseException (Location, "Files above the application's root directory cannot be included.");
  677. }
  678. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  679. {
  680. bool tagIgnored;
  681. this.location = new Location (location);
  682. if (tparser != null)
  683. tparser.Location = location;
  684. if (text.Length != 0)
  685. FlushText (lastTag == TagType.CodeRender);
  686. if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
  687. bool in_script = (inScript || ignore_text);
  688. if (in_script) {
  689. if (ProcessScript (tagtype, attributes))
  690. return;
  691. } else
  692. if (ProcessScript (tagtype, attributes))
  693. return;
  694. }
  695. lastTag = tagtype;
  696. switch (tagtype) {
  697. case TagType.Directive:
  698. if (tagid.Length == 0)
  699. tagid = tparser.DefaultDirectiveName;
  700. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  701. break;
  702. case TagType.Tag:
  703. if (ProcessTag (location, tagid, attributes, tagtype, out tagIgnored)) {
  704. if (!tagIgnored)
  705. useOtherTags = true;
  706. break;
  707. }
  708. if (useOtherTags) {
  709. stack.Builder.EnsureOtherTags ();
  710. stack.Builder.OtherTags.Add (tagid);
  711. }
  712. {
  713. string plainText = location.PlainText;
  714. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
  715. TextParsed (location, plainText);
  716. }
  717. break;
  718. case TagType.Close:
  719. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  720. if (!notServer && CloseControl (tagid))
  721. break;
  722. TextParsed (location, location.PlainText);
  723. break;
  724. case TagType.SelfClosing:
  725. int count = stack.Count;
  726. if (!ProcessTag (location, tagid, attributes, tagtype, out tagIgnored) && !tagIgnored) {
  727. string plainText = location.PlainText;
  728. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
  729. TextParsed (location, plainText);
  730. } else if (stack.Count != count) {
  731. CloseControl (tagid);
  732. }
  733. break;
  734. case TagType.DataBinding:
  735. goto case TagType.CodeRender;
  736. case TagType.CodeRenderExpression:
  737. goto case TagType.CodeRender;
  738. case TagType.CodeRender:
  739. if (isApplication)
  740. throw new ParseException (location, "Invalid content for application file.");
  741. ProcessCode (tagtype, tagid, location);
  742. break;
  743. case TagType.Include:
  744. if (isApplication)
  745. throw new ParseException (location, "Invalid content for application file.");
  746. string file = attributes ["virtual"] as string;
  747. bool isvirtual = (file != null);
  748. if (!isvirtual)
  749. file = attributes ["file"] as string;
  750. if (isvirtual) {
  751. bool parsed = false;
  752. #if NET_2_0
  753. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  754. if (vpp.FileExists (file)) {
  755. VirtualFile vf = vpp.GetFile (file);
  756. if (vf != null) {
  757. Parse (vf.Open (), file, true);
  758. parsed = true;
  759. }
  760. }
  761. #endif
  762. if (!parsed)
  763. Parse (tparser.MapPath (file), true);
  764. } else {
  765. string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
  766. CheckIfIncludeFileIsSecure (includeFilePath);
  767. tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
  768. try {
  769. Parse (includeFilePath, true);
  770. } finally {
  771. tparser.PopIncludeDir ();
  772. }
  773. }
  774. break;
  775. default:
  776. break;
  777. }
  778. //PrintLocation (location);
  779. }
  780. static bool TryRemoveTag (string tagid, ArrayList otags)
  781. {
  782. if (otags == null || otags.Count == 0)
  783. return false;
  784. for (int idx = otags.Count - 1; idx >= 0; idx--) {
  785. string otagid = (string) otags [idx];
  786. if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
  787. do {
  788. otags.RemoveAt (idx);
  789. } while (otags.Count - 1 >= idx);
  790. return true;
  791. }
  792. }
  793. return false;
  794. }
  795. static string GetIncludeFilePath (string basedir, string filename)
  796. {
  797. if (Path.DirectorySeparatorChar == '/')
  798. filename = filename.Replace ("\\", "/");
  799. return Path.GetFullPath (Path.Combine (basedir, filename));
  800. }
  801. void TextParsed (ILocation location, string text)
  802. {
  803. if (ignore_text)
  804. return;
  805. if (text.IndexOf ("<%") != -1 && !inScript) {
  806. if (this.text.Length > 0)
  807. FlushText (true);
  808. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  809. r.AddChildren (this);
  810. return;
  811. }
  812. this.text.Append (text);
  813. //PrintLocation (location);
  814. }
  815. void FlushText ()
  816. {
  817. FlushText (false);
  818. }
  819. void FlushText (bool ignoreEmptyString)
  820. {
  821. string t = text.ToString ();
  822. text.Length = 0;
  823. if (ignoreEmptyString && t.Trim ().Length == 0)
  824. return;
  825. if (inScript) {
  826. #if NET_2_0
  827. PageParserFilter pfilter = PageParserFilter;
  828. if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
  829. return;
  830. #endif
  831. tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
  832. return;
  833. }
  834. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  835. throw new ParseException (location, "Content not valid for application file.");
  836. ControlBuilder current = stack.Builder;
  837. current.AppendLiteralString (t);
  838. if (current.NeedsTagInnerText ()) {
  839. tagInnerText.Append (t);
  840. }
  841. }
  842. #if NET_2_0
  843. bool BuilderHasOtherThan (Type type, ControlBuilder cb)
  844. {
  845. ArrayList al = cb.OtherTags;
  846. if (al != null && al.Count > 0)
  847. return true;
  848. al = cb.Children;
  849. if (al != null) {
  850. ControlBuilder tmp;
  851. foreach (object o in al) {
  852. if (o == null)
  853. continue;
  854. tmp = o as ControlBuilder;
  855. if (tmp == null) {
  856. string s = o as string;
  857. if (s != null && String.IsNullOrEmpty (s.Trim ()))
  858. continue;
  859. return true;
  860. }
  861. if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
  862. continue;
  863. if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. bool OtherControlsAllowed (ControlBuilder cb)
  870. {
  871. if (cb == null)
  872. return true;
  873. if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
  874. return true;
  875. if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), RootBuilder))
  876. return false;
  877. return true;
  878. }
  879. #endif
  880. public void AddControl (Type type, IDictionary attributes)
  881. {
  882. ControlBuilder parent = stack.Builder;
  883. ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
  884. attributes, location.BeginLine,
  885. location.Filename);
  886. if (builder != null)
  887. parent.AppendSubBuilder (builder);
  888. }
  889. bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype, out bool ignored)
  890. {
  891. ignored = false;
  892. if (isApplication) {
  893. if (String.Compare (tagid, "object", true, CultureInfo.InvariantCulture) != 0)
  894. throw new ParseException (location, "Invalid tag for application file.");
  895. }
  896. ControlBuilder parent = stack.Builder;
  897. ControlBuilder builder = null;
  898. if (parent != null && parent.ControlType == typeof (HtmlTable) &&
  899. (String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0 ||
  900. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0)) {
  901. ignored = true;
  902. return true;
  903. }
  904. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  905. if (stack.Count > 1) {
  906. try {
  907. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  908. } catch (TypeLoadException e) {
  909. throw new ParseException (Location, "Type not found.", e);
  910. } catch (Exception e) {
  911. throw new ParseException (Location, e.Message, e);
  912. }
  913. }
  914. bool runatServer = atts != null && atts.IsRunAtServer ();
  915. if (builder == null && runatServer) {
  916. string id = htable ["id"] as string;
  917. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  918. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  919. try {
  920. builder = RootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  921. } catch (TypeLoadException e) {
  922. throw new ParseException (Location, "Type not found.", e);
  923. } catch (Exception e) {
  924. throw new ParseException (Location, e.Message, e);
  925. }
  926. }
  927. if (builder == null)
  928. return false;
  929. // This is as good as we can do for now - if the parsed location contains
  930. // both expressions and code render blocks then we're out of luck...
  931. string plainText = location.PlainText;
  932. if (!runatServer && plainText.IndexOf ("<%$") == -1&& plainText.IndexOf ("<%") > -1)
  933. return false;
  934. #if NET_2_0
  935. PageParserFilter pfilter = PageParserFilter;
  936. if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
  937. throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
  938. if (!OtherControlsAllowed (builder))
  939. throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
  940. #endif
  941. builder.Location = location;
  942. builder.ID = htable ["id"] as string;
  943. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  944. if (inForm)
  945. throw new ParseException (location, "Only one <form> allowed.");
  946. inForm = true;
  947. }
  948. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  949. if (builder is TemplateBuilder) {
  950. // push the id list
  951. }
  952. stack.Push (builder, location);
  953. } else {
  954. if (!isApplication && builder is ObjectTagBuilder) {
  955. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  956. if (ot.Scope != null && ot.Scope.Length > 0)
  957. throw new ParseException (location, "Scope not allowed here");
  958. if (tagtype == TagType.Tag) {
  959. stack.Push (builder, location);
  960. return true;
  961. }
  962. }
  963. parent.AppendSubBuilder (builder);
  964. builder.CloseControl ();
  965. }
  966. return true;
  967. }
  968. string ReadFile (string filename)
  969. {
  970. string realpath = tparser.MapPath (filename);
  971. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  972. string content = sr.ReadToEnd ();
  973. return content;
  974. }
  975. }
  976. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  977. {
  978. if (tagtype != TagType.Close) {
  979. if (attributes != null && attributes.IsRunAtServer ()) {
  980. string language = (string) attributes ["language"];
  981. if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
  982. tparser.SetLanguage (language);
  983. CheckLanguage (language);
  984. string src = (string) attributes ["src"];
  985. if (src != null) {
  986. if (src == "")
  987. throw new ParseException (Parser,
  988. "src cannot be an empty string");
  989. string content = ReadFile (src);
  990. inScript = true;
  991. TextParsed (Parser, content);
  992. FlushText ();
  993. inScript = false;
  994. if (tagtype != TagType.SelfClosing) {
  995. ignore_text = true;
  996. Parser.VerbatimID = "script";
  997. }
  998. } else if (tagtype == TagType.Tag) {
  999. Parser.VerbatimID = "script";
  1000. inScript = true;
  1001. }
  1002. return true;
  1003. } else {
  1004. if (tagtype != TagType.SelfClosing) {
  1005. Parser.VerbatimID = "script";
  1006. javascript = true;
  1007. }
  1008. TextParsed (location, location.PlainText);
  1009. return true;
  1010. }
  1011. }
  1012. bool result;
  1013. if (inScript) {
  1014. result = inScript;
  1015. inScript = false;
  1016. } else if (!ignore_text) {
  1017. result = javascript;
  1018. javascript = false;
  1019. TextParsed (location, location.PlainText);
  1020. } else {
  1021. ignore_text = false;
  1022. result = true;
  1023. }
  1024. return result;
  1025. }
  1026. bool CloseControl (string tagid)
  1027. {
  1028. ControlBuilder current = stack.Builder;
  1029. string btag = current.OriginalTagName;
  1030. if (String.Compare (btag, "tbody", true, CultureInfo.InvariantCulture) != 0 &&
  1031. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0) {
  1032. if (!current.ChildrenAsProperties) {
  1033. try {
  1034. TextParsed (location, location.PlainText);
  1035. FlushText ();
  1036. } catch {}
  1037. }
  1038. return true;
  1039. }
  1040. if (current.ControlType == typeof (HtmlTable) && String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0)
  1041. return true;
  1042. if (0 != String.Compare (tagid, btag, true, CultureInfo.InvariantCulture))
  1043. return false;
  1044. // if (current is TemplateBuilder)
  1045. // pop from the id list
  1046. if (current.NeedsTagInnerText ()) {
  1047. try {
  1048. current.SetTagInnerText (tagInnerText.ToString ());
  1049. } catch (Exception e) {
  1050. throw new ParseException (current.Location, e.Message, e);
  1051. }
  1052. tagInnerText.Length = 0;
  1053. }
  1054. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  1055. inForm = false;
  1056. }
  1057. current.CloseControl ();
  1058. stack.Pop ();
  1059. stack.Builder.AppendSubBuilder (current);
  1060. return true;
  1061. }
  1062. #if NET_2_0
  1063. CodeConstructType MapTagTypeToConstructType (TagType tagtype)
  1064. {
  1065. switch (tagtype) {
  1066. case TagType.DataBinding:
  1067. return CodeConstructType.ExpressionSnippet;
  1068. case TagType.CodeRender:
  1069. return CodeConstructType.CodeSnippet;
  1070. case TagType.CodeRenderExpression:
  1071. return CodeConstructType.DataBindingSnippet;
  1072. default:
  1073. throw new InvalidOperationException ("Unexpected tag type.");
  1074. }
  1075. }
  1076. #endif
  1077. bool ProcessCode (TagType tagtype, string code, ILocation location)
  1078. {
  1079. #if NET_2_0
  1080. PageParserFilter pfilter = PageParserFilter;
  1081. // LAMESPEC:
  1082. //
  1083. // http://msdn.microsoft.com/en-us/library/system.web.ui.pageparserfilter.processcodeconstruct.aspx
  1084. //
  1085. // The above page says if false is returned then we should NOT process the
  1086. // code further, wheras in reality it's the other way around. The
  1087. // ProcessCodeConstruct return value means whether or not the filter
  1088. // _processed_ the code.
  1089. //
  1090. if (pfilter != null && (!pfilter.AllowCode || pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
  1091. return true;
  1092. #endif
  1093. ControlBuilder b = null;
  1094. if (tagtype == TagType.CodeRender)
  1095. b = new CodeRenderBuilder (code, false, location);
  1096. else if (tagtype == TagType.CodeRenderExpression)
  1097. b = new CodeRenderBuilder (code, true, location);
  1098. else if (tagtype == TagType.DataBinding)
  1099. b = new DataBindingBuilder (code, location);
  1100. else
  1101. throw new HttpException ("Should never happen");
  1102. stack.Builder.AppendSubBuilder (b);
  1103. return true;
  1104. }
  1105. public ILocation Location {
  1106. get { return location; }
  1107. }
  1108. void CheckLanguage (string lang)
  1109. {
  1110. if (lang == null || lang == "")
  1111. return;
  1112. if (String.Compare (lang, tparser.Language, true, CultureInfo.InvariantCulture) == 0)
  1113. return;
  1114. #if NET_2_0
  1115. CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  1116. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  1117. #else
  1118. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  1119. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
  1120. #endif
  1121. throw new ParseException (Location,
  1122. String.Format ("Trying to mix language '{0}' and '{1}'.",
  1123. tparser.Language, lang));
  1124. }
  1125. // Used to get CodeRender tags in attribute values
  1126. class CodeRenderParser
  1127. {
  1128. string str;
  1129. ControlBuilder builder;
  1130. AspGenerator generator;
  1131. public CodeRenderParser (string str, ControlBuilder builder)
  1132. {
  1133. this.str = str;
  1134. this.builder = builder;
  1135. }
  1136. public void AddChildren (AspGenerator generator)
  1137. {
  1138. this.generator = generator;
  1139. int index = str.IndexOf ("<%");
  1140. if (index > 0)
  1141. DoParseExpressions (str);
  1142. else
  1143. DoParse (str);
  1144. }
  1145. void DoParseExpressions (string str)
  1146. {
  1147. int startIndex = 0, index = 0;
  1148. Regex codeDirective = new Regex ("(<%(?!@)(?<code>.*?)%>)|(<[\\w:\\.]+.*?runat=[\"']?server[\"']?.*?/>)",
  1149. RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  1150. Match match;
  1151. int strLen = str.Length;
  1152. while (index > -1 && startIndex < strLen) {
  1153. match = codeDirective.Match (str, index);
  1154. if (match.Success) {
  1155. string value = match.Value;
  1156. index = match.Index;
  1157. if (index > startIndex)
  1158. TextParsed (null, str.Substring (startIndex, index - startIndex));
  1159. DoParse (value);
  1160. index += value.Length;
  1161. startIndex = index;
  1162. } else
  1163. break;
  1164. if (index < strLen)
  1165. index = str.IndexOf ('<', index);
  1166. else
  1167. break;
  1168. }
  1169. if (startIndex < strLen)
  1170. TextParsed (null, str.Substring (startIndex));
  1171. }
  1172. void DoParse (string str)
  1173. {
  1174. AspParser parser = new AspParser ("@@nested_tag@@", new StringReader (str));
  1175. parser.Error += new ParseErrorHandler (ParseError);
  1176. parser.TagParsed += new TagParsedHandler (TagParsed);
  1177. parser.TextParsed += new TextParsedHandler (TextParsed);
  1178. parser.Parse ();
  1179. }
  1180. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  1181. {
  1182. switch (tagtype) {
  1183. case TagType.CodeRender:
  1184. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  1185. break;
  1186. case TagType.CodeRenderExpression:
  1187. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  1188. break;
  1189. case TagType.DataBinding:
  1190. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  1191. break;
  1192. case TagType.Tag:
  1193. case TagType.SelfClosing:
  1194. case TagType.Close:
  1195. if (generator != null)
  1196. generator.TagParsed (location, tagtype, tagid, attributes);
  1197. else
  1198. goto default;
  1199. break;
  1200. default:
  1201. string text = location.PlainText;
  1202. if (text != null && text.Trim ().Length > 0)
  1203. builder.AppendLiteralString (text);
  1204. break;
  1205. }
  1206. }
  1207. void TextParsed (ILocation location, string text)
  1208. {
  1209. builder.AppendLiteralString (text);
  1210. }
  1211. void ParseError (ILocation location, string message)
  1212. {
  1213. throw new ParseException (location, message);
  1214. }
  1215. }
  1216. }
  1217. }