AspGenerator.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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 outerParser = location as AspParser;
  680. int positionOffset = outerParser != null ? outerParser.BeginPosition : 0;
  681. AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code), location.BeginLine - 1, positionOffset, outerParser);
  682. parser.Error += new ParseErrorHandler (ParseError);
  683. parser.TagParsed += new TagParsedHandler (TagParsed);
  684. parser.TextParsed += new TextParsedHandler (TextParsed);
  685. parser.Parse ();
  686. if (text.Length > 0)
  687. FlushText ();
  688. }
  689. void ParsingCompleted ()
  690. {
  691. PageParserFilter pfilter = PageParserFilter;
  692. if (pfilter == null)
  693. return;
  694. pfilter.ParseComplete (RootBuilder);
  695. }
  696. void CheckIfIncludeFileIsSecure (string filePath)
  697. {
  698. if (filePath == null || filePath.Length == 0)
  699. return;
  700. // a bit slow, but fully portable
  701. string newdir = null;
  702. Exception exception = null;
  703. try {
  704. string origdir = Directory.GetCurrentDirectory ();
  705. Directory.SetCurrentDirectory (Path.GetDirectoryName (filePath));
  706. newdir = Directory.GetCurrentDirectory ();
  707. Directory.SetCurrentDirectory (origdir);
  708. if (newdir [newdir.Length - 1] != '/')
  709. newdir += "/";
  710. } catch (DirectoryNotFoundException) {
  711. return; // will be converted into 404
  712. } catch (FileNotFoundException) {
  713. return; // as above
  714. } catch (Exception ex) {
  715. // better safe than sorry
  716. exception = ex;
  717. }
  718. if (exception != null || !StrUtils.StartsWith (newdir, HttpRuntime.AppDomainAppPath))
  719. throw new ParseException (Location, "Files above the application's root directory cannot be included.");
  720. }
  721. string ChopOffTagStart (ILocation location, string content, string tagid)
  722. {
  723. string tagstart = '<' + tagid;
  724. if (content.StartsWith (tagstart)) {
  725. TextParsed (location, tagstart);
  726. content = content.Substring (tagstart.Length);
  727. }
  728. return content;
  729. }
  730. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  731. {
  732. bool tagIgnored;
  733. this.location = new Location (location);
  734. if (tparser != null)
  735. tparser.Location = location;
  736. if (text.Length != 0)
  737. FlushText (lastTag == TagType.CodeRender);
  738. if (0 == String.Compare (tagid, "script", true, Helpers.InvariantCulture)) {
  739. bool in_script = (inScript || ignore_text);
  740. if (in_script) {
  741. if (ProcessScript (tagtype, attributes))
  742. return;
  743. } else
  744. if (ProcessScript (tagtype, attributes))
  745. return;
  746. }
  747. lastTag = tagtype;
  748. switch (tagtype) {
  749. case TagType.Directive:
  750. if (tagid.Length == 0)
  751. tagid = tparser.DefaultDirectiveName;
  752. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  753. break;
  754. case TagType.Tag:
  755. if (ProcessTag (location, tagid, attributes, tagtype, out tagIgnored)) {
  756. if (!tagIgnored)
  757. useOtherTags = true;
  758. break;
  759. }
  760. if (useOtherTags) {
  761. stack.Builder.EnsureOtherTags ();
  762. stack.Builder.OtherTags.Add (tagid);
  763. }
  764. {
  765. string plainText = location.PlainText;
  766. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
  767. TextParsed (location, ChopOffTagStart (location, plainText, tagid));
  768. }
  769. break;
  770. case TagType.Close:
  771. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  772. if (!notServer && CloseControl (tagid))
  773. break;
  774. TextParsed (location, location.PlainText);
  775. break;
  776. case TagType.SelfClosing:
  777. int count = stack.Count;
  778. if (!ProcessTag (location, tagid, attributes, tagtype, out tagIgnored) && !tagIgnored) {
  779. string plainText = location.PlainText;
  780. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
  781. TextParsed (location, ChopOffTagStart (location, plainText, tagid));
  782. } else if (stack.Count != count) {
  783. CloseControl (tagid);
  784. }
  785. break;
  786. case TagType.DataBinding:
  787. goto case TagType.CodeRender;
  788. case TagType.CodeRenderExpression:
  789. goto case TagType.CodeRender;
  790. case TagType.CodeRender:
  791. if (isApplication)
  792. throw new ParseException (location, "Invalid content for application file.");
  793. ProcessCode (tagtype, tagid, location);
  794. break;
  795. case TagType.Include:
  796. if (isApplication)
  797. throw new ParseException (location, "Invalid content for application file.");
  798. string file = attributes ["virtual"] as string;
  799. bool isvirtual = (file != null);
  800. if (!isvirtual)
  801. file = attributes ["file"] as string;
  802. if (isvirtual) {
  803. bool parsed = false;
  804. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  805. if (vpp.FileExists (file)) {
  806. VirtualFile vf = vpp.GetFile (file);
  807. if (vf != null) {
  808. Parse (vf.Open (), file, true);
  809. parsed = true;
  810. }
  811. }
  812. if (!parsed)
  813. Parse (tparser.MapPath (file), true);
  814. } else {
  815. string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
  816. CheckIfIncludeFileIsSecure (includeFilePath);
  817. tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
  818. try {
  819. Parse (includeFilePath, true);
  820. } finally {
  821. tparser.PopIncludeDir ();
  822. }
  823. }
  824. break;
  825. default:
  826. break;
  827. }
  828. //PrintLocation (location);
  829. }
  830. static bool TryRemoveTag (string tagid, ArrayList otags)
  831. {
  832. if (otags == null || otags.Count == 0)
  833. return false;
  834. for (int idx = otags.Count - 1; idx >= 0; idx--) {
  835. string otagid = (string) otags [idx];
  836. if (0 == String.Compare (tagid, otagid, true, Helpers.InvariantCulture)) {
  837. do {
  838. otags.RemoveAt (idx);
  839. } while (otags.Count - 1 >= idx);
  840. return true;
  841. }
  842. }
  843. return false;
  844. }
  845. static string GetIncludeFilePath (string basedir, string filename)
  846. {
  847. if (Path.DirectorySeparatorChar == '/')
  848. filename = filename.Replace ("\\", "/");
  849. return Path.GetFullPath (Path.Combine (basedir, filename));
  850. }
  851. delegate bool CheckBlockEnd (string text);
  852. bool CheckTagEndNeeded (string text)
  853. {
  854. return !text.EndsWith ("/>");
  855. }
  856. List <TextBlock> FindRegexBlocks (Regex rxStart, Regex rxEnd, CheckBlockEnd checkEnd, IList blocks, TextBlockType typeForMatches, bool discardBlocks)
  857. {
  858. var ret = new List <TextBlock> ();
  859. foreach (TextBlock block in blocks) {
  860. if (block.Type != TextBlockType.Verbatim) {
  861. ret.Add (block);
  862. continue;
  863. }
  864. int lastIndex = 0, index;
  865. MatchCollection matches = rxStart.Matches (block.Content);
  866. bool foundMatches = matches.Count > 0;
  867. foreach (Match match in matches) {
  868. foundMatches = true;
  869. index = match.Index;
  870. if (lastIndex < index)
  871. ret.Add (new TextBlock (TextBlockType.Verbatim, block.Content.Substring (lastIndex, index - lastIndex)));
  872. string value = match.Value;
  873. if (rxEnd != null && checkEnd (value)) {
  874. int startFrom = index + value.Length;
  875. Match m = rxEnd.Match (block.Content, startFrom);
  876. if (m.Success)
  877. value += block.Content.Substring (startFrom, m.Index - startFrom) + m.Value;
  878. }
  879. if (!discardBlocks)
  880. ret.Add (new TextBlock (typeForMatches, value));
  881. lastIndex = index + value.Length;
  882. }
  883. if (lastIndex > 0 && lastIndex < block.Content.Length)
  884. ret.Add (new TextBlock (TextBlockType.Verbatim, block.Content.Substring (lastIndex)));
  885. if (!foundMatches)
  886. ret.Add (block);
  887. }
  888. return ret;
  889. }
  890. IList SplitTextIntoBlocks (string text)
  891. {
  892. var ret = new List <TextBlock> ();
  893. ret.Add (new TextBlock (TextBlockType.Verbatim, text));
  894. ret = FindRegexBlocks (clientCommentRegex, null, null, ret, TextBlockType.Comment, false);
  895. ret = FindRegexBlocks (runatServer, endOfTag, CheckTagEndNeeded, ret, TextBlockType.Tag, false);
  896. ret = FindRegexBlocks (expressionRegex, null, null, ret, TextBlockType.Expression, false);
  897. return ret;
  898. }
  899. void TextParsed (ILocation location, string text)
  900. {
  901. if (ignore_text)
  902. return;
  903. if (inScript) {
  904. this.text.Append (text);
  905. FlushText (true);
  906. return;
  907. }
  908. IList blocks = SplitTextIntoBlocks (text);
  909. foreach (TextBlock block in blocks) {
  910. switch (block.Type) {
  911. case TextBlockType.Verbatim:
  912. this.text.Append (block.Content);
  913. break;
  914. case TextBlockType.Expression:
  915. if (this.text.Length > 0)
  916. FlushText (true);
  917. CodeRenderParser r = new CodeRenderParser (block.Content, stack.Builder, location);
  918. r.AddChildren (this);
  919. break;
  920. case TextBlockType.Tag:
  921. ParseAttributeTag (block.Content, location);
  922. break;
  923. case TextBlockType.Comment: {
  924. this.text.Append ("<!--");
  925. FlushText (true);
  926. string blockToParse = block.Content.Substring (4, block.Length - 7);
  927. bool condEndif;
  928. if (blockToParse.EndsWith ("<![endif]")) {
  929. blockToParse = blockToParse.Substring (0, blockToParse.Length - 9);
  930. condEndif = true;
  931. } else
  932. condEndif = false;
  933. AspParser outerParser = location as AspParser;
  934. int positionOffset = outerParser != null ? outerParser.BeginPosition : 0;
  935. AspParser parser = new AspParser ("@@comment_code@@", new StringReader (blockToParse), location.BeginLine - 1, positionOffset, outerParser);
  936. parser.Error += new ParseErrorHandler (ParseError);
  937. parser.TagParsed += new TagParsedHandler (TagParsed);
  938. parser.TextParsed += new TextParsedHandler (TextParsed);
  939. parser.Parse ();
  940. if (condEndif)
  941. this.text.Append ("<![endif]");
  942. this.text.Append ("-->");
  943. FlushText (true);
  944. break;
  945. }
  946. }
  947. }
  948. }
  949. void FlushText ()
  950. {
  951. FlushText (false);
  952. }
  953. void FlushText (bool ignoreEmptyString)
  954. {
  955. string t = text.ToString ();
  956. text.Length = 0;
  957. if (ignoreEmptyString && t.Trim ().Length == 0)
  958. return;
  959. if (inScript) {
  960. PageParserFilter pfilter = PageParserFilter;
  961. if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
  962. return;
  963. tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
  964. return;
  965. }
  966. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  967. throw new ParseException (location, "Content not valid for application file.");
  968. ControlBuilder current = stack.Builder;
  969. current.AppendLiteralString (t);
  970. if (current.NeedsTagInnerText ()) {
  971. tagInnerText.Append (t);
  972. }
  973. }
  974. bool BuilderHasOtherThan (Type type, ControlBuilder cb)
  975. {
  976. ArrayList al = cb.OtherTags;
  977. if (al != null && al.Count > 0)
  978. return true;
  979. al = cb.Children;
  980. if (al != null) {
  981. ControlBuilder tmp;
  982. foreach (object o in al) {
  983. if (o == null)
  984. continue;
  985. tmp = o as ControlBuilder;
  986. if (tmp == null) {
  987. string s = o as string;
  988. if (s != null && String.IsNullOrEmpty (s.Trim ()))
  989. continue;
  990. return true;
  991. }
  992. if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
  993. continue;
  994. if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
  995. return true;
  996. }
  997. }
  998. return false;
  999. }
  1000. bool OtherControlsAllowed (ControlBuilder cb)
  1001. {
  1002. if (cb == null)
  1003. return true;
  1004. if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
  1005. return true;
  1006. if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), RootBuilder))
  1007. return false;
  1008. return true;
  1009. }
  1010. public void AddControl (Type type, IDictionary attributes)
  1011. {
  1012. ControlBuilder parent = stack.Builder;
  1013. ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
  1014. attributes, location.BeginLine,
  1015. location.Filename);
  1016. if (builder != null)
  1017. parent.AppendSubBuilder (builder);
  1018. }
  1019. bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype, out bool ignored)
  1020. {
  1021. ignored = false;
  1022. if (isApplication) {
  1023. if (String.Compare (tagid, "object", true, Helpers.InvariantCulture) != 0)
  1024. throw new ParseException (location, "Invalid tag for application file.");
  1025. }
  1026. ControlBuilder parent = stack.Builder;
  1027. ControlBuilder builder = null;
  1028. if (parent != null && parent.ControlType == typeof (HtmlTable) &&
  1029. (String.Compare (tagid, "thead", true, Helpers.InvariantCulture) == 0 ||
  1030. String.Compare (tagid, "tbody", true, Helpers.InvariantCulture) == 0)) {
  1031. ignored = true;
  1032. return true;
  1033. }
  1034. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  1035. if (stack.Count > 1) {
  1036. try {
  1037. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  1038. } catch (TypeLoadException e) {
  1039. throw new ParseException (Location, "Type not found.", e);
  1040. } catch (Exception e) {
  1041. throw new ParseException (Location, e.Message, e);
  1042. }
  1043. }
  1044. bool runatServer = atts != null && atts.IsRunAtServer ();
  1045. if (builder == null && runatServer) {
  1046. string id = htable ["id"] as string;
  1047. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  1048. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  1049. try {
  1050. builder = RootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  1051. } catch (TypeLoadException e) {
  1052. throw new ParseException (Location, "Type not found.", e);
  1053. } catch (HttpException e) {
  1054. CompilationException inner = e.InnerException as CompilationException;
  1055. if (inner != null)
  1056. throw inner;
  1057. throw new ParseException (Location, e.Message, e);
  1058. } catch (Exception e) {
  1059. throw new ParseException (Location, e.Message, e);
  1060. }
  1061. }
  1062. if (builder == null)
  1063. return false;
  1064. // This is as good as we can do for now - if the parsed location contains
  1065. // both expressions and code render blocks then we're out of luck...
  1066. string plainText = location.PlainText;
  1067. if (!runatServer && plainText.IndexOf ("<%$") == -1&& plainText.IndexOf ("<%") > -1)
  1068. return false;
  1069. PageParserFilter pfilter = PageParserFilter;
  1070. if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
  1071. throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
  1072. if (!OtherControlsAllowed (builder))
  1073. throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
  1074. builder.Location = location;
  1075. builder.ID = htable ["id"] as string;
  1076. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  1077. if (inForm)
  1078. throw new ParseException (location, "Only one <form> allowed.");
  1079. inForm = true;
  1080. }
  1081. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  1082. if (builder is TemplateBuilder) {
  1083. // push the id list
  1084. }
  1085. stack.Push (builder, location);
  1086. } else {
  1087. if (!isApplication && builder is ObjectTagBuilder) {
  1088. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  1089. if (ot.Scope != null && ot.Scope.Length > 0)
  1090. throw new ParseException (location, "Scope not allowed here");
  1091. if (tagtype == TagType.Tag) {
  1092. stack.Push (builder, location);
  1093. return true;
  1094. }
  1095. }
  1096. parent.AppendSubBuilder (builder);
  1097. builder.CloseControl ();
  1098. }
  1099. return true;
  1100. }
  1101. string ReadFile (string filename)
  1102. {
  1103. string realpath = tparser.MapPath (filename);
  1104. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  1105. string content = sr.ReadToEnd ();
  1106. return content;
  1107. }
  1108. }
  1109. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  1110. {
  1111. if (tagtype != TagType.Close) {
  1112. if (attributes != null && attributes.IsRunAtServer ()) {
  1113. string language = (string) attributes ["language"];
  1114. if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
  1115. tparser.SetLanguage (language);
  1116. CheckLanguage (language);
  1117. string src = (string) attributes ["src"];
  1118. if (src != null) {
  1119. if (src.Length == 0)
  1120. throw new ParseException (Parser,
  1121. "src cannot be an empty string");
  1122. string content = ReadFile (src);
  1123. inScript = true;
  1124. TextParsed (Parser, content);
  1125. FlushText ();
  1126. inScript = false;
  1127. if (tagtype != TagType.SelfClosing) {
  1128. ignore_text = true;
  1129. Parser.VerbatimID = "script";
  1130. }
  1131. } else if (tagtype == TagType.Tag) {
  1132. Parser.VerbatimID = "script";
  1133. inScript = true;
  1134. }
  1135. return true;
  1136. } else {
  1137. if (tagtype != TagType.SelfClosing) {
  1138. Parser.VerbatimID = "script";
  1139. javascript = true;
  1140. }
  1141. string content = location.PlainText;
  1142. /* HACK, HACK, HACK */
  1143. if (content.StartsWith ("<script")) {
  1144. TextParsed (location, "<script");
  1145. content = content.Substring (7);
  1146. }
  1147. TextParsed (location, content);
  1148. return true;
  1149. }
  1150. }
  1151. bool result;
  1152. if (inScript) {
  1153. result = inScript;
  1154. inScript = false;
  1155. } else if (!ignore_text) {
  1156. result = javascript;
  1157. javascript = false;
  1158. TextParsed (location, location.PlainText);
  1159. } else {
  1160. ignore_text = false;
  1161. result = true;
  1162. }
  1163. return result;
  1164. }
  1165. bool CloseControl (string tagid)
  1166. {
  1167. ControlBuilder current = stack.Builder;
  1168. string btag = current.OriginalTagName;
  1169. if (String.Compare (btag, "tbody", true, Helpers.InvariantCulture) != 0 &&
  1170. String.Compare (tagid, "tbody", true, Helpers.InvariantCulture) == 0) {
  1171. if (!current.ChildrenAsProperties) {
  1172. try {
  1173. TextParsed (location, location.PlainText);
  1174. FlushText ();
  1175. } catch {}
  1176. }
  1177. return true;
  1178. }
  1179. if (current.ControlType == typeof (HtmlTable) && String.Compare (tagid, "thead", true, Helpers.InvariantCulture) == 0)
  1180. return true;
  1181. if (0 != String.Compare (tagid, btag, true, Helpers.InvariantCulture))
  1182. return false;
  1183. // if (current is TemplateBuilder)
  1184. // pop from the id list
  1185. if (current.NeedsTagInnerText ()) {
  1186. try {
  1187. current.SetTagInnerText (tagInnerText.ToString ());
  1188. } catch (Exception e) {
  1189. throw new ParseException (current.Location, e.Message, e);
  1190. }
  1191. tagInnerText.Length = 0;
  1192. }
  1193. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  1194. inForm = false;
  1195. }
  1196. current.CloseControl ();
  1197. stack.Pop ();
  1198. stack.Builder.AppendSubBuilder (current);
  1199. return true;
  1200. }
  1201. CodeConstructType MapTagTypeToConstructType (TagType tagtype)
  1202. {
  1203. switch (tagtype) {
  1204. case TagType.CodeRenderExpression:
  1205. return CodeConstructType.ExpressionSnippet;
  1206. case TagType.CodeRender:
  1207. return CodeConstructType.CodeSnippet;
  1208. case TagType.DataBinding:
  1209. return CodeConstructType.DataBindingSnippet;
  1210. default:
  1211. throw new InvalidOperationException ("Unexpected tag type.");
  1212. }
  1213. }
  1214. bool ProcessCode (TagType tagtype, string code, ILocation location)
  1215. {
  1216. PageParserFilter pfilter = PageParserFilter;
  1217. // LAMESPEC:
  1218. //
  1219. // http://msdn.microsoft.com/en-us/library/system.web.ui.pageparserfilter.processcodeconstruct.aspx
  1220. //
  1221. // The above page says if false is returned then we should NOT process the
  1222. // code further, wheras in reality it's the other way around. The
  1223. // ProcessCodeConstruct return value means whether or not the filter
  1224. // _processed_ the code.
  1225. //
  1226. if (pfilter != null && (!pfilter.AllowCode || pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
  1227. return true;
  1228. ControlBuilder b = null;
  1229. if (tagtype == TagType.CodeRender)
  1230. b = new CodeRenderBuilder (code, false, location);
  1231. else if (tagtype == TagType.CodeRenderExpression)
  1232. b = new CodeRenderBuilder (code, true, location);
  1233. else if (tagtype == TagType.DataBinding)
  1234. b = new DataBindingBuilder (code, location);
  1235. else
  1236. throw new HttpException ("Should never happen");
  1237. stack.Builder.AppendSubBuilder (b);
  1238. return true;
  1239. }
  1240. public ILocation Location {
  1241. get { return location; }
  1242. }
  1243. void CheckLanguage (string lang)
  1244. {
  1245. if (lang == null || lang == "")
  1246. return;
  1247. if (String.Compare (lang, tparser.Language, true, Helpers.InvariantCulture) == 0)
  1248. return;
  1249. CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  1250. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  1251. throw new ParseException (Location,
  1252. String.Format ("Trying to mix language '{0}' and '{1}'.",
  1253. tparser.Language, lang));
  1254. }
  1255. // Used to get CodeRender tags in attribute values
  1256. class CodeRenderParser
  1257. {
  1258. string str;
  1259. ControlBuilder builder;
  1260. AspGenerator generator;
  1261. ILocation location;
  1262. public CodeRenderParser (string str, ControlBuilder builder, ILocation location)
  1263. {
  1264. this.str = str;
  1265. this.builder = builder;
  1266. this.location = location;
  1267. }
  1268. public void AddChildren (AspGenerator generator)
  1269. {
  1270. this.generator = generator;
  1271. int index = str.IndexOf ("<%");
  1272. if (index > 0)
  1273. DoParseExpressions (str);
  1274. else
  1275. DoParse (str);
  1276. }
  1277. void DoParseExpressions (string str)
  1278. {
  1279. int startIndex = 0, index = 0;
  1280. Regex codeDirective = new Regex ("(<%(?!@)(?<code>(.|\\s)*?)%>)|(<[\\w:\\.]+.*?runat=[\"']?server[\"']?.*?/>)",
  1281. RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  1282. Match match;
  1283. int strLen = str.Length;
  1284. while (index > -1 && startIndex < strLen) {
  1285. match = codeDirective.Match (str, index);
  1286. if (match.Success) {
  1287. string value = match.Value;
  1288. index = match.Index;
  1289. if (index > startIndex)
  1290. TextParsed (null, str.Substring (startIndex, index - startIndex));
  1291. DoParse (value);
  1292. index += value.Length;
  1293. startIndex = index;
  1294. } else
  1295. break;
  1296. if (index < strLen)
  1297. index = str.IndexOf ('<', index);
  1298. else
  1299. break;
  1300. }
  1301. if (startIndex < strLen)
  1302. TextParsed (null, str.Substring (startIndex));
  1303. }
  1304. void DoParse (string str)
  1305. {
  1306. AspParser outerParser = location as AspParser;
  1307. int positionOffset = outerParser != null ? outerParser.BeginPosition : 0;
  1308. AspParser parser = new AspParser ("@@code_render@@", new StringReader (str), location.BeginLine - 1, positionOffset, outerParser);
  1309. parser.Error += new ParseErrorHandler (ParseError);
  1310. parser.TagParsed += new TagParsedHandler (TagParsed);
  1311. parser.TextParsed += new TextParsedHandler (TextParsed);
  1312. parser.Parse ();
  1313. }
  1314. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  1315. {
  1316. switch (tagtype) {
  1317. case TagType.CodeRender:
  1318. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  1319. break;
  1320. case TagType.CodeRenderExpression:
  1321. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  1322. break;
  1323. case TagType.DataBinding:
  1324. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  1325. break;
  1326. case TagType.Tag:
  1327. case TagType.SelfClosing:
  1328. case TagType.Close:
  1329. if (generator != null)
  1330. generator.TagParsed (location, tagtype, tagid, attributes);
  1331. else
  1332. goto default;
  1333. break;
  1334. default:
  1335. string text = location.PlainText;
  1336. if (text != null && text.Trim ().Length > 0)
  1337. builder.AppendLiteralString (text);
  1338. break;
  1339. }
  1340. }
  1341. void TextParsed (ILocation location, string text)
  1342. {
  1343. builder.AppendLiteralString (text);
  1344. }
  1345. void ParseError (ILocation location, string message)
  1346. {
  1347. throw new ParseException (location, message);
  1348. }
  1349. }
  1350. }
  1351. }