AspGenerator.cs 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. ParserStack pstack;
  154. BuilderLocationStack stack;
  155. TemplateParser tparser;
  156. StringBuilder text;
  157. RootBuilder rootBuilder;
  158. bool inScript, javascript, ignore_text;
  159. ILocation location;
  160. bool isApplication;
  161. StringBuilder tagInnerText = new StringBuilder ();
  162. static Hashtable emptyHash = new Hashtable ();
  163. bool inForm;
  164. bool useOtherTags;
  165. TagType lastTag;
  166. public AspGenerator (TemplateParser tparser)
  167. {
  168. this.tparser = tparser;
  169. text = new StringBuilder ();
  170. stack = new BuilderLocationStack ();
  171. rootBuilder = new RootBuilder (tparser);
  172. stack.Push (rootBuilder, null);
  173. tparser.RootBuilder = rootBuilder;
  174. pstack = new ParserStack ();
  175. }
  176. public RootBuilder RootBuilder {
  177. get { return tparser.RootBuilder; }
  178. }
  179. public AspParser Parser {
  180. get { return pstack.Parser; }
  181. }
  182. public string Filename {
  183. get { return pstack.Filename; }
  184. }
  185. #if NET_2_0
  186. PageParserFilter PageParserFilter {
  187. get {
  188. if (tparser == null)
  189. return null;
  190. return tparser.PageParserFilter;
  191. }
  192. }
  193. #endif
  194. BaseCompiler GetCompilerFromType ()
  195. {
  196. Type type = tparser.GetType ();
  197. if (type == typeof (PageParser))
  198. return new PageCompiler ((PageParser) tparser);
  199. if (type == typeof (ApplicationFileParser))
  200. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  201. if (type == typeof (UserControlParser))
  202. return new UserControlCompiler ((UserControlParser) tparser);
  203. #if NET_2_0
  204. if (type == typeof(MasterPageParser))
  205. return new MasterPageCompiler ((MasterPageParser) tparser);
  206. #endif
  207. throw new Exception ("Got type: " + type);
  208. }
  209. void InitParser (TextReader reader, string filename)
  210. {
  211. AspParser parser = new AspParser (filename, reader);
  212. parser.Error += new ParseErrorHandler (ParseError);
  213. parser.TagParsed += new TagParsedHandler (TagParsed);
  214. parser.TextParsed += new TextParsedHandler (TextParsed);
  215. #if NET_2_0
  216. parser.ParsingComplete += new ParsingCompleteHandler (ParsingCompleted);
  217. tparser.AspGenerator = this;
  218. #endif
  219. if (!pstack.Push (parser))
  220. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  221. if (filename != "@@inner_string@@") {
  222. string arvp = Path.Combine (tparser.BaseVirtualDir, Path.GetFileName (filename));
  223. if (VirtualPathUtility.IsAbsolute (arvp))
  224. arvp = VirtualPathUtility.ToAppRelative (arvp);
  225. tparser.AddDependency (arvp);
  226. }
  227. #if NET_2_0
  228. tparser.MD5Checksum = parser.MD5Checksum;
  229. #endif
  230. }
  231. #if NET_2_0
  232. void InitParser (string filename)
  233. {
  234. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  235. InitParser (reader, filename);
  236. }
  237. #endif
  238. public void Parse (string file)
  239. {
  240. #if ONLY_1_1
  241. Parse (file, true);
  242. #else
  243. Parse (file, false);
  244. #endif
  245. }
  246. public void Parse (TextReader reader, string filename, bool doInitParser)
  247. {
  248. try {
  249. isApplication = tparser.DefaultDirectiveName == "application";
  250. if (doInitParser)
  251. InitParser (reader, filename);
  252. pstack.Parser.Parse ();
  253. if (text.Length > 0)
  254. FlushText ();
  255. pstack.Pop ();
  256. #if DEBUG
  257. PrintTree (rootBuilder, 0);
  258. #endif
  259. if (stack.Count > 1 && pstack.Count == 0)
  260. throw new ParseException (stack.Builder.Location,
  261. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  262. } finally {
  263. if (reader != null)
  264. reader.Close ();
  265. }
  266. }
  267. public void Parse (Stream stream, string filename, bool doInitParser)
  268. {
  269. Parse (new StreamReader (stream, WebEncoding.FileEncoding), filename, doInitParser);
  270. }
  271. public void Parse (string filename, bool doInitParser)
  272. {
  273. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  274. Parse (reader, filename, doInitParser);
  275. }
  276. public void Parse ()
  277. {
  278. #if NET_2_0
  279. string inputFile = tparser.InputFile;
  280. TextReader inputReader = tparser.Reader;
  281. try {
  282. if (String.IsNullOrEmpty (inputFile)) {
  283. StreamReader sr = inputReader as StreamReader;
  284. if (sr != null) {
  285. FileStream fr = sr.BaseStream as FileStream;
  286. if (fr != null)
  287. inputFile = fr.Name;
  288. }
  289. if (String.IsNullOrEmpty (inputFile))
  290. inputFile = "@@inner_string@@";
  291. }
  292. if (inputReader != null) {
  293. Parse (inputReader, inputFile, true);
  294. } else {
  295. if (String.IsNullOrEmpty (inputFile))
  296. throw new HttpException ("Parser input file is empty, cannot continue.");
  297. inputFile = Path.GetFullPath (inputFile);
  298. InitParser (inputFile);
  299. Parse (inputFile);
  300. }
  301. } finally {
  302. if (inputReader != null)
  303. inputReader.Close ();
  304. }
  305. #else
  306. Parse (Path.GetFullPath (tparser.InputFile));
  307. #endif
  308. }
  309. internal static void AddTypeToCache (ArrayList dependencies, string inputFile, Type type)
  310. {
  311. if (type == null || inputFile == null || inputFile.Length == 0)
  312. return;
  313. if (dependencies != null && dependencies.Count > 0) {
  314. string [] deps = (string []) dependencies.ToArray (typeof (string));
  315. HttpContext ctx = HttpContext.Current;
  316. HttpRequest req = ctx != null ? ctx.Request : null;
  317. if (req == null)
  318. throw new HttpException ("No current context, cannot compile.");
  319. for (int i = 0; i < deps.Length; i++)
  320. deps [i] = req.MapPath (deps [i]);
  321. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type, new CacheDependency (deps));
  322. } else
  323. HttpRuntime.InternalCache.Insert ("@@Type" + inputFile, type);
  324. }
  325. public Type GetCompiledType ()
  326. {
  327. Type type = (Type) HttpRuntime.InternalCache.Get ("@@Type" + tparser.InputFile);
  328. if (type != null) {
  329. return type;
  330. }
  331. Parse ();
  332. BaseCompiler compiler = GetCompilerFromType ();
  333. type = compiler.GetCompiledType ();
  334. AddTypeToCache (tparser.Dependencies, tparser.InputFile, type);
  335. return type;
  336. }
  337. #if DEBUG
  338. static void PrintTree (ControlBuilder builder, int indent)
  339. {
  340. if (builder == null)
  341. return;
  342. string i = new string ('\t', indent);
  343. Console.Write (i);
  344. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  345. builder, builder.ID, builder.ControlType, builder.ParentBuilder);
  346. if (builder.Children != null)
  347. foreach (object o in builder.Children) {
  348. if (o is ControlBuilder)
  349. PrintTree ((ControlBuilder) o, indent++);
  350. }
  351. }
  352. static void PrintLocation (ILocation loc)
  353. {
  354. Console.WriteLine ("\tFile name: " + loc.Filename);
  355. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  356. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  357. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  358. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  359. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  360. Console.WriteLine ();
  361. }
  362. #endif
  363. void ParseError (ILocation location, string message)
  364. {
  365. throw new ParseException (location, message);
  366. }
  367. // KLUDGE WARNING!!
  368. //
  369. // The code below (ProcessTagsInAttributes, ParseAttributeTag) serves the purpose to work
  370. // around a limitation of the current asp.net parser which is unable to parse server
  371. // controls inside client tag attributes. Since the architecture of the current
  372. // parser does not allow for clean solution of this problem, hence the kludge
  373. // below. It will be gone as soon as the parser is rewritten.
  374. //
  375. // The kludge supports only self-closing tags inside attributes.
  376. //
  377. // KLUDGE WARNING!!
  378. static readonly Regex runatServer=new Regex (@"<[\w:\.]+.*?runat=[""']?server[""']?.*?/>",
  379. RegexOptions.Compiled | RegexOptions.Singleline |
  380. RegexOptions.Multiline | RegexOptions.IgnoreCase);
  381. bool ProcessTagsInAttributes (ILocation location, string tagid, TagAttributes attributes, TagType type)
  382. {
  383. if (attributes == null || attributes.Count == 0)
  384. return false;
  385. Match match;
  386. Group group;
  387. string value;
  388. bool retval = false;
  389. int index, length;
  390. StringBuilder sb = new StringBuilder ();
  391. sb.AppendFormat ("\t<{0}", tagid);
  392. foreach (string key in attributes.Keys) {
  393. value = attributes [key] as string;
  394. if (value == null || value.Length < 16) // optimization
  395. continue;
  396. match = runatServer.Match (attributes [key] as string);
  397. if (!match.Success) {
  398. sb.AppendFormat (" {0}=\"{1}\"", key, value);
  399. continue;
  400. }
  401. if (sb.Length > 0) {
  402. TextParsed (location, sb.ToString ());
  403. sb.Length = 0;
  404. }
  405. retval = true;
  406. group = match.Groups [0];
  407. index = group.Index;
  408. length = group.Length;
  409. if (index > 0)
  410. TextParsed (location, String.Format (" {0}=\"{1}", key, value.Substring (0, index)));
  411. FlushText ();
  412. ParseAttributeTag (group.Value);
  413. if (index + length < value.Length)
  414. TextParsed (location, value.Substring (index + length) + "\"");
  415. }
  416. if (type == TagType.SelfClosing)
  417. sb.Append ("/>");
  418. else
  419. sb.Append (">");
  420. if (retval && sb.Length > 0)
  421. TextParsed (location, sb.ToString ());
  422. return retval;
  423. }
  424. void ParseAttributeTag (string code)
  425. {
  426. AspParser parser = new AspParser ("@@attribute_tag@@", new StringReader (code));
  427. parser.Error += new ParseErrorHandler (ParseError);
  428. parser.TagParsed += new TagParsedHandler (TagParsed);
  429. parser.TextParsed += new TextParsedHandler (TextParsed);
  430. parser.Parse ();
  431. if (text.Length > 0)
  432. FlushText ();
  433. }
  434. #if NET_2_0
  435. void ParsingCompleted ()
  436. {
  437. PageParserFilter pfilter = PageParserFilter;
  438. if (pfilter == null)
  439. return;
  440. pfilter.ParseComplete (rootBuilder);
  441. }
  442. #endif
  443. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  444. {
  445. this.location = new Location (location);
  446. if (tparser != null)
  447. tparser.Location = location;
  448. if (text.Length != 0)
  449. FlushText (lastTag == TagType.CodeRender);
  450. if (0 == String.Compare (tagid, "script", true, CultureInfo.InvariantCulture)) {
  451. bool in_script = (inScript || ignore_text);
  452. if (in_script || (tagtype != TagType.Close && attributes != null)) {
  453. if ((in_script || attributes.IsRunAtServer ()) && ProcessScript (tagtype, attributes))
  454. return;
  455. }
  456. }
  457. lastTag = tagtype;
  458. switch (tagtype) {
  459. case TagType.Directive:
  460. if (tagid.Length == 0)
  461. tagid = tparser.DefaultDirectiveName;
  462. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  463. break;
  464. case TagType.Tag:
  465. if (ProcessTag (location, tagid, attributes, tagtype)) {
  466. useOtherTags = true;
  467. break;
  468. }
  469. if (useOtherTags) {
  470. stack.Builder.EnsureOtherTags ();
  471. stack.Builder.OtherTags.Add (tagid);
  472. }
  473. {
  474. string plainText = location.PlainText;
  475. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.Tag))
  476. TextParsed (location, plainText);
  477. }
  478. break;
  479. case TagType.Close:
  480. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  481. if (!notServer && CloseControl (tagid))
  482. break;
  483. TextParsed (location, location.PlainText);
  484. break;
  485. case TagType.SelfClosing:
  486. int count = stack.Count;
  487. if (!ProcessTag (location, tagid, attributes, tagtype)) {
  488. string plainText = location.PlainText;
  489. if (!ProcessTagsInAttributes (location, tagid, attributes, TagType.SelfClosing))
  490. TextParsed (location, plainText);
  491. } else if (stack.Count != count) {
  492. CloseControl (tagid);
  493. }
  494. break;
  495. case TagType.DataBinding:
  496. goto case TagType.CodeRender;
  497. case TagType.CodeRenderExpression:
  498. goto case TagType.CodeRender;
  499. case TagType.CodeRender:
  500. if (isApplication)
  501. throw new ParseException (location, "Invalid content for application file.");
  502. ProcessCode (tagtype, tagid, location);
  503. break;
  504. case TagType.Include:
  505. if (isApplication)
  506. throw new ParseException (location, "Invalid content for application file.");
  507. string file = attributes ["virtual"] as string;
  508. bool isvirtual = (file != null);
  509. if (!isvirtual)
  510. file = attributes ["file"] as string;
  511. if (isvirtual) {
  512. bool parsed = false;
  513. #if NET_2_0
  514. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  515. if (vpp.FileExists (file)) {
  516. VirtualFile vf = vpp.GetFile (file);
  517. if (vf != null) {
  518. Parse (vf.Open (), file, true);
  519. parsed = true;
  520. }
  521. }
  522. #endif
  523. if (!parsed)
  524. Parse (tparser.MapPath (file), true);
  525. } else {
  526. string includeFilePath = GetIncludeFilePath (tparser.ParserDir, file);
  527. tparser.PushIncludeDir (Path.GetDirectoryName (includeFilePath));
  528. try {
  529. Parse (includeFilePath, true);
  530. } finally {
  531. tparser.PopIncludeDir ();
  532. }
  533. }
  534. break;
  535. default:
  536. break;
  537. }
  538. //PrintLocation (location);
  539. }
  540. static bool TryRemoveTag (string tagid, ArrayList otags)
  541. {
  542. if (otags == null || otags.Count == 0)
  543. return false;
  544. for (int idx = otags.Count - 1; idx >= 0; idx--) {
  545. string otagid = (string) otags [idx];
  546. if (0 == String.Compare (tagid, otagid, true, CultureInfo.InvariantCulture)) {
  547. do {
  548. otags.RemoveAt (idx);
  549. } while (otags.Count - 1 >= idx);
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. static string GetIncludeFilePath (string basedir, string filename)
  556. {
  557. if (Path.DirectorySeparatorChar == '/')
  558. filename = filename.Replace ("\\", "/");
  559. return Path.GetFullPath (Path.Combine (basedir, filename));
  560. }
  561. void TextParsed (ILocation location, string text)
  562. {
  563. if (ignore_text)
  564. return;
  565. if (text.IndexOf ("<%") != -1 && !inScript) {
  566. if (this.text.Length > 0)
  567. FlushText (true);
  568. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  569. r.AddChildren (this);
  570. return;
  571. }
  572. this.text.Append (text);
  573. //PrintLocation (location);
  574. }
  575. void FlushText ()
  576. {
  577. FlushText (false);
  578. }
  579. void FlushText (bool ignoreEmptyString)
  580. {
  581. string t = text.ToString ();
  582. text.Length = 0;
  583. if (ignoreEmptyString && t.Trim ().Length == 0)
  584. return;
  585. if (inScript) {
  586. #if NET_2_0
  587. PageParserFilter pfilter = PageParserFilter;
  588. if (pfilter != null && !pfilter.ProcessCodeConstruct (CodeConstructType.ScriptTag, t))
  589. return;
  590. #endif
  591. tparser.Scripts.Add (new ServerSideScript (t, new System.Web.Compilation.Location (tparser.Location)));
  592. return;
  593. }
  594. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  595. throw new ParseException (location, "Content not valid for application file.");
  596. ControlBuilder current = stack.Builder;
  597. current.AppendLiteralString (t);
  598. if (current.NeedsTagInnerText ()) {
  599. tagInnerText.Append (t);
  600. }
  601. }
  602. #if NET_2_0
  603. bool BuilderHasOtherThan (Type type, ControlBuilder cb)
  604. {
  605. ArrayList al = cb.OtherTags;
  606. if (al != null && al.Count > 0)
  607. return true;
  608. al = cb.Children;
  609. if (al != null) {
  610. ControlBuilder tmp;
  611. foreach (object o in al) {
  612. if (o == null)
  613. continue;
  614. tmp = o as ControlBuilder;
  615. if (tmp == null) {
  616. string s = o as string;
  617. if (s != null && String.IsNullOrEmpty (s.Trim ()))
  618. continue;
  619. return true;
  620. }
  621. if (tmp is System.Web.UI.WebControls.ContentBuilderInternal)
  622. continue;
  623. if (tmp.ControlType != typeof (System.Web.UI.WebControls.Content))
  624. return true;
  625. }
  626. }
  627. return false;
  628. }
  629. bool OtherControlsAllowed (ControlBuilder cb)
  630. {
  631. if (cb == null)
  632. return true;
  633. if (!typeof (System.Web.UI.WebControls.Content).IsAssignableFrom (cb.ControlType))
  634. return true;
  635. if (BuilderHasOtherThan (typeof (System.Web.UI.WebControls.Content), rootBuilder))
  636. return false;
  637. return true;
  638. }
  639. #endif
  640. public void AddControl (Type type, IDictionary attributes)
  641. {
  642. ControlBuilder parent = stack.Builder;
  643. ControlBuilder builder = ControlBuilder.CreateBuilderFromType (tparser, parent, type, null, null,
  644. attributes, location.BeginLine,
  645. location.Filename);
  646. if (builder != null)
  647. parent.AppendSubBuilder (builder);
  648. }
  649. bool ProcessTag (ILocation location, string tagid, TagAttributes atts, TagType tagtype)
  650. {
  651. if (isApplication) {
  652. if (String.Compare (tagid, "object", true, CultureInfo.InvariantCulture) != 0)
  653. throw new ParseException (location, "Invalid tag for application file.");
  654. }
  655. ControlBuilder parent = stack.Builder;
  656. ControlBuilder builder = null;
  657. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  658. if (stack.Count > 1) {
  659. try {
  660. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  661. } catch (TypeLoadException e) {
  662. throw new ParseException (Location, "Type not found.", e);
  663. } catch (Exception e) {
  664. throw new ParseException (Location, e.Message, e);
  665. }
  666. }
  667. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  668. string id = htable ["id"] as string;
  669. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  670. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  671. try {
  672. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  673. } catch (TypeLoadException e) {
  674. throw new ParseException (Location, "Type not found.", e);
  675. } catch (Exception e) {
  676. throw new ParseException (Location, e.Message, e);
  677. }
  678. }
  679. if (builder == null)
  680. return false;
  681. #if NET_2_0
  682. PageParserFilter pfilter = PageParserFilter;
  683. if (pfilter != null && !pfilter.AllowControl (builder.ControlType, builder))
  684. throw new ParseException (Location, "Control type '" + builder.ControlType + "' not allowed.");
  685. if (!OtherControlsAllowed (builder))
  686. throw new ParseException (Location, "Only Content controls are allowed directly in a content page that contains Content controls.");
  687. #endif
  688. builder.Location = location;
  689. builder.ID = htable ["id"] as string;
  690. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  691. if (inForm)
  692. throw new ParseException (location, "Only one <form> allowed.");
  693. inForm = true;
  694. }
  695. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  696. if (builder is TemplateBuilder) {
  697. // push the id list
  698. }
  699. stack.Push (builder, location);
  700. } else {
  701. if (!isApplication && builder is ObjectTagBuilder) {
  702. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  703. if (ot.Scope != null && ot.Scope != "")
  704. throw new ParseException (location, "Scope not allowed here");
  705. if (tagtype == TagType.Tag) {
  706. stack.Push (builder, location);
  707. return true;
  708. }
  709. }
  710. parent.AppendSubBuilder (builder);
  711. builder.CloseControl ();
  712. }
  713. return true;
  714. }
  715. string ReadFile (string filename)
  716. {
  717. string realpath = tparser.MapPath (filename);
  718. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  719. string content = sr.ReadToEnd ();
  720. return content;
  721. }
  722. }
  723. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  724. {
  725. if (tagtype != TagType.Close) {
  726. if (attributes != null && attributes.IsRunAtServer ()) {
  727. string language = (string) attributes ["language"];
  728. if (language != null && language.Length > 0 && tparser.ImplicitLanguage)
  729. tparser.SetLanguage (language);
  730. CheckLanguage (language);
  731. string src = (string) attributes ["src"];
  732. if (src != null) {
  733. if (src == "")
  734. throw new ParseException (Parser,
  735. "src cannot be an empty string");
  736. string content = ReadFile (src);
  737. inScript = true;
  738. TextParsed (Parser, content);
  739. FlushText ();
  740. inScript = false;
  741. if (tagtype != TagType.SelfClosing) {
  742. ignore_text = true;
  743. Parser.VerbatimID = "script";
  744. }
  745. } else if (tagtype == TagType.Tag) {
  746. Parser.VerbatimID = "script";
  747. inScript = true;
  748. }
  749. return true;
  750. } else {
  751. if (tagtype != TagType.SelfClosing) {
  752. Parser.VerbatimID = "script";
  753. javascript = true;
  754. }
  755. TextParsed (location, location.PlainText);
  756. return true;
  757. }
  758. }
  759. bool result;
  760. if (inScript) {
  761. result = inScript;
  762. inScript = false;
  763. } else if (!ignore_text) {
  764. result = javascript;
  765. javascript = false;
  766. TextParsed (location, location.PlainText);
  767. } else {
  768. ignore_text = false;
  769. result = true;
  770. }
  771. return result;
  772. }
  773. bool CloseControl (string tagid)
  774. {
  775. ControlBuilder current = stack.Builder;
  776. string btag = current.OriginalTagName;
  777. if (String.Compare (btag, "tbody", true, CultureInfo.InvariantCulture) != 0 &&
  778. String.Compare (tagid, "tbody", true, CultureInfo.InvariantCulture) == 0) {
  779. if (!current.ChildrenAsProperties) {
  780. try {
  781. TextParsed (location, location.PlainText);
  782. FlushText ();
  783. } catch {}
  784. }
  785. return true;
  786. }
  787. if (0 != String.Compare (tagid, btag, true, CultureInfo.InvariantCulture))
  788. return false;
  789. // if (current is TemplateBuilder)
  790. // pop from the id list
  791. if (current.NeedsTagInnerText ()) {
  792. try {
  793. current.SetTagInnerText (tagInnerText.ToString ());
  794. } catch (Exception e) {
  795. throw new ParseException (current.Location, e.Message, e);
  796. }
  797. tagInnerText.Length = 0;
  798. }
  799. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  800. inForm = false;
  801. }
  802. current.CloseControl ();
  803. stack.Pop ();
  804. stack.Builder.AppendSubBuilder (current);
  805. return true;
  806. }
  807. #if NET_2_0
  808. CodeConstructType MapTagTypeToConstructType (TagType tagtype)
  809. {
  810. switch (tagtype) {
  811. case TagType.DataBinding:
  812. return CodeConstructType.ExpressionSnippet;
  813. case TagType.CodeRender:
  814. return CodeConstructType.CodeSnippet;
  815. case TagType.CodeRenderExpression:
  816. return CodeConstructType.DataBindingSnippet;
  817. default:
  818. throw new InvalidOperationException ("Unexpected tag type.");
  819. }
  820. }
  821. #endif
  822. bool ProcessCode (TagType tagtype, string code, ILocation location)
  823. {
  824. #if NET_2_0
  825. PageParserFilter pfilter = PageParserFilter;
  826. if (pfilter != null && (!pfilter.AllowCode || !pfilter.ProcessCodeConstruct (MapTagTypeToConstructType (tagtype), code)))
  827. return true;
  828. #endif
  829. ControlBuilder b = null;
  830. if (tagtype == TagType.CodeRender)
  831. b = new CodeRenderBuilder (code, false, location);
  832. else if (tagtype == TagType.CodeRenderExpression)
  833. b = new CodeRenderBuilder (code, true, location);
  834. else if (tagtype == TagType.DataBinding)
  835. b = new DataBindingBuilder (code, location);
  836. else
  837. throw new HttpException ("Should never happen");
  838. stack.Builder.AppendSubBuilder (b);
  839. return true;
  840. }
  841. public ILocation Location {
  842. get { return location; }
  843. }
  844. void CheckLanguage (string lang)
  845. {
  846. if (lang == null || lang == "")
  847. return;
  848. if (String.Compare (lang, tparser.Language, true, CultureInfo.InvariantCulture) == 0)
  849. return;
  850. #if NET_2_0
  851. CompilationSection section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  852. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  853. #else
  854. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  855. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
  856. #endif
  857. throw new ParseException (Location,
  858. String.Format ("Trying to mix language '{0}' and '{1}'.",
  859. tparser.Language, lang));
  860. }
  861. // Used to get CodeRender tags in attribute values
  862. class CodeRenderParser
  863. {
  864. string str;
  865. ControlBuilder builder;
  866. AspGenerator generator;
  867. public CodeRenderParser (string str, ControlBuilder builder)
  868. {
  869. this.str = str;
  870. this.builder = builder;
  871. }
  872. public void AddChildren (AspGenerator generator)
  873. {
  874. this.generator = generator;
  875. int index = str.IndexOf ("<%");
  876. if (index > 0) {
  877. TextParsed (null, str.Substring (0, index));
  878. str = str.Substring (index);
  879. }
  880. AspParser parser = new AspParser ("@@nested_tag@@", new StringReader (str));
  881. parser.Error += new ParseErrorHandler (ParseError);
  882. parser.TagParsed += new TagParsedHandler (TagParsed);
  883. parser.TextParsed += new TextParsedHandler (TextParsed);
  884. parser.Parse ();
  885. }
  886. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  887. {
  888. switch (tagtype) {
  889. case TagType.CodeRender:
  890. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  891. break;
  892. case TagType.CodeRenderExpression:
  893. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  894. break;
  895. case TagType.DataBinding:
  896. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  897. break;
  898. case TagType.Tag:
  899. case TagType.SelfClosing:
  900. if (generator != null)
  901. generator.TagParsed (location, tagtype, tagid, attributes);
  902. else
  903. goto default;
  904. break;
  905. default:
  906. builder.AppendLiteralString (location.PlainText);
  907. break;
  908. }
  909. }
  910. void TextParsed (ILocation location, string text)
  911. {
  912. builder.AppendLiteralString (text);
  913. }
  914. void ParseError (ILocation location, string message)
  915. {
  916. throw new ParseException (location, message);
  917. }
  918. }
  919. }
  920. }