AspGenerator.cs 45 KB

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