AspGenerator.cs 45 KB

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