AspGenerator.cs 44 KB

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