AspGenerator.cs 37 KB

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