AspGenerator.cs 19 KB

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