AspGenerator.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. //
  2. // System.Web.Compilation.AspGenerator
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. // Marek Habersack <[email protected]>
  7. //
  8. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  9. // Copyright (c) 2004-2009 Novell, Inc (http://www.novell.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.CodeDom.Compiler;
  34. using System.Globalization;
  35. using System.IO;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. using System.Web.Caching;
  39. using System.Web.Configuration;
  40. using System.Web.Hosting;
  41. using System.Web.UI;
  42. using System.Web.UI.HtmlControls;
  43. using System.Web.Util;
  44. #if NET_2_0
  45. using System.Collections.Generic;
  46. #endif
  47. namespace System.Web.Compilation
  48. {
  49. class BuilderLocation
  50. {
  51. public ControlBuilder Builder;
  52. public ILocation Location;
  53. public BuilderLocation (ControlBuilder builder, ILocation location)
  54. {
  55. this.Builder = builder;
  56. this.Location = new Location (location);
  57. }
  58. }
  59. class BuilderLocationStack : Stack
  60. {
  61. public override void Push (object o)
  62. {
  63. if (!(o is BuilderLocation))
  64. throw new InvalidOperationException ();
  65. base.Push (o);
  66. }
  67. public virtual void Push (ControlBuilder builder, ILocation location)
  68. {
  69. BuilderLocation bl = new BuilderLocation (builder, location);
  70. Push (bl);
  71. }
  72. public new BuilderLocation Peek ()
  73. {
  74. return (BuilderLocation) base.Peek ();
  75. }
  76. public new BuilderLocation Pop ()
  77. {
  78. return (BuilderLocation) base.Pop ();
  79. }
  80. public ControlBuilder Builder {
  81. get { return Peek ().Builder; }
  82. }
  83. }
  84. class ParserStack
  85. {
  86. Hashtable files;
  87. Stack parsers;
  88. AspParser current;
  89. public ParserStack ()
  90. {
  91. files = new Hashtable (); // may be this should be case sensitive for windows
  92. parsers = new Stack ();
  93. }
  94. public bool Push (AspParser parser)
  95. {
  96. if (files.Contains (parser.Filename))
  97. return false;
  98. files [parser.Filename] = true;
  99. parsers.Push (parser);
  100. current = parser;
  101. return true;
  102. }
  103. public AspParser Pop ()
  104. {
  105. if (parsers.Count == 0)
  106. return null;
  107. files.Remove (current.Filename);
  108. AspParser result = (AspParser) parsers.Pop ();
  109. if (parsers.Count > 0)
  110. current = (AspParser) parsers.Peek ();
  111. else
  112. current = null;
  113. return result;
  114. }
  115. public int Count {
  116. get { return parsers.Count; }
  117. }
  118. public AspParser Parser {
  119. get { return current; }
  120. }
  121. public string Filename {
  122. get { return current.Filename; }
  123. }
  124. }
  125. class TagStack
  126. {
  127. Stack tags;
  128. public TagStack ()
  129. {
  130. tags = new Stack ();
  131. }
  132. public void Push (string tagid)
  133. {
  134. tags.Push (tagid);
  135. }
  136. public string Pop ()
  137. {
  138. if (tags.Count == 0)
  139. return null;
  140. return (string) tags.Pop ();
  141. }
  142. public bool CompareTo (string tagid)
  143. {
  144. if (tags.Count == 0)
  145. return false;
  146. return 0 == String.Compare (tagid, (string) tags.Peek (), true, CultureInfo.InvariantCulture);
  147. }
  148. public int Count {
  149. get { return tags.Count; }
  150. }
  151. public string Current {
  152. get { return (string) tags.Peek (); }
  153. }
  154. }
  155. enum TextBlockType
  156. {
  157. Verbatim,
  158. Expression,
  159. Tag,
  160. Comment
  161. }
  162. sealed class TextBlock
  163. {
  164. public string Content;
  165. public readonly TextBlockType Type;
  166. public readonly int Length;
  167. public TextBlock (TextBlockType type, string content)
  168. {
  169. Content = content;
  170. Type = type;
  171. Length = content.Length;
  172. }
  173. public override string ToString ()
  174. {
  175. return this.GetType ().FullName + " [" + this.Type + "]";
  176. }
  177. }
  178. class AspGenerator
  179. {
  180. #if NET_2_0
  181. const int READ_BUFFER_SIZE = 8192;
  182. 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);
  183. #endif
  184. static readonly Regex runatServer = new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/?>",
  185. RegexOptions.Compiled | RegexOptions.Singleline |
  186. RegexOptions.Multiline | RegexOptions.IgnoreCase |
  187. RegexOptions.CultureInvariant);
  188. static readonly Regex endOfTag = new Regex (@"</[\w:\.]+\s*?>",
  189. RegexOptions.Compiled | RegexOptions.Singleline |
  190. RegexOptions.Multiline | RegexOptions.IgnoreCase |
  191. RegexOptions.CultureInvariant);
  192. static readonly Regex expressionRegex = new Regex (@"<%.*?%>",
  193. RegexOptions.Compiled | RegexOptions.Singleline |
  194. RegexOptions.Multiline | RegexOptions.IgnoreCase |
  195. RegexOptions.CultureInvariant);
  196. static readonly Regex clientCommentRegex = new Regex (@"<!--(.|\s)*?-->",
  197. RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase |
  198. RegexOptions.CultureInvariant);
  199. ParserStack pstack;
  200. BuilderLocationStack stack;
  201. TemplateParser tparser;
  202. StringBuilder text;
  203. RootBuilder rootBuilder;
  204. bool inScript, javascript, ignore_text;
  205. ILocation location;
  206. bool isApplication;
  207. StringBuilder tagInnerText = new StringBuilder ();
  208. static Hashtable emptyHash = new Hashtable ();
  209. bool inForm;
  210. bool useOtherTags;
  211. TagType lastTag;
  212. #if NET_2_0
  213. AspComponentFoundry componentFoundry;
  214. Stream inputStream;
  215. public AspGenerator (TemplateParser tparser, AspComponentFoundry componentFoundry) : this (tparser)
  216. {
  217. this.componentFoundry = componentFoundry;
  218. }
  219. #endif
  220. public AspGenerator (TemplateParser tparser)
  221. {
  222. this.tparser = tparser;
  223. text = new StringBuilder ();
  224. stack = new BuilderLocationStack ();
  225. #if !NET_2_0
  226. rootBuilder = new RootBuilder (tparser);
  227. tparser.RootBuilder = rootBuilder;
  228. stack.Push (rootBuilder, null);
  229. #endif
  230. pstack = new ParserStack ();
  231. }
  232. public RootBuilder RootBuilder {
  233. get { return rootBuilder; }
  234. }
  235. public AspParser Parser {
  236. get { return pstack.Parser; }
  237. }
  238. public string Filename {
  239. get { return pstack.Filename; }
  240. }
  241. #if NET_2_0
  242. PageParserFilter PageParserFilter {
  243. get {
  244. if (tparser == null)
  245. return null;
  246. return tparser.PageParserFilter;
  247. }
  248. }
  249. // KLUDGE WARNING
  250. //
  251. // The kludge to determine the base type of the to-be-generated ASP.NET class is
  252. // very unfortunate but with our current parser it is, unfortunately, necessary. The
  253. // reason for reading the entire file into memory and parsing it with a regexp is
  254. // that we need to read the main directive (i.e. <%@Page %>, <%@Control %> etc),
  255. // pass it to the page parser filter if it exists, and finally read the inherits
  256. // attribute of the directive to get access to the base type of the class to be
  257. // generated. On that type we check whether it is decorated with the
  258. // FileLevelControlBuilder attribute and, if yes, use the indicated type as the
  259. // RootBuilder. This is necessary for the ASP.NET MVC views using the "generic"
  260. // inherits declaration to work properly. Our current parser is not able to parse
  261. // the input file out of sequence (i.e. directives first, then the rest) so we need
  262. // to do what we do below, alas.
  263. Hashtable GetDirectiveAttributesDictionary (string skipKeyName, CaptureCollection names, CaptureCollection values)
  264. {
  265. var ret = new Hashtable (StringComparer.InvariantCultureIgnoreCase);
  266. int index = 0;
  267. string keyName;
  268. foreach (Capture c in names) {
  269. keyName = c.Value;
  270. if (String.Compare (skipKeyName, keyName, StringComparison.OrdinalIgnoreCase) == 0) {
  271. index++;
  272. continue;
  273. }
  274. ret.Add (c.Value, values [index++].Value);
  275. }
  276. return ret;
  277. }
  278. string GetDirectiveName (CaptureCollection names)
  279. {
  280. string val;
  281. foreach (Capture c in names) {
  282. val = c.Value;
  283. if (Directive.IsDirective (val))
  284. return val;
  285. }
  286. return tparser.DefaultDirectiveName;
  287. }
  288. int GetLineNumberForIndex (string fileContents, int index)
  289. {
  290. int line = 1;
  291. char c;
  292. bool foundCR = false;
  293. for (int pos = 0; pos < index; pos++) {
  294. c = fileContents [pos];
  295. if (c == '\n' || foundCR) {
  296. line++;
  297. foundCR = false;
  298. }
  299. foundCR = (c == '\r');
  300. }
  301. return line;
  302. }
  303. int GetNumberOfLinesForRange (string fileContents, int index, int length)
  304. {
  305. int lines = 0;
  306. int stop = index + length;
  307. char c;
  308. bool foundCR = false;
  309. for (int pos = index; pos < stop; pos++) {
  310. c = fileContents [pos];
  311. if (c == '\n' || foundCR) {
  312. lines++;
  313. foundCR = false;
  314. }
  315. foundCR = (c == '\r');
  316. }
  317. return lines;
  318. }
  319. Type GetInheritedType (string fileContents, string filename)
  320. {
  321. MatchCollection matches = DirectiveRegex.Matches (fileContents);
  322. if (matches == null || matches.Count == 0)
  323. return null;
  324. string wantedDirectiveName = tparser.DefaultDirectiveName.ToLower ();
  325. string directiveName;
  326. GroupCollection groups;
  327. CaptureCollection ccNames;
  328. foreach (Match match in matches) {
  329. groups = match.Groups;
  330. if (groups.Count < 6)
  331. continue;
  332. ccNames = groups [3].Captures;
  333. directiveName = GetDirectiveName (ccNames);
  334. if (String.IsNullOrEmpty (directiveName))
  335. continue;
  336. if (String.Compare (directiveName.ToLower (), wantedDirectiveName, StringComparison.Ordinal) != 0)
  337. continue;
  338. var loc = new Location (null);
  339. int index = match.Index;
  340. loc.Filename = filename;
  341. loc.BeginLine = GetLineNumberForIndex (fileContents, index);
  342. loc.EndLine = loc.BeginLine + GetNumberOfLinesForRange (fileContents, index, match.Length);
  343. tparser.Location = loc;
  344. tparser.allowedMainDirectives = 2;
  345. tparser.AddDirective (wantedDirectiveName, GetDirectiveAttributesDictionary (wantedDirectiveName, ccNames, groups [5].Captures));
  346. return tparser.BaseType;
  347. }
  348. return null;
  349. }
  350. string ReadFileContents (Stream inputStream, string filename)
  351. {
  352. string ret = null;
  353. if (inputStream != null) {
  354. if (inputStream.CanSeek) {
  355. long curPos = inputStream.Position;
  356. inputStream.Seek (0, SeekOrigin.Begin);
  357. Encoding enc = WebEncoding.FileEncoding;
  358. StringBuilder sb = new StringBuilder ();
  359. byte[] buffer = new byte [READ_BUFFER_SIZE];
  360. int nbytes;
  361. while ((nbytes = inputStream.Read (buffer, 0, READ_BUFFER_SIZE)) > 0)
  362. sb.Append (enc.GetString (buffer, 0, nbytes));
  363. inputStream.Seek (curPos, SeekOrigin.Begin);
  364. ret = sb.ToString ();
  365. sb.Length = 0;
  366. sb.Capacity = 0;
  367. } else {
  368. FileStream fs = inputStream as FileStream;
  369. if (fs != null) {
  370. string fname = fs.Name;
  371. try {
  372. if (File.Exists (fname))
  373. ret = File.ReadAllText (fname);
  374. } catch {
  375. // ignore
  376. }
  377. }
  378. }
  379. }
  380. if (ret == null && !String.IsNullOrEmpty (filename) && String.Compare (filename, "@@inner_string@@", StringComparison.Ordinal) != 0) {
  381. try {
  382. if (File.Exists (filename))
  383. ret = File.ReadAllText (filename);
  384. } catch {
  385. // ignore
  386. }
  387. }
  388. return ret;
  389. }
  390. Type GetRootBuilderType (Stream inputStream, string filename)
  391. {
  392. Type ret = null;
  393. string fileContents;
  394. if (tparser != null)
  395. fileContents = ReadFileContents (inputStream, filename);
  396. else
  397. fileContents = null;
  398. if (!String.IsNullOrEmpty (fileContents)) {
  399. Type inheritedType = GetInheritedType (fileContents, filename);
  400. fileContents = null;
  401. if (inheritedType != null) {
  402. FileLevelControlBuilderAttribute attr;
  403. try {
  404. object[] attrs = inheritedType.GetCustomAttributes (typeof (FileLevelControlBuilderAttribute), true);
  405. if (attrs != null && attrs.Length > 0)
  406. attr = attrs [0] as FileLevelControlBuilderAttribute;
  407. else
  408. attr = null;
  409. } catch {
  410. attr = null;
  411. }
  412. ret = attr != null ? attr.BuilderType : null;
  413. }
  414. }
  415. if (ret == null) {
  416. if (tparser is PageParser)
  417. return typeof (FileLevelPageControlBuilder);
  418. else if (tparser is UserControlParser)
  419. return typeof (FileLevelUserControlBuilder);
  420. else
  421. return typeof (RootBuilder);
  422. } else
  423. return ret;
  424. }
  425. void CreateRootBuilder (Stream inputStream, string filename)
  426. {
  427. if (rootBuilder != null)
  428. return;
  429. Type rootBuilderType = GetRootBuilderType (inputStream, filename);
  430. rootBuilder = Activator.CreateInstance (rootBuilderType) as RootBuilder;
  431. if (rootBuilder == null)
  432. throw new HttpException ("Cannot create an instance of file-level control builder.");
  433. rootBuilder.Init (tparser, null, null, null, null, null);
  434. if (componentFoundry != null)
  435. rootBuilder.Foundry = componentFoundry;
  436. stack.Push (rootBuilder, null);
  437. tparser.RootBuilder = rootBuilder;
  438. }
  439. #endif
  440. BaseCompiler GetCompilerFromType ()
  441. {
  442. Type type = tparser.GetType ();
  443. if (type == typeof (PageParser))
  444. return new PageCompiler ((PageParser) tparser);
  445. if (type == typeof (ApplicationFileParser))
  446. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  447. if (type == typeof (UserControlParser))
  448. return new UserControlCompiler ((UserControlParser) tparser);
  449. #if NET_2_0
  450. if (type == typeof(MasterPageParser))
  451. return new MasterPageCompiler ((MasterPageParser) tparser);
  452. #endif
  453. throw new Exception ("Got type: " + type);
  454. }
  455. void InitParser (TextReader reader, string filename)
  456. {
  457. AspParser parser = new AspParser (filename, reader);
  458. parser.Error += new ParseErrorHandler (ParseError);
  459. parser.TagParsed += new TagParsedHandler (TagParsed);
  460. parser.TextParsed += new TextParsedHandler (TextParsed);
  461. #if NET_2_0
  462. parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
  463. tparser.AspGenerator = this;
  464. CreateRootBuilder (inputStream, filename);
  465. #endif
  466. if (!pstack.Push (parser))
  467. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  468. if (filename != "@@inner_string@@") {
  469. string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
  470. if (VirtualPathUtility.IsAbsolute (arvp))
  471. arvp = VirtualPathUtility.ToAppRelative (arvp);
  472. tparser.AddDependency (arvp);
  473. }
  474. }
  475. #if NET_2_0
  476. void InitParser (string filename)
  477. {
  478. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  479. InitParser (reader, filename);
  480. }
  481. #endif
  482. void CheckForDuplicateIds (ControlBuilder root, Stack scopes)
  483. {
  484. if (root == null)
  485. return;
  486. if (scopes == null)
  487. scopes = new Stack ();
  488. #if NET_2_0
  489. Dictionary <string, bool> ids;
  490. #else
  491. Hashtable ids;
  492. #endif
  493. if (scopes.Count == 0 || root.IsNamingContainer) {
  494. #if NET_2_0
  495. ids = new Dictionary <string, bool> (StringComparer.Ordinal);
  496. #else
  497. ids = new Hashtable ();
  498. #endif
  499. scopes.Push (ids);
  500. } else {
  501. #if NET_2_0
  502. ids = scopes.Peek () as Dictionary <string, bool>;
  503. #else
  504. ids = scopes.Peek () as Hashtable;
  505. #endif
  506. }
  507. if (ids == null)
  508. return;
  509. ControlBuilder cb;
  510. string id;
  511. ArrayList children = root.Children;
  512. if (children != null) {
  513. foreach (object o in children) {
  514. cb = o as ControlBuilder;
  515. if (cb == null)
  516. continue;
  517. id = cb.ID;
  518. if (id == null || id.Length == 0)
  519. continue;
  520. if (ids.ContainsKey (id))
  521. throw new ParseException (cb.Location, "Id '" + id + "' is already used by another control.");
  522. ids.Add (id, true);
  523. CheckForDuplicateIds (cb, scopes);
  524. }
  525. }
  526. }
  527. public void Parse (string file)
  528. {
  529. #if ONLY_1_1
  530. Parse (file, true);
  531. #else
  532. Parse (file, false);
  533. #endif
  534. }
  535. public void Parse (TextReader reader, string filename, bool doInitParser)
  536. {
  537. try {
  538. isApplication = tparser.DefaultDirectiveName == "application";
  539. if (doInitParser)
  540. InitParser (reader, filename);
  541. pstack.Parser.Parse ();
  542. if (text.Length > 0)
  543. FlushText ();
  544. #if NET_2_0
  545. tparser.MD5Checksum = pstack.Parser.MD5Checksum;
  546. #endif
  547. pstack.Pop ();
  548. #if DEBUG
  549. PrintTree (RootBuilder, 0);
  550. #endif
  551. if (stack.Count > 1 && pstack.Count == 0)
  552. throw new ParseException (stack.Builder.Location,
  553. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  554. CheckForDuplicateIds (RootBuilder, null);
  555. } finally {
  556. if (reader != null)
  557. reader.Close ();
  558. }
  559. }
  560. public void Parse (Stream stream, string filename, bool doInitParser)
  561. {
  562. #if NET_2_0
  563. inputStream = stream;
  564. #endif
  565. Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
  566. }
  567. public void Parse (string filename, bool doInitParser)
  568. {
  569. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  570. Parse (reader, filename, doInitParser);
  571. }
  572. public void Parse ()
  573. {
  574. #if NET_2_0
  575. string inputFile = tparser.InputFile;
  576. TextReader inputReader = tparser.Reader;
  577. try {
  578. if (String.IsNullOrEmpty (inputFile)) {
  579. StreamReader sr = inputReader as StreamReader;
  580. if (sr != null) {
  581. FileStream fr = sr.BaseStream as FileStream;
  582. if (fr != null)
  583. inputFile = fr.Name;
  584. }
  585. if (String.IsNullOrEmpty (inputFile))
  586. inputFile = "@@inner_string@@";
  587. }
  588. if (inputReader != null) {
  589. Parse (inputReader, inputFile, true);
  590. } else {
  591. if (String.IsNullOrEmpty (inputFile))
  592. throw new HttpException ("Parser input file is empty, cannot continue.");
  593. inputFile = Path.GetFullPath (inputFile);
  594. InitParser (inputFile);
  595. Parse (inputFile);
  596. }
  597. } finally {
  598. if (inputReader != null)
  599. inputReader.Close ();
  600. }
  601. #else
  602. Parse (Path.GetFullPath (tparser.InputFile));
  603. #endif
  604. }
  605. internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
  606. {
  607. if (type == null || inputFile == null || inputFile.Length == 0)
  608. return;
  609. if (dependencies != null && dependencies.Count > 0) {
  610. string [] deps = (string []) dependencies.ToArray (typeof (string));
  611. HttpContext ctx = HttpContext.Current;
  612. HttpRequest req = ctx != null ? ctx.Request : null;
  613. if (req == null)
  614. throw new HttpException ("No current context, cannot compile.");
  615. for (int i = 0; i < deps.Length; i++)
  616. deps [i] = req.MapPath (deps [i]);
  617. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
  618. } else
  619. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
  620. }
  621. public Type GetCompiledType ()
  622. {
  623. Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
  624. if (type != null) {
  625. return type;
  626. }
  627. #if NET_2_0
  628. Parse ();
  629. #else
  630. try {
  631. Parse ();
  632. } catch (ParseException ex) {
  633. throw new HttpException ("Compilation failed.", ex);
  634. }
  635. #endif
  636. BaseCompiler compiler = GetCompilerFromType ();
  637. type = compiler.GetCompiledType ();
  638. AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
  639. return type;
  640. }
  641. #if DEBUG
  642. static void PrintTree (ControlBuilder builder, int indent)
  643. {
  644. if (builder == null)
  645. return;
  646. string i = new string ('\t', indent);
  647. Console.Write (i);
  648. Console.WriteLine ("b: {0}; naming container: {1}; id: {2}; type: {3}; parent: {4}",
  649. builder, builder.IsNamingContainer, builder.ID, builder.ControlType, builder.ParentBuilder);
  650. if (builder.Children != null)
  651. foreach (object o in builder.Children) {
  652. if (o is ControlBuilder)
  653. PrintTree ((ControlBuilder) o, indent++);
  654. }
  655. }
  656. static void PrintLocation (ILocation loc)
  657. {
  658. Console.WriteLine ("\tFile name: " + loc.Filename);
  659. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  660. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  661. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  662. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  663. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  664. Console.WriteLine ();
  665. }
  666. #endif
  667. void ParseError (ILocation location, string message)
  668. {
  669. throw new ParseException (location, message);
  670. }
  671. // KLUDGE WARNING!!
  672. //
  673. // The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
  674. // around a limitation of the current asp.net parser which is unable to parse server
  675. // controls inside client tag attributes. Since the architecture of the current
  676. // parser does not allow for clean solution of this problem, hence the kludge
  677. // below. It will be gone as soon as the parser is rewritten.
  678. //
  679. // The kludge supports only self-closing tags inside attributes.
  680. //
  681. // KLUDGE WARNING!!
  682. bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
  683. {
  684. if (attributes == null || attributes.Count == 0)
  685. return false;
  686. Match match;
  687. Group group;
  688. string value;
  689. bool retval = false;
  690. int index, length;
  691. StringBuilder sb = new StringBuilder ();
  692. sb.AppendFormat ("\t<{0}", tagid);
  693. foreach (string key in attributes.Keys) {
  694. value = attributes [key] as string;
  695. if (value == null || value.Length < 16) { // optimization
  696. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  697. continue;
  698. }
  699. match = runatServer.Match (attributes [key] as string);
  700. if (!match.Success) {
  701. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  702. continue;
  703. }
  704. if (sb.Length > 0) {
  705. TextParsed (location, sb.ToString ());
  706. sb.Length = 0;
  707. }
  708. retval = true;
  709. group = match.Groups [0];
  710. index = group.Index;
  711. length = group.Length;
  712. TextParsed (location, String.Format (" {0}=\"{1}", key, index > 0 ? value.Substring (0, index) : String.Empty));;
  713. FlushText ();
  714. ParseAttributeTag (group.Value, location);
  715. if (index + length < value.Length)
  716. TextParsed (location, value.Substring (index + length) + "\"");
  717. else
  718. TextParsed (location, "\"");
  719. }
  720. if (type == TagType.SelfClosing)
  721. sb.Append ("/>");
  722. else
  723. sb.Append (">");
  724. if (retval && sb.Length > 0)
  725. TextParsed (location, sb.ToString ());
  726. return retval;
  727. }
  728. void ParseAttributeTag (string code, ILocation location)
  729. {
  730. AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code), location.BeginLine - 1, location as AspParser);
  731. parser.Error += new ParseErrorHandler (ParseError);
  732. parser.TagParsed += new TagParsedHandler (TagParsed);
  733. parser.TextParsed += new TextParsedHandler (TextParsed);
  734. parser.Parse ();
  735. if (text.Length > 0)
  736. FlushText ();
  737. }
  738. #if NET_2_0
  739. void ParsingCompleted ()
  740. {
  741. PageParserFilter pfilter = PageParserFilter;
  742. if (pfilter == null)
  743. return;
  744. pfilter.ParseComplete (RootBuilder);
  745. }
  746. #endif
  747. void CheckIfIncludeFileIsSecure (string filePath)
  748. {
  749. if (filePath == null || filePath.Length == 0)
  750. return;
  751. // a bit slow, but fully portable
  752. string newdir = null;
  753. Exception exception = null;
  754. try {
  755. string origdir = Directory.GetCurrentDirectory ();
  756. Directory.SetCurrentDirectory (Path.GetDirectoryName (filePath));
  757. newdir = Directory.GetCurrentDirectory ();
  758. Directory.SetCurrentDirectory (origdir);
  759. if (newdir [newdir.Length - 1] != '/')
  760. newdir += "/";
  761. } catch (DirectoryNotFoundException) {
  762. return; // will be converted into 404
  763. } catch (FileNotFoundException) {
  764. return; // as above
  765. } catch (Exception ex) {
  766. // better safe than sorry
  767. exception = ex;
  768. }
  769. if (exception != null || !StrUtils.StartsWith (newdir, HttpRuntime.AppDomainAppPath))
  770. throw new ParseException (Location, "Files above the application's root directory cannot be included.");
  771. }
  772. string ChopOffTagStart (ILocation location, string content, string tagid)
  773. {
  774. string tagstart = '<' + tagid;
  775. if (content.StartsWith (tagstart)) {
  776. TextParsed (location, tagstart);
  777. content = content.Substring (tagstart.Length);
  778. }
  779. return content;
  780. }
  781. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  782. {
  783. bool tagIgnored;
  784. this.location = new Location (location);
  785. if (tparser != null)
  786. tparser.Location = location;
  787. if (text.Length != 0)
  788. FlushText (lastTag == TagType.CodeRender);
  789. if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
  790. bool in_script = (inScript || ignore_text);
  791. if (in_script) {
  792. if (ProcessScript (tagtype, attributes))
  793. return;
  794. } else
  795. if (ProcessScript (tagtype, attributes))
  796. return;
  797. }
  798. lastTag = tagtype;
  799. switch (tagtype) {
  800. case TagType.Directive:
  801. if (tagid.Length == 0)
  802. tagid = tparser.DefaultDirectiveName;
  803. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  804. break;
  805. case TagType.Tag:
  806. if (ProcessTag (location, tagid, attributes, tagtype, out tagIgnored)) {
  807. if (!tagIgnored)
  808. useOtherTags = true;
  809. break;
  810. }
  811. if (useOtherTags) {
  812. stack.Builder.EnsureOtherTags ();
  813. stack.Builder.OtherTags.Add (tagid);
  814. }
  815. {
  816. string plainText = location.PlainText;
  817. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
  818. TextParsed (location, ChopOffTagStart (location, plainText, tagid));
  819. }
  820. break;
  821. case TagType.Close:
  822. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  823. if (!notServer && CloseControl (tagid))
  824. break;
  825. TextParsed (location, location.PlainText);
  826. break;
  827. case TagType.SelfClosing:
  828. int count = stack.Count;
  829. if (!ProcessTag (location, tagid, attributes, tagtype, out tagIgnored) && !tagIgnored) {
  830. string plainText = location.PlainText;
  831. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
  832. TextParsed (location, ChopOffTagStart (location, plainText, tagid));
  833. } else if (stack.Count != count) {
  834. CloseControl (tagid);
  835. }
  836. break;
  837. case TagType.DataBinding:
  838. goto case TagType.CodeRender;
  839. case TagType.CodeRenderExpression:
  840. goto case TagType.CodeRender;
  841. case TagType.CodeRender:
  842. if (isApplication)
  843. throw new ParseException (location, "Invalid content for application file.");
  844. ProcessCode (tagtype, tagid, location);
  845. break;
  846. case TagType.Include:
  847. if (isApplication)
  848. throw new ParseException (location, "Invalid content for application file.");
  849. string file = attributes ["virtual"] as string;
  850. bool isvirtual = (file != null);
  851. if (!isvirtual)
  852. file = attributes ["file"] as string;
  853. if (isvirtual) {
  854. bool parsed = false;
  855. #if NET_2_0
  856. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  857. if (vpp.FileExists (file)) {
  858. VirtualFile vf = vpp.GetFile (file);
  859. if (vf != null) {
  860. Parse (vf.Open (), file, true);
  861. parsed = true;
  862. }
  863. }
  864. #endif
  865. if (!parsed)
  866. Parse (tparser.MapPath (file), true);
  867. } else {
  868. string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
  869. CheckIfIncludeFileIsSecure (includeFilePath);
  870. tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
  871. try {
  872. Parse (includeFilePath, true);
  873. } finally {
  874. tparser.PopIncludeDir ();
  875. }
  876. }
  877. break;
  878. default:
  879. break;
  880. }
  881. //PrintLocation (location);
  882. }
  883. static bool TryRemoveTag (string tagid, ArrayList otags)
  884. {
  885. if (otags == null || otags.Count == 0)
  886. return false;
  887. for (int idx = otags.Count - 1; idx >= 0; idx--) {
  888. string otagid = (string) otags [idx];
  889. if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
  890. do {
  891. otags.RemoveAt (idx);
  892. } while (otags.Count - 1 >= idx);
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. static string GetIncludeFilePath (string basedir, string filename)
  899. {
  900. if (Path.DirectorySeparatorChar == '/')
  901. filename = filename.Replace ("\\", "/");
  902. return Path.GetFullPath (Path.Combine (basedir, filename));
  903. }
  904. delegate bool CheckBlockEnd (string text);
  905. bool CheckTagEndNeeded (string text)
  906. {
  907. return !text.EndsWith ("/>");
  908. }
  909. #if NET_2_0
  910. List <TextBlock>
  911. #else
  912. ArrayList
  913. #endif
  914. FindRegexBlocks (Regex rxStart, Regex rxEnd, CheckBlockEnd checkEnd, IList blocks, TextBlockType typeForMatches, bool discardBlocks)
  915. {
  916. #if NET_2_0
  917. var ret = new List <TextBlock> ();
  918. #else
  919. ArrayList ret = new ArrayList ();
  920. #endif
  921. foreach (TextBlock block in blocks) {
  922. if (block.Type != TextBlockType.Verbatim) {
  923. ret.Add (block);
  924. continue;
  925. }
  926. int lastIndex = 0, index;
  927. MatchCollection matches = rxStart.Matches (block.Content);
  928. bool foundMatches = matches.Count > 0;
  929. foreach (Match match in matches) {
  930. foundMatches = true;
  931. index = match.Index;
  932. if (lastIndex < index)
  933. ret.Add (new TextBlock (TextBlockType.Verbatim, block.Content.Substring (lastIndex, index - lastIndex)));
  934. string value = match.Value;
  935. if (rxEnd != null && checkEnd (value)) {
  936. int startFrom = index + value.Length;
  937. Match m = rxEnd.Match (block.Content, startFrom);
  938. if (m.Success)
  939. value += block.Content.Substring (startFrom, m.Index - startFrom) + m.Value;
  940. }
  941. if (!discardBlocks)
  942. ret.Add (new TextBlock (typeForMatches, value));
  943. lastIndex = index + value.Length;
  944. }
  945. if (lastIndex > 0 && lastIndex < block.Content.Length)
  946. ret.Add (new TextBlock (TextBlockType.Verbatim, block.Content.Substring (lastIndex)));
  947. if (!foundMatches)
  948. ret.Add (block);
  949. }
  950. return ret;
  951. }
  952. IList SplitTextIntoBlocks (string text)
  953. {
  954. #if NET_2_0
  955. var ret = new List <TextBlock> ();
  956. #else
  957. ArrayList ret = new ArrayList ();
  958. #endif
  959. ret.Add (new TextBlock (TextBlockType.Verbatim, text));
  960. ret = FindRegexBlocks (clientCommentRegex, null, null, ret, TextBlockType.Comment, false);
  961. ret = FindRegexBlocks (runatServer, endOfTag, CheckTagEndNeeded, ret, TextBlockType.Tag, false);
  962. ret = FindRegexBlocks (expressionRegex, null, null, ret, TextBlockType.Expression, false);
  963. return ret;
  964. }
  965. void TextParsed (ILocation location, string text)
  966. {
  967. if (ignore_text)
  968. return;
  969. if (inScript) {
  970. this.text.Append (text);
  971. FlushText (true);
  972. return;
  973. }
  974. IList blocks = SplitTextIntoBlocks (text);
  975. foreach (TextBlock block in blocks) {
  976. switch (block.Type) {
  977. case TextBlockType.Verbatim:
  978. this.text.Append (block.Content);
  979. break;
  980. case TextBlockType.Expression:
  981. if (this.text.Length > 0)
  982. FlushText (true);
  983. CodeRenderParser r = new CodeRenderParser (block.Content, stack.Builder, location);
  984. r.AddChildren (this);
  985. break;
  986. case TextBlockType.Tag:
  987. ParseAttributeTag (block.Content, location);
  988. break;
  989. case TextBlockType.Comment: {
  990. this.text.Append ("<!--");
  991. FlushText (true);
  992. AspParser parser = new AspParser ("@@comment_code@@",
  993. new StringReader (block.Content.Substring (4, block.Length - 7)),
  994. location.BeginLine - 1,
  995. location as AspParser);
  996. parser.Error += new ParseErrorHandler (ParseError);
  997. parser.TagParsed += new TagParsedHandler (TagParsed);
  998. parser.TextParsed += new TextParsedHandler (TextParsed);
  999. parser.Parse ();
  1000. this.text.Append ("-->");
  1001. FlushText (true);
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. void FlushText ()
  1008. {
  1009. FlushText (false);
  1010. }
  1011. void FlushText (bool ignoreEmptyString)
  1012. {
  1013. string t = text.ToString ();
  1014. text.Length = 0;
  1015. if (ignoreEmptyString && t.Trim ().Length == 0)
  1016. return;
  1017. if (inScript) {
  1018. #if NET_2_0
  1019. PageParserFilter pfilter = PageParserFilter;
  1020. if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
  1021. return;
  1022. #endif
  1023. tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
  1024. return;
  1025. }
  1026. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  1027. throw new ParseException (location, "Content not valid for application file.");
  1028. ControlBuilder current = stack.Builder;
  1029. current.AppendLiteralString (t);
  1030. if (current.NeedsTagInnerText ()) {
  1031. tagInnerText.Append (t);
  1032. }
  1033. }
  1034. #if NET_2_0
  1035. bool BuilderHasOtherThan (Type type, ControlBuilder cb)
  1036. {
  1037. ArrayList al = cb.OtherTags;
  1038. if (al != null && al.Count > 0)
  1039. return true;
  1040. al = cb.Children;
  1041. if (al != null) {
  1042. ControlBuilder tmp;
  1043. foreach (object o in al) {
  1044. if (o == null)
  1045. continue;
  1046. tmp = o as ControlBuilder;
  1047. if (tmp == null) {
  1048. string s = o as string;
  1049. if (s != null && String.IsNullOrEmpty (s.Trim ()))
  1050. continue;
  1051. return true;
  1052. }
  1053. if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
  1054. continue;
  1055. if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
  1056. return true;
  1057. }
  1058. }
  1059. return false;
  1060. }
  1061. bool OtherControlsAllowed (ControlBuilder cb)
  1062. {
  1063. if (cb == null)
  1064. return true;
  1065. if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
  1066. return true;
  1067. if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), RootBuilder))
  1068. return false;
  1069. return true;
  1070. }
  1071. #endif
  1072. public void AddControl (Type type, IDictionary attributes)
  1073. {
  1074. ControlBuilder parent = stack.Builder;
  1075. ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
  1076. attributes, location.BeginLine,
  1077. location.Filename);
  1078. if (builder != null)
  1079. parent.AppendSubBuilder (builder);
  1080. }
  1081. bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype, out bool ignored)
  1082. {
  1083. ignored = false;
  1084. if (isApplication) {
  1085. if (String.Compare (tagid, "object", true, CultureInfo.InvariantCulture) != 0)
  1086. throw new ParseException (location, "Invalid tag for application file.");
  1087. }
  1088. ControlBuilder parent = stack.Builder;
  1089. ControlBuilder builder = null;
  1090. if (parent != null && parent.ControlType == typeof (HtmlTable) &&
  1091. (String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0 ||
  1092. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0)) {
  1093. ignored = true;
  1094. return true;
  1095. }
  1096. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  1097. if (stack.Count > 1) {
  1098. try {
  1099. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  1100. } catch (TypeLoadException e) {
  1101. throw new ParseException (Location, "Type not found.", e);
  1102. } catch (Exception e) {
  1103. throw new ParseException (Location, e.Message, e);
  1104. }
  1105. }
  1106. bool runatServer = atts != null && atts.IsRunAtServer ();
  1107. if (builder == null && runatServer) {
  1108. string id = htable ["id"] as string;
  1109. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  1110. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  1111. try {
  1112. builder = RootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  1113. } catch (TypeLoadException e) {
  1114. throw new ParseException (Location, "Type not found.", e);
  1115. } catch (HttpException e) {
  1116. CompilationException inner = e.InnerException as CompilationException;
  1117. if (inner != null)
  1118. throw inner;
  1119. throw new ParseException (Location, e.Message, e);
  1120. } catch (Exception e) {
  1121. throw new ParseException (Location, e.Message, e);
  1122. }
  1123. }
  1124. if (builder == null)
  1125. return false;
  1126. // This is as good as we can do for now - if the parsed location contains
  1127. // both expressions and code render blocks then we're out of luck...
  1128. string plainText = location.PlainText;
  1129. if (!runatServer && plainText.IndexOf ("<%$") == -1&& plainText.IndexOf ("<%") > -1)
  1130. return false;
  1131. #if NET_2_0
  1132. PageParserFilter pfilter = PageParserFilter;
  1133. if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
  1134. throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
  1135. if (!OtherControlsAllowed (builder))
  1136. throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
  1137. #endif
  1138. builder.Location = location;
  1139. builder.ID = htable ["id"] as string;
  1140. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  1141. if (inForm)
  1142. throw new ParseException (location, "Only one <form> allowed.");
  1143. inForm = true;
  1144. }
  1145. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  1146. if (builder is TemplateBuilder) {
  1147. // push the id list
  1148. }
  1149. stack.Push (builder, location);
  1150. } else {
  1151. if (!isApplication && builder is ObjectTagBuilder) {
  1152. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  1153. if (ot.Scope != null && ot.Scope.Length > 0)
  1154. throw new ParseException (location, "Scope not allowed here");
  1155. if (tagtype == TagType.Tag) {
  1156. stack.Push (builder, location);
  1157. return true;
  1158. }
  1159. }
  1160. parent.AppendSubBuilder (builder);
  1161. builder.CloseControl ();
  1162. }
  1163. return true;
  1164. }
  1165. string ReadFile (string filename)
  1166. {
  1167. string realpath = tparser.MapPath (filename);
  1168. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  1169. string content = sr.ReadToEnd ();
  1170. return content;
  1171. }
  1172. }
  1173. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  1174. {
  1175. if (tagtype != TagType.Close) {
  1176. if (attributes != null && attributes.IsRunAtServer ()) {
  1177. string language = (string) attributes ["language"];
  1178. if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
  1179. tparser.SetLanguage (language);
  1180. CheckLanguage (language);
  1181. string src = (string) attributes ["src"];
  1182. if (src != null) {
  1183. if (src.Length == 0)
  1184. throw new ParseException (Parser,
  1185. "src cannot be an empty string");
  1186. string content = ReadFile (src);
  1187. inScript = true;
  1188. TextParsed (Parser, content);
  1189. FlushText ();
  1190. inScript = false;
  1191. if (tagtype != TagType.SelfClosing) {
  1192. ignore_text = true;
  1193. Parser.VerbatimID = "script";
  1194. }
  1195. } else if (tagtype == TagType.Tag) {
  1196. Parser.VerbatimID = "script";
  1197. inScript = true;
  1198. }
  1199. return true;
  1200. } else {
  1201. if (tagtype != TagType.SelfClosing) {
  1202. Parser.VerbatimID = "script";
  1203. javascript = true;
  1204. }
  1205. string content = location.PlainText;
  1206. /* HACK, HACK, HACK */
  1207. if (content.StartsWith ("<script")) {
  1208. TextParsed (location, "<script");
  1209. content = content.Substring (7);
  1210. }
  1211. TextParsed (location, content);
  1212. return true;
  1213. }
  1214. }
  1215. bool result;
  1216. if (inScript) {
  1217. result = inScript;
  1218. inScript = false;
  1219. } else if (!ignore_text) {
  1220. result = javascript;
  1221. javascript = false;
  1222. TextParsed (location, location.PlainText);
  1223. } else {
  1224. ignore_text = false;
  1225. result = true;
  1226. }
  1227. return result;
  1228. }
  1229. bool CloseControl (string tagid)
  1230. {
  1231. ControlBuilder current = stack.Builder;
  1232. string btag = current.OriginalTagName;
  1233. if (String.Compare (btag, "tbody", true, CultureInfo.InvariantCulture) != 0 &&
  1234. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0) {
  1235. if (!current.ChildrenAsProperties) {
  1236. try {
  1237. TextParsed (location, location.PlainText);
  1238. FlushText ();
  1239. } catch {}
  1240. }
  1241. return true;
  1242. }
  1243. if (current.ControlType == typeof (HtmlTable) && String.Compare (tagid, "thead", true, CultureInfo.InvariantCulture) == 0)
  1244. return true;
  1245. if (0 != String.Compare (tagid, btag, true, CultureInfo.InvariantCulture))
  1246. return false;
  1247. // if (current is TemplateBuilder)
  1248. // pop from the id list
  1249. if (current.NeedsTagInnerText ()) {
  1250. try {
  1251. current.SetTagInnerText (tagInnerText.ToString ());
  1252. } catch (Exception e) {
  1253. throw new ParseException (current.Location, e.Message, e);
  1254. }
  1255. tagInnerText.Length = 0;
  1256. }
  1257. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  1258. inForm = false;
  1259. }
  1260. current.CloseControl ();
  1261. stack.Pop ();
  1262. stack.Builder.AppendSubBuilder (current);
  1263. return true;
  1264. }
  1265. #if NET_2_0
  1266. CodeConstructType MapTagTypeToConstructType (TagType tagtype)
  1267. {
  1268. switch (tagtype) {
  1269. case TagType.CodeRenderExpression:
  1270. return CodeConstructType.ExpressionSnippet;
  1271. case TagType.CodeRender:
  1272. return CodeConstructType.CodeSnippet;
  1273. case TagType.DataBinding:
  1274. return CodeConstructType.DataBindingSnippet;
  1275. default:
  1276. throw new InvalidOperationException ("Unexpected tag type.");
  1277. }
  1278. }
  1279. #endif
  1280. bool ProcessCode (TagType tagtype, string code, ILocation location)
  1281. {
  1282. #if NET_2_0
  1283. PageParserFilter pfilter = PageParserFilter;
  1284. // LAMESPEC:
  1285. //
  1286. // http://msdn.microsoft.com/en-us/library/system.web.ui.pageparserfilter.processcodeconstruct.aspx
  1287. //
  1288. // The above page says if false is returned then we should NOT process the
  1289. // code further, wheras in reality it's the other way around. The
  1290. // ProcessCodeConstruct return value means whether or not the filter
  1291. // _processed_ the code.
  1292. //
  1293. if (pfilter != null && (!pfilter.AllowCode || pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
  1294. return true;
  1295. #endif
  1296. ControlBuilder b = null;
  1297. if (tagtype == TagType.CodeRender)
  1298. b = new CodeRenderBuilder (code, false, location);
  1299. else if (tagtype == TagType.CodeRenderExpression)
  1300. b = new CodeRenderBuilder (code, true, location);
  1301. else if (tagtype == TagType.DataBinding)
  1302. b = new DataBindingBuilder (code, location);
  1303. else
  1304. throw new HttpException ("Should never happen");
  1305. stack.Builder.AppendSubBuilder (b);
  1306. return true;
  1307. }
  1308. public ILocation Location {
  1309. get { return location; }
  1310. }
  1311. void CheckLanguage (string lang)
  1312. {
  1313. if (lang == null || lang == "")
  1314. return;
  1315. if (String.Compare (lang, tparser.Language, true, CultureInfo.InvariantCulture) == 0)
  1316. return;
  1317. #if NET_2_0
  1318. CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  1319. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  1320. #else
  1321. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  1322. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
  1323. #endif
  1324. throw new ParseException (Location,
  1325. String.Format ("Trying to mix language '{0}' and '{1}'.",
  1326. tparser.Language, lang));
  1327. }
  1328. // Used to get CodeRender tags in attribute values
  1329. class CodeRenderParser
  1330. {
  1331. string str;
  1332. ControlBuilder builder;
  1333. AspGenerator generator;
  1334. ILocation location;
  1335. public CodeRenderParser (string str, ControlBuilder builder, ILocation location)
  1336. {
  1337. this.str = str;
  1338. this.builder = builder;
  1339. this.location = location;
  1340. }
  1341. public void AddChildren (AspGenerator generator)
  1342. {
  1343. this.generator = generator;
  1344. int index = str.IndexOf ("<%");
  1345. if (index > 0)
  1346. DoParseExpressions (str);
  1347. else
  1348. DoParse (str);
  1349. }
  1350. void DoParseExpressions (string str)
  1351. {
  1352. int startIndex = 0, index = 0;
  1353. Regex codeDirective = new Regex ("(<%(?!@)(?<code>(.|\\s)*?)%>)|(<[\\w:\\.]+.*?runat=[\"']?server[\"']?.*?/>)",
  1354. RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  1355. Match match;
  1356. int strLen = str.Length;
  1357. while (index > -1 && startIndex < strLen) {
  1358. match = codeDirective.Match (str, index);
  1359. if (match.Success) {
  1360. string value = match.Value;
  1361. index = match.Index;
  1362. if (index > startIndex)
  1363. TextParsed (null, str.Substring (startIndex, index - startIndex));
  1364. DoParse (value);
  1365. index += value.Length;
  1366. startIndex = index;
  1367. } else
  1368. break;
  1369. if (index < strLen)
  1370. index = str.IndexOf ('<', index);
  1371. else
  1372. break;
  1373. }
  1374. if (startIndex < strLen)
  1375. TextParsed (null, str.Substring (startIndex));
  1376. }
  1377. void DoParse (string str)
  1378. {
  1379. AspParser parser = new AspParser ("@@code_render@@", new StringReader (str), location.BeginLine - 1, location as AspParser);
  1380. parser.Error += new ParseErrorHandler (ParseError);
  1381. parser.TagParsed += new TagParsedHandler (TagParsed);
  1382. parser.TextParsed += new TextParsedHandler (TextParsed);
  1383. parser.Parse ();
  1384. }
  1385. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  1386. {
  1387. switch (tagtype) {
  1388. case TagType.CodeRender:
  1389. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  1390. break;
  1391. case TagType.CodeRenderExpression:
  1392. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  1393. break;
  1394. case TagType.DataBinding:
  1395. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  1396. break;
  1397. case TagType.Tag:
  1398. case TagType.SelfClosing:
  1399. case TagType.Close:
  1400. if (generator != null)
  1401. generator.TagParsed (location, tagtype, tagid, attributes);
  1402. else
  1403. goto default;
  1404. break;
  1405. default:
  1406. string text = location.PlainText;
  1407. if (text != null && text.Trim ().Length > 0)
  1408. builder.AppendLiteralString (text);
  1409. break;
  1410. }
  1411. }
  1412. void TextParsed (ILocation location, string text)
  1413. {
  1414. builder.AppendLiteralString (text);
  1415. }
  1416. void ParseError (ILocation location, string message)
  1417. {
  1418. throw new ParseException (location, message);
  1419. }
  1420. }
  1421. }
  1422. }