AspGenerator.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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.IO;
  34. using System.Text;
  35. using System.Web.Caching;
  36. using System.Web.Configuration;
  37. using System.Web.UI;
  38. using System.Web.UI.HtmlControls;
  39. using System.Web.Util;
  40. namespace System.Web.Compilation
  41. {
  42. class BuilderLocation
  43. {
  44. public ControlBuilder Builder;
  45. public ILocation Location;
  46. public BuilderLocation (ControlBuilder builder, ILocation location)
  47. {
  48. this.Builder = builder;
  49. this.Location = location;
  50. }
  51. }
  52. class BuilderLocationStack : Stack
  53. {
  54. public override void Push (object o)
  55. {
  56. if (!(o is BuilderLocation))
  57. throw new InvalidOperationException ();
  58. base.Push (o);
  59. }
  60. public virtual void Push (ControlBuilder builder, ILocation location)
  61. {
  62. BuilderLocation bl = new BuilderLocation (builder, location);
  63. Push (bl);
  64. }
  65. public new BuilderLocation Peek ()
  66. {
  67. return (BuilderLocation) base.Peek ();
  68. }
  69. public new BuilderLocation Pop ()
  70. {
  71. return (BuilderLocation) base.Pop ();
  72. }
  73. public ControlBuilder Builder {
  74. get { return Peek ().Builder; }
  75. }
  76. }
  77. class ParserStack
  78. {
  79. Hashtable files;
  80. Stack parsers;
  81. AspParser current;
  82. public ParserStack ()
  83. {
  84. files = new Hashtable (); // may be this should be case sensitive for windows
  85. parsers = new Stack ();
  86. }
  87. public bool Push (AspParser parser)
  88. {
  89. if (files.Contains (parser.Filename))
  90. return false;
  91. files [parser.Filename] = true;
  92. parsers.Push (parser);
  93. current = parser;
  94. return true;
  95. }
  96. public AspParser Pop ()
  97. {
  98. if (parsers.Count == 0)
  99. return null;
  100. files.Remove (current.Filename);
  101. AspParser result = (AspParser) parsers.Pop ();
  102. if (parsers.Count > 0)
  103. current = (AspParser) parsers.Peek ();
  104. else
  105. current = null;
  106. return result;
  107. }
  108. public AspParser Parser {
  109. get { return current; }
  110. }
  111. public string Filename {
  112. get { return current.Filename; }
  113. }
  114. }
  115. class TagStack
  116. {
  117. Stack tags;
  118. public TagStack ()
  119. {
  120. tags = new Stack ();
  121. }
  122. public void Push (string tagid)
  123. {
  124. tags.Push (tagid);
  125. }
  126. public string Pop ()
  127. {
  128. if (tags.Count == 0)
  129. return null;
  130. return (string) tags.Pop ();
  131. }
  132. public bool CompareTo (string tagid)
  133. {
  134. if (tags.Count == 0)
  135. return false;
  136. return 0 == String.Compare (tagid, (string) tags.Peek (), true);
  137. }
  138. public int Count {
  139. get { return tags.Count; }
  140. }
  141. public string Current {
  142. get { return (string) tags.Peek (); }
  143. }
  144. }
  145. class AspGenerator
  146. {
  147. ParserStack pstack;
  148. BuilderLocationStack stack;
  149. TemplateParser tparser;
  150. StringBuilder text;
  151. RootBuilder rootBuilder;
  152. bool inScript, javascript, ignore_text;
  153. ILocation location;
  154. bool isApplication;
  155. StringBuilder tagInnerText = new StringBuilder ();
  156. static Hashtable emptyHash = new Hashtable ();
  157. bool inForm;
  158. bool useOtherTags;
  159. public AspGenerator (TemplateParser tparser)
  160. {
  161. this.tparser = tparser;
  162. text = new StringBuilder ();
  163. stack = new BuilderLocationStack ();
  164. rootBuilder = new RootBuilder (tparser);
  165. stack.Push (rootBuilder, null);
  166. tparser.RootBuilder = rootBuilder;
  167. pstack = new ParserStack ();
  168. }
  169. public AspParser Parser {
  170. get { return pstack.Parser; }
  171. }
  172. public string Filename {
  173. get { return pstack.Filename; }
  174. }
  175. BaseCompiler GetCompilerFromType ()
  176. {
  177. Type type = tparser.GetType ();
  178. if (type == typeof (PageParser))
  179. return new PageCompiler ((PageParser) tparser);
  180. if (type == typeof (ApplicationFileParser))
  181. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  182. if (type == typeof (UserControlParser))
  183. return new UserControlCompiler ((UserControlParser) tparser);
  184. #if NET_2_0
  185. if (type == typeof(MasterPageParser))
  186. return new UserControlCompiler ((UserControlParser) tparser);
  187. #endif
  188. throw new Exception ("Got type: " + type);
  189. }
  190. void InitParser (string filename)
  191. {
  192. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  193. AspParser parser = new AspParser (filename, reader);
  194. reader.Close ();
  195. parser.Error += new ParseErrorHandler (ParseError);
  196. parser.TagParsed += new TagParsedHandler (TagParsed);
  197. parser.TextParsed += new TextParsedHandler (TextParsed);
  198. if (!pstack.Push (parser))
  199. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  200. tparser.AddDependency (filename);
  201. }
  202. void DoParse ()
  203. {
  204. pstack.Parser.Parse ();
  205. if (text.Length > 0)
  206. FlushText ();
  207. pstack.Pop ();
  208. }
  209. public Type GetCompiledType ()
  210. {
  211. Type type = (Type) HttpRuntime.Cache.Get ("@@Type" + tparser.InputFile);
  212. if (type != null) {
  213. return type;
  214. }
  215. isApplication = tparser.DefaultDirectiveName == "application";
  216. InitParser (Path.GetFullPath (tparser.InputFile));
  217. DoParse ();
  218. #if DEBUG
  219. PrintTree (rootBuilder, 0);
  220. #endif
  221. if (stack.Count > 1)
  222. throw new ParseException (stack.Builder.location,
  223. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  224. BaseCompiler compiler = GetCompilerFromType ();
  225. type = compiler.GetCompiledType ();
  226. CacheDependency cd = new CacheDependency ((string[])
  227. tparser.Dependencies.ToArray (typeof (string)));
  228. HttpRuntime.Cache.InsertPrivate ("@@Type" + tparser.InputFile, type, cd);
  229. return type;
  230. }
  231. #if DEBUG
  232. static void PrintTree (ControlBuilder builder, int indent)
  233. {
  234. if (builder == null)
  235. return;
  236. string i = new string ('\t', indent);
  237. Console.Write (i);
  238. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  239. builder, builder.ID, builder.ControlType, builder.parentBuilder);
  240. if (builder.Children != null)
  241. foreach (object o in builder.Children) {
  242. if (o is ControlBuilder)
  243. PrintTree ((ControlBuilder) o, indent++);
  244. }
  245. }
  246. static void PrintLocation (ILocation loc)
  247. {
  248. Console.WriteLine ("\tFile name: " + loc.Filename);
  249. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  250. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  251. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  252. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  253. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  254. Console.WriteLine ();
  255. }
  256. #endif
  257. void ParseError (ILocation location, string message)
  258. {
  259. throw new ParseException (location, message);
  260. }
  261. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  262. {
  263. this.location = new Location (location);
  264. if (tparser != null)
  265. tparser.Location = location;
  266. // MS ignores tbody/thead
  267. if ((attributes == null || !attributes.IsRunAtServer ())) {
  268. if (String.Compare (tagid, "tbody", true) == 0 ||
  269. String.Compare (tagid, "thead", true) == 0)
  270. return;
  271. }
  272. if (text.Length != 0)
  273. FlushText ();
  274. if (0 == String.Compare (tagid, "script", true)) {
  275. bool in_script = (inScript || ignore_text);
  276. if (in_script || (tagtype != TagType.Close && attributes != null)) {
  277. if ((in_script || attributes.IsRunAtServer ()) && ProcessScript (tagtype, attributes))
  278. return;
  279. }
  280. }
  281. switch (tagtype) {
  282. case TagType.Directive:
  283. if (tagid == "")
  284. tagid = tparser.DefaultDirectiveName;
  285. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  286. break;
  287. case TagType.Tag:
  288. if (ProcessTag (tagid, attributes, tagtype)) {
  289. useOtherTags = true;
  290. break;
  291. }
  292. if (useOtherTags) {
  293. stack.Builder.EnsureOtherTags ();
  294. stack.Builder.OtherTags.Add (tagid);
  295. }
  296. TextParsed (location, location.PlainText);
  297. break;
  298. case TagType.Close:
  299. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  300. if (!notServer && CloseControl (tagid))
  301. break;
  302. TextParsed (location, location.PlainText);
  303. break;
  304. case TagType.SelfClosing:
  305. int count = stack.Count;
  306. if (!ProcessTag (tagid, attributes, tagtype)) {
  307. TextParsed (location, location.PlainText);
  308. } else if (stack.Count != count) {
  309. CloseControl (tagid);
  310. }
  311. break;
  312. case TagType.DataBinding:
  313. goto case TagType.CodeRender;
  314. case TagType.CodeRenderExpression:
  315. goto case TagType.CodeRender;
  316. case TagType.CodeRender:
  317. if (isApplication)
  318. throw new ParseException (location, "Invalid content for application file.");
  319. ProcessCode (tagtype, tagid, location);
  320. break;
  321. case TagType.Include:
  322. if (isApplication)
  323. throw new ParseException (location, "Invalid content for application file.");
  324. string file = attributes ["virtual"] as string;
  325. bool isvirtual = (file != null);
  326. if (!isvirtual)
  327. file = attributes ["file"] as string;
  328. if (isvirtual) {
  329. file = tparser.MapPath (file);
  330. } else {
  331. file = GetIncludeFilePath (tparser.BaseDir, file);
  332. }
  333. InitParser (file);
  334. DoParse ();
  335. break;
  336. default:
  337. break;
  338. }
  339. //PrintLocation (location);
  340. }
  341. static bool TryRemoveTag (string tagid, ArrayList otags)
  342. {
  343. if (otags == null || otags.Count == 0)
  344. return false;
  345. int idx = otags.Count - 1;
  346. string otagid = (string) otags [idx];
  347. if (0 != String.Compare (tagid, otagid, true))
  348. return false;
  349. otags.RemoveAt (idx);
  350. return true;
  351. }
  352. static string GetIncludeFilePath (string basedir, string filename)
  353. {
  354. if (Path.DirectorySeparatorChar == '/')
  355. filename = filename.Replace ("\\", "/");
  356. return Path.GetFullPath (Path.Combine (basedir, filename));
  357. }
  358. void TextParsed (ILocation location, string text)
  359. {
  360. if (ignore_text)
  361. return;
  362. if (text.IndexOf ("<%") != -1 && !inScript) {
  363. if (this.text.Length > 0)
  364. FlushText ();
  365. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  366. r.AddChildren ();
  367. return;
  368. }
  369. this.text.Append (text);
  370. //PrintLocation (location);
  371. }
  372. void FlushText ()
  373. {
  374. string t = text.ToString ();
  375. text.Length = 0;
  376. if (inScript) {
  377. // TODO: store location
  378. tparser.Scripts.Add (t);
  379. return;
  380. }
  381. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  382. throw new ParseException (location, "Content not valid for application file.");
  383. ControlBuilder current = stack.Builder;
  384. current.AppendLiteralString (t);
  385. if (current.NeedsTagInnerText ()) {
  386. tagInnerText.Append (t);
  387. }
  388. }
  389. bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
  390. {
  391. if (isApplication) {
  392. if (String.Compare (tagid, "object", true) != 0)
  393. throw new ParseException (location, "Invalid tag for application file.");
  394. }
  395. ControlBuilder parent = stack.Builder;
  396. ControlBuilder builder = null;
  397. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  398. if (stack.Count > 1) {
  399. try {
  400. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  401. } catch (TypeLoadException e) {
  402. throw new ParseException (Location, "Type not found.", e);
  403. } catch (Exception e) {
  404. throw new ParseException (Location, e.Message, e);
  405. }
  406. }
  407. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  408. string id = htable ["id"] as string;
  409. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  410. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  411. try {
  412. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  413. } catch (TypeLoadException e) {
  414. throw new ParseException (Location, "Type not found.", e);
  415. } catch (Exception e) {
  416. throw new ParseException (Location, e.Message, e);
  417. }
  418. }
  419. if (builder == null)
  420. return false;
  421. builder.location = location;
  422. builder.ID = htable ["id"] as string;
  423. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  424. if (inForm)
  425. throw new ParseException (location, "Only one <form> allowed.");
  426. inForm = true;
  427. }
  428. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  429. if (builder is TemplateBuilder) {
  430. // push the id list
  431. }
  432. stack.Push (builder, location);
  433. } else {
  434. if (!isApplication && builder is ObjectTagBuilder) {
  435. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  436. if (ot.Scope != null && ot.Scope != "")
  437. throw new ParseException (location, "Scope not allowed here");
  438. if (tagtype == TagType.Tag) {
  439. stack.Push (builder, location);
  440. return true;
  441. }
  442. }
  443. parent.AppendSubBuilder (builder);
  444. builder.CloseControl ();
  445. }
  446. return true;
  447. }
  448. string ReadFile (string filename)
  449. {
  450. string realpath = tparser.MapPath (filename);
  451. using (StreamReader sr = new StreamReader (realpath, WebEncoding.FileEncoding)) {
  452. string content = sr.ReadToEnd ();
  453. return content;
  454. }
  455. }
  456. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  457. {
  458. if (tagtype != TagType.Close) {
  459. if (attributes != null && attributes.IsRunAtServer ()) {
  460. CheckLanguage ((string) attributes ["language"]);
  461. string src = (string) attributes ["src"];
  462. if (src != null) {
  463. if (src == "")
  464. throw new ParseException (Parser,
  465. "src cannot be an empty string");
  466. string content = ReadFile (src);
  467. inScript = true;
  468. TextParsed (Parser, content);
  469. FlushText ();
  470. inScript = false;
  471. if (tagtype != TagType.SelfClosing) {
  472. ignore_text = true;
  473. Parser.VerbatimID = "script";
  474. }
  475. } else if (tagtype == TagType.Tag) {
  476. Parser.VerbatimID = "script";
  477. inScript = true;
  478. }
  479. return true;
  480. } else {
  481. if (tagtype != TagType.SelfClosing) {
  482. Parser.VerbatimID = "script";
  483. javascript = true;
  484. }
  485. TextParsed (location, location.PlainText);
  486. return true;
  487. }
  488. }
  489. bool result;
  490. if (inScript) {
  491. result = inScript;
  492. inScript = false;
  493. } else if (!ignore_text) {
  494. result = javascript;
  495. javascript = false;
  496. TextParsed (location, location.PlainText);
  497. } else {
  498. ignore_text = false;
  499. result = true;
  500. }
  501. return result;
  502. }
  503. bool CloseControl (string tagid)
  504. {
  505. ControlBuilder current = stack.Builder;
  506. string btag = current.TagName;
  507. if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
  508. if (!current.ChildrenAsProperties) {
  509. try {
  510. TextParsed (location, location.PlainText);
  511. FlushText ();
  512. } catch {}
  513. }
  514. return true;
  515. }
  516. if (0 != String.Compare (tagid, btag, true))
  517. return false;
  518. // if (current is TemplateBuilder)
  519. // pop from the id list
  520. if (current.NeedsTagInnerText ()) {
  521. try {
  522. current.SetTagInnerText (tagInnerText.ToString ());
  523. } catch (Exception e) {
  524. throw new ParseException (current.location, e.Message, e);
  525. }
  526. tagInnerText.Length = 0;
  527. }
  528. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  529. inForm = false;
  530. }
  531. current.CloseControl ();
  532. stack.Pop ();
  533. stack.Builder.AppendSubBuilder (current);
  534. return true;
  535. }
  536. bool ProcessCode (TagType tagtype, string code, ILocation location)
  537. {
  538. ControlBuilder b = null;
  539. if (tagtype == TagType.CodeRender)
  540. b = new CodeRenderBuilder (code, false, location);
  541. else if (tagtype == TagType.CodeRenderExpression)
  542. b = new CodeRenderBuilder (code, true, location);
  543. else if (tagtype == TagType.DataBinding)
  544. b = new DataBindingBuilder (code, location);
  545. else
  546. throw new HttpException ("Should never happen");
  547. stack.Builder.AppendSubBuilder (b);
  548. return true;
  549. }
  550. public ILocation Location {
  551. get { return location; }
  552. }
  553. void CheckLanguage (string lang)
  554. {
  555. if (lang == null || lang == "")
  556. return;
  557. if (String.Compare (lang, tparser.Language, true) == 0)
  558. return;
  559. #if CONFIGURATION_2_0
  560. CompilationSection section = (CompilationSection) WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
  561. if (section.Compilers[tparser.Language] != section.Compilers[lang])
  562. #else
  563. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  564. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang))
  565. #endif
  566. throw new ParseException (Location,
  567. String.Format ("Trying to mix language '{0}' and '{1}'.",
  568. tparser.Language, lang));
  569. }
  570. // Used to get CodeRender tags in attribute values
  571. class CodeRenderParser
  572. {
  573. string str;
  574. ControlBuilder builder;
  575. public CodeRenderParser (string str, ControlBuilder builder)
  576. {
  577. this.str = str;
  578. this.builder = builder;
  579. }
  580. public void AddChildren ()
  581. {
  582. int index = str.IndexOf ("<%");
  583. if (index > 0) {
  584. TextParsed (null, str.Substring (0, index));
  585. str = str.Substring (index);
  586. }
  587. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  588. parser.Error += new ParseErrorHandler (ParseError);
  589. parser.TagParsed += new TagParsedHandler (TagParsed);
  590. parser.TextParsed += new TextParsedHandler (TextParsed);
  591. parser.Parse ();
  592. }
  593. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  594. {
  595. if (tagtype == TagType.CodeRender)
  596. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  597. else if (tagtype == TagType.CodeRenderExpression)
  598. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  599. else if (tagtype == TagType.DataBinding)
  600. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  601. else
  602. builder.AppendLiteralString (location.PlainText);
  603. }
  604. void TextParsed (ILocation location, string text)
  605. {
  606. builder.AppendLiteralString (text);
  607. }
  608. void ParseError (ILocation location, string message)
  609. {
  610. throw new ParseException (location, message);
  611. }
  612. }
  613. }
  614. }