AspGenerator.cs 19 KB

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