AspGenerator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.CodeDom.Compiler;
  32. using System.IO;
  33. using System.Text;
  34. using System.Web.Caching;
  35. using System.Web.UI;
  36. using System.Web.UI.HtmlControls;
  37. using System.Web.Util;
  38. namespace System.Web.Compilation
  39. {
  40. class BuilderLocation
  41. {
  42. public ControlBuilder Builder;
  43. public ILocation Location;
  44. public BuilderLocation (ControlBuilder builder, ILocation location)
  45. {
  46. this.Builder = builder;
  47. this.Location = location;
  48. }
  49. }
  50. class BuilderLocationStack : Stack
  51. {
  52. public override void Push (object o)
  53. {
  54. if (!(o is BuilderLocation))
  55. throw new InvalidOperationException ();
  56. base.Push (o);
  57. }
  58. public virtual void Push (ControlBuilder builder, ILocation location)
  59. {
  60. BuilderLocation bl = new BuilderLocation (builder, location);
  61. Push (bl);
  62. }
  63. public new BuilderLocation Peek ()
  64. {
  65. return (BuilderLocation) base.Peek ();
  66. }
  67. public new BuilderLocation Pop ()
  68. {
  69. return (BuilderLocation) base.Pop ();
  70. }
  71. public ControlBuilder Builder {
  72. get { return Peek ().Builder; }
  73. }
  74. }
  75. class ParserStack
  76. {
  77. Hashtable files;
  78. Stack parsers;
  79. AspParser current;
  80. public ParserStack ()
  81. {
  82. files = new Hashtable (); // may be this should be case sensitive for windows
  83. parsers = new Stack ();
  84. }
  85. public bool Push (AspParser parser)
  86. {
  87. if (files.Contains (parser.Filename))
  88. return false;
  89. files [parser.Filename] = true;
  90. parsers.Push (parser);
  91. current = parser;
  92. return true;
  93. }
  94. public AspParser Pop ()
  95. {
  96. if (parsers.Count == 0)
  97. return null;
  98. files.Remove (current.Filename);
  99. AspParser result = (AspParser) parsers.Pop ();
  100. if (parsers.Count > 0)
  101. current = (AspParser) parsers.Peek ();
  102. else
  103. current = null;
  104. return result;
  105. }
  106. public AspParser Parser {
  107. get { return current; }
  108. }
  109. public string Filename {
  110. get { return current.Filename; }
  111. }
  112. }
  113. class TagStack
  114. {
  115. Stack tags;
  116. public TagStack ()
  117. {
  118. tags = new Stack ();
  119. }
  120. public void Push (string tagid)
  121. {
  122. tags.Push (tagid);
  123. }
  124. public string Pop ()
  125. {
  126. if (tags.Count == 0)
  127. return null;
  128. return (string) tags.Pop ();
  129. }
  130. public bool CompareTo (string tagid)
  131. {
  132. if (tags.Count == 0)
  133. return false;
  134. return 0 == String.Compare (tagid, (string) tags.Peek (), true);
  135. }
  136. public int Count {
  137. get { return tags.Count; }
  138. }
  139. public string Current {
  140. get { return (string) tags.Peek (); }
  141. }
  142. }
  143. class AspGenerator
  144. {
  145. ParserStack pstack;
  146. BuilderLocationStack stack;
  147. TemplateParser tparser;
  148. StringBuilder text;
  149. RootBuilder rootBuilder;
  150. bool inScript, javascript;
  151. ILocation location;
  152. bool isApplication;
  153. StringBuilder tagInnerText = new StringBuilder ();
  154. static Hashtable emptyHash = new Hashtable ();
  155. bool inForm;
  156. TagStack formTags;
  157. public AspGenerator (TemplateParser tparser)
  158. {
  159. this.tparser = tparser;
  160. tparser.AddDependency (tparser.InputFile);
  161. text = new StringBuilder ();
  162. stack = new BuilderLocationStack ();
  163. rootBuilder = new RootBuilder (tparser);
  164. stack.Push (rootBuilder, null);
  165. tparser.RootBuilder = rootBuilder;
  166. pstack = new ParserStack ();
  167. }
  168. public AspParser Parser {
  169. get { return pstack.Parser; }
  170. }
  171. public string Filename {
  172. get { return pstack.Filename; }
  173. }
  174. BaseCompiler GetCompilerFromType ()
  175. {
  176. Type type = tparser.GetType ();
  177. if (type == typeof (PageParser))
  178. return new PageCompiler ((PageParser) tparser);
  179. if (type == typeof (ApplicationFileParser))
  180. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  181. if (type == typeof (UserControlParser))
  182. return new UserControlCompiler ((UserControlParser) tparser);
  183. #if NET_2_0
  184. if (type == typeof(MasterPageParser))
  185. return new UserControlCompiler ((UserControlParser) tparser);
  186. #endif
  187. throw new Exception ("Got type: " + type);
  188. }
  189. void InitParser (string filename)
  190. {
  191. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  192. AspParser parser = new AspParser (filename, reader);
  193. reader.Close ();
  194. parser.Error += new ParseErrorHandler (ParseError);
  195. parser.TagParsed += new TagParsedHandler (TagParsed);
  196. parser.TextParsed += new TextParsedHandler (TextParsed);
  197. if (!pstack.Push (parser))
  198. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  199. tparser.AddDependency (filename);
  200. }
  201. void DoParse ()
  202. {
  203. pstack.Parser.Parse ();
  204. if (text.Length > 0)
  205. FlushText ();
  206. pstack.Pop ();
  207. }
  208. public Type GetCompiledType ()
  209. {
  210. Type type = (Type) HttpRuntime.Cache.Get ("@@Type" + tparser.InputFile);
  211. if (type != null) {
  212. return type;
  213. }
  214. isApplication = tparser.DefaultDirectiveName == "application";
  215. InitParser (Path.GetFullPath (tparser.InputFile));
  216. DoParse ();
  217. #if DEBUG
  218. PrintTree (rootBuilder, 0);
  219. #endif
  220. if (stack.Count > 1)
  221. throw new ParseException (stack.Builder.location,
  222. "Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
  223. BaseCompiler compiler = GetCompilerFromType ();
  224. type = compiler.GetCompiledType ();
  225. CacheDependency cd = new CacheDependency ((string[])
  226. tparser.Dependencies.ToArray (typeof (string)));
  227. HttpRuntime.Cache.Insert ("@@Type" + tparser.InputFile, type, cd);
  228. return type;
  229. }
  230. #if DEBUG
  231. static void PrintTree (ControlBuilder builder, int indent)
  232. {
  233. if (builder == null)
  234. return;
  235. string i = new string ('\t', indent);
  236. Console.Write (i);
  237. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  238. builder, builder.ID, builder.ControlType, builder.parentBuilder);
  239. if (builder.Children != null)
  240. foreach (object o in builder.Children) {
  241. if (o is ControlBuilder)
  242. PrintTree ((ControlBuilder) o, indent++);
  243. }
  244. }
  245. #endif
  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. void ParseError (ILocation location, string message)
  257. {
  258. throw new ParseException (location, message);
  259. }
  260. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  261. {
  262. this.location = new Location (location);
  263. if (tparser != null)
  264. tparser.Location = location;
  265. if (text.Length != 0)
  266. FlushText ();
  267. if (0 == String.Compare (tagid, "script", true)) {
  268. if (ProcessScript (tagtype, attributes))
  269. return;
  270. }
  271. switch (tagtype) {
  272. case TagType.Directive:
  273. if (tagid == "")
  274. tagid = tparser.DefaultDirectiveName;
  275. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  276. break;
  277. case TagType.Tag:
  278. if (ProcessTag (tagid, attributes, tagtype))
  279. break;
  280. if (inForm) {
  281. stack.Builder.EnsureOtherTags ();
  282. stack.Builder.OtherTags.Add (tagid);
  283. }
  284. TextParsed (location, location.PlainText);
  285. break;
  286. case TagType.Close:
  287. bool notServer = (inForm && TryRemoveTag (tagid, stack.Builder.OtherTags));
  288. if (!notServer && CloseControl (tagid))
  289. break;
  290. TextParsed (location, location.PlainText);
  291. break;
  292. case TagType.SelfClosing:
  293. int count = stack.Count;
  294. if (!ProcessTag (tagid, attributes, tagtype)) {
  295. TextParsed (location, location.PlainText);
  296. } else if (stack.Count != count) {
  297. CloseControl (tagid);
  298. }
  299. break;
  300. case TagType.DataBinding:
  301. goto case TagType.CodeRender;
  302. case TagType.CodeRenderExpression:
  303. goto case TagType.CodeRender;
  304. case TagType.CodeRender:
  305. if (isApplication)
  306. throw new ParseException (location, "Invalid content for application file.");
  307. ProcessCode (tagtype, tagid, location);
  308. break;
  309. case TagType.Include:
  310. if (isApplication)
  311. throw new ParseException (location, "Invalid content for application file.");
  312. string file = attributes ["virtual"] as string;
  313. bool isvirtual = (file != null);
  314. if (!isvirtual)
  315. file = attributes ["file"] as string;
  316. if (isvirtual) {
  317. file = tparser.MapPath (file);
  318. } else {
  319. file = GetIncludeFilePath (tparser.BaseDir, file);
  320. }
  321. InitParser (file);
  322. DoParse ();
  323. break;
  324. default:
  325. break;
  326. }
  327. //PrintLocation (location);
  328. }
  329. static bool TryRemoveTag (string tagid, ArrayList otags)
  330. {
  331. if (otags == null || otags.Count == 0)
  332. return false;
  333. int idx = otags.Count - 1;
  334. string otagid = (string) otags [idx];
  335. if (0 != String.Compare (tagid, otagid, true))
  336. return false;
  337. otags.RemoveAt (idx);
  338. return true;
  339. }
  340. static string GetIncludeFilePath (string basedir, string filename)
  341. {
  342. if (Path.DirectorySeparatorChar == '/')
  343. filename = filename.Replace ("\\", "/");
  344. return Path.GetFullPath (Path.Combine (basedir, filename));
  345. }
  346. void TextParsed (ILocation location, string text)
  347. {
  348. if (text.IndexOf ("<%") != -1 && !inScript) {
  349. if (this.text.Length > 0)
  350. FlushText ();
  351. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  352. r.AddChildren ();
  353. return;
  354. }
  355. this.text.Append (text);
  356. //PrintLocation (location);
  357. }
  358. void FlushText ()
  359. {
  360. string t = text.ToString ();
  361. text.Length = 0;
  362. if (inScript) {
  363. // TODO: store location
  364. tparser.Scripts.Add (t);
  365. return;
  366. }
  367. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  368. throw new ParseException (location, "Content not valid for application file.");
  369. ControlBuilder current = stack.Builder;
  370. current.AppendLiteralString (t);
  371. if (current.NeedsTagInnerText ()) {
  372. tagInnerText.Append (t);
  373. }
  374. }
  375. bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
  376. {
  377. if ((atts == null || !atts.IsRunAtServer ()) && String.Compare (tagid, "tbody", true) == 0) {
  378. // MS completely ignores tbody or, if runat="server", fails when compiling
  379. if (stack.Count > 0)
  380. return stack.Builder.ChildrenAsProperties;
  381. return false;
  382. }
  383. if (isApplication) {
  384. if (String.Compare (tagid, "object", true) != 0)
  385. throw new ParseException (location, "Invalid tag for application file.");
  386. }
  387. ControlBuilder parent = stack.Builder;
  388. ControlBuilder builder = null;
  389. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  390. if (stack.Count > 1) {
  391. try {
  392. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  393. } catch (TypeLoadException e) {
  394. throw new ParseException (Location, "Type not found.", e);
  395. } catch (Exception e) {
  396. throw new ParseException (Location, e.Message, e);
  397. }
  398. }
  399. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  400. string id = htable ["id"] as string;
  401. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  402. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  403. try {
  404. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  405. } catch (TypeLoadException e) {
  406. throw new ParseException (Location, "Type not found.", e);
  407. } catch (Exception e) {
  408. throw new ParseException (Location, e.Message, e);
  409. }
  410. }
  411. if (builder == null)
  412. return false;
  413. builder.location = location;
  414. builder.ID = htable ["id"] as string;
  415. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  416. if (inForm)
  417. throw new ParseException (location, "Only one <form> allowed.");
  418. inForm = true;
  419. formTags = new TagStack ();
  420. }
  421. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  422. if (builder is TemplateBuilder) {
  423. // push the id list
  424. }
  425. stack.Push (builder, location);
  426. } else {
  427. if (!isApplication && builder is ObjectTagBuilder) {
  428. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  429. if (ot.Scope != null && ot.Scope != "")
  430. throw new ParseException (location, "Scope not allowed here");
  431. if (tagtype == TagType.Tag) {
  432. stack.Push (builder, location);
  433. return true;
  434. }
  435. }
  436. parent.AppendSubBuilder (builder);
  437. builder.CloseControl ();
  438. }
  439. return true;
  440. }
  441. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  442. {
  443. if (tagtype != TagType.Close) {
  444. if (attributes != null && attributes.IsRunAtServer ()) {
  445. CheckLanguage ((string) attributes ["language"]);
  446. if (tagtype == TagType.Tag) {
  447. Parser.VerbatimID = "script";
  448. inScript = true;
  449. } //else if (tagtype == TagType.SelfClosing)
  450. // load script file here
  451. return true;
  452. } else {
  453. if (tagtype != TagType.SelfClosing) {
  454. Parser.VerbatimID = "script";
  455. javascript = true;
  456. }
  457. TextParsed (location, location.PlainText);
  458. return true;
  459. }
  460. }
  461. bool result;
  462. if (inScript) {
  463. result = inScript;
  464. inScript = false;
  465. } else {
  466. result = javascript;
  467. javascript = false;
  468. TextParsed (location, location.PlainText);
  469. }
  470. return result;
  471. }
  472. bool CloseControl (string tagid)
  473. {
  474. ControlBuilder current = stack.Builder;
  475. string btag = current.TagName;
  476. if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
  477. if (!current.ChildrenAsProperties) {
  478. try {
  479. TextParsed (location, location.PlainText);
  480. FlushText ();
  481. } catch {}
  482. }
  483. return true;
  484. }
  485. if (0 != String.Compare (tagid, btag, true))
  486. return false;
  487. // if (current is TemplateBuilder)
  488. // pop from the id list
  489. if (current.NeedsTagInnerText ()) {
  490. try {
  491. current.SetTagInnerText (tagInnerText.ToString ());
  492. } catch (Exception e) {
  493. throw new ParseException (current.location, e.Message, e);
  494. }
  495. tagInnerText.Length = 0;
  496. }
  497. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  498. inForm = false;
  499. }
  500. current.CloseControl ();
  501. stack.Pop ();
  502. stack.Builder.AppendSubBuilder (current);
  503. return true;
  504. }
  505. bool ProcessCode (TagType tagtype, string code, ILocation location)
  506. {
  507. ControlBuilder b = null;
  508. if (tagtype == TagType.CodeRender)
  509. b = new CodeRenderBuilder (code, false, location);
  510. else if (tagtype == TagType.CodeRenderExpression)
  511. b = new CodeRenderBuilder (code, true, location);
  512. else if (tagtype == TagType.DataBinding)
  513. b = new DataBindingBuilder (code, location);
  514. else
  515. throw new HttpException ("Should never happen");
  516. stack.Builder.AppendSubBuilder (b);
  517. return true;
  518. }
  519. public ILocation Location {
  520. get { return location; }
  521. }
  522. void CheckLanguage (string lang)
  523. {
  524. if (lang == null || lang == "")
  525. return;
  526. if (String.Compare (lang, tparser.Language, true) != 0) {
  527. throw new ParseException (Location,
  528. String.Format ("Trying to mix language '{0}' and '{1}'.",
  529. tparser.Language, lang));
  530. }
  531. }
  532. // Used to get CodeRender tags in attribute values
  533. class CodeRenderParser
  534. {
  535. string str;
  536. ControlBuilder builder;
  537. public CodeRenderParser (string str, ControlBuilder builder)
  538. {
  539. this.str = str;
  540. this.builder = builder;
  541. }
  542. public void AddChildren ()
  543. {
  544. int index = str.IndexOf ("<%");
  545. if (index > 0) {
  546. TextParsed (null, str.Substring (0, index));
  547. str = str.Substring (index);
  548. }
  549. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  550. parser.Error += new ParseErrorHandler (ParseError);
  551. parser.TagParsed += new TagParsedHandler (TagParsed);
  552. parser.TextParsed += new TextParsedHandler (TextParsed);
  553. parser.Parse ();
  554. }
  555. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  556. {
  557. if (tagtype == TagType.CodeRender)
  558. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  559. else if (tagtype == TagType.CodeRenderExpression)
  560. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  561. else if (tagtype == TagType.DataBinding)
  562. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  563. else
  564. builder.AppendLiteralString (location.PlainText);
  565. }
  566. void TextParsed (ILocation location, string text)
  567. {
  568. builder.AppendLiteralString (text);
  569. }
  570. void ParseError (ILocation location, string message)
  571. {
  572. throw new ParseException (location, message);
  573. }
  574. }
  575. }
  576. }