AspGenerator.cs 17 KB

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