AspGenerator.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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.Configuration;
  36. using System.Web.UI;
  37. using System.Web.UI.HtmlControls;
  38. using System.Web.Util;
  39. namespace System.Web.Compilation
  40. {
  41. class BuilderLocation
  42. {
  43. public ControlBuilder Builder;
  44. public ILocation Location;
  45. public BuilderLocation (ControlBuilder builder, ILocation location)
  46. {
  47. this.Builder = builder;
  48. this.Location = location;
  49. }
  50. }
  51. class BuilderLocationStack : Stack
  52. {
  53. public override void Push (object o)
  54. {
  55. if (!(o is BuilderLocation))
  56. throw new InvalidOperationException ();
  57. base.Push (o);
  58. }
  59. public virtual void Push (ControlBuilder builder, ILocation location)
  60. {
  61. BuilderLocation bl = new BuilderLocation (builder, location);
  62. Push (bl);
  63. }
  64. public new BuilderLocation Peek ()
  65. {
  66. return (BuilderLocation) base.Peek ();
  67. }
  68. public new BuilderLocation Pop ()
  69. {
  70. return (BuilderLocation) base.Pop ();
  71. }
  72. public ControlBuilder Builder {
  73. get { return Peek ().Builder; }
  74. }
  75. }
  76. class ParserStack
  77. {
  78. Hashtable files;
  79. Stack parsers;
  80. AspParser current;
  81. public ParserStack ()
  82. {
  83. files = new Hashtable (); // may be this should be case sensitive for windows
  84. parsers = new Stack ();
  85. }
  86. public bool Push (AspParser parser)
  87. {
  88. if (files.Contains (parser.Filename))
  89. return false;
  90. files [parser.Filename] = true;
  91. parsers.Push (parser);
  92. current = parser;
  93. return true;
  94. }
  95. public AspParser Pop ()
  96. {
  97. if (parsers.Count == 0)
  98. return null;
  99. files.Remove (current.Filename);
  100. AspParser result = (AspParser) parsers.Pop ();
  101. if (parsers.Count > 0)
  102. current = (AspParser) parsers.Peek ();
  103. else
  104. current = null;
  105. return result;
  106. }
  107. public AspParser Parser {
  108. get { return current; }
  109. }
  110. public string Filename {
  111. get { return current.Filename; }
  112. }
  113. }
  114. class TagStack
  115. {
  116. Stack tags;
  117. public TagStack ()
  118. {
  119. tags = new Stack ();
  120. }
  121. public void Push (string tagid)
  122. {
  123. tags.Push (tagid);
  124. }
  125. public string Pop ()
  126. {
  127. if (tags.Count == 0)
  128. return null;
  129. return (string) tags.Pop ();
  130. }
  131. public bool CompareTo (string tagid)
  132. {
  133. if (tags.Count == 0)
  134. return false;
  135. return 0 == String.Compare (tagid, (string) tags.Peek (), true);
  136. }
  137. public int Count {
  138. get { return tags.Count; }
  139. }
  140. public string Current {
  141. get { return (string) tags.Peek (); }
  142. }
  143. }
  144. class AspGenerator
  145. {
  146. ParserStack pstack;
  147. BuilderLocationStack stack;
  148. TemplateParser tparser;
  149. StringBuilder text;
  150. RootBuilder rootBuilder;
  151. bool inScript, javascript;
  152. ILocation location;
  153. bool isApplication;
  154. StringBuilder tagInnerText = new StringBuilder ();
  155. static Hashtable emptyHash = new Hashtable ();
  156. bool inForm;
  157. bool useOtherTags;
  158. public AspGenerator (TemplateParser tparser)
  159. {
  160. this.tparser = tparser;
  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.InsertPrivate ("@@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. static void PrintLocation (ILocation loc)
  246. {
  247. Console.WriteLine ("\tFile name: " + loc.Filename);
  248. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  249. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  250. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  251. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  252. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  253. Console.WriteLine ();
  254. }
  255. #endif
  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. useOtherTags = true;
  280. break;
  281. }
  282. if (useOtherTags) {
  283. stack.Builder.EnsureOtherTags ();
  284. stack.Builder.OtherTags.Add (tagid);
  285. }
  286. TextParsed (location, location.PlainText);
  287. break;
  288. case TagType.Close:
  289. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  290. if (!notServer && CloseControl (tagid))
  291. break;
  292. TextParsed (location, location.PlainText);
  293. break;
  294. case TagType.SelfClosing:
  295. int count = stack.Count;
  296. if (!ProcessTag (tagid, attributes, tagtype)) {
  297. TextParsed (location, location.PlainText);
  298. } else if (stack.Count != count) {
  299. CloseControl (tagid);
  300. }
  301. break;
  302. case TagType.DataBinding:
  303. goto case TagType.CodeRender;
  304. case TagType.CodeRenderExpression:
  305. goto case TagType.CodeRender;
  306. case TagType.CodeRender:
  307. if (isApplication)
  308. throw new ParseException (location, "Invalid content for application file.");
  309. ProcessCode (tagtype, tagid, location);
  310. break;
  311. case TagType.Include:
  312. if (isApplication)
  313. throw new ParseException (location, "Invalid content for application file.");
  314. string file = attributes ["virtual"] as string;
  315. bool isvirtual = (file != null);
  316. if (!isvirtual)
  317. file = attributes ["file"] as string;
  318. if (isvirtual) {
  319. file = tparser.MapPath (file);
  320. } else {
  321. file = GetIncludeFilePath (tparser.BaseDir, file);
  322. }
  323. InitParser (file);
  324. DoParse ();
  325. break;
  326. default:
  327. break;
  328. }
  329. //PrintLocation (location);
  330. }
  331. static bool TryRemoveTag (string tagid, ArrayList otags)
  332. {
  333. if (otags == null || otags.Count == 0)
  334. return false;
  335. int idx = otags.Count - 1;
  336. string otagid = (string) otags [idx];
  337. if (0 != String.Compare (tagid, otagid, true))
  338. return false;
  339. otags.RemoveAt (idx);
  340. return true;
  341. }
  342. static string GetIncludeFilePath (string basedir, string filename)
  343. {
  344. if (Path.DirectorySeparatorChar == '/')
  345. filename = filename.Replace ("\\", "/");
  346. return Path.GetFullPath (Path.Combine (basedir, filename));
  347. }
  348. void TextParsed (ILocation location, string text)
  349. {
  350. if (text.IndexOf ("<%") != -1 && !inScript) {
  351. if (this.text.Length > 0)
  352. FlushText ();
  353. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  354. r.AddChildren ();
  355. return;
  356. }
  357. this.text.Append (text);
  358. //PrintLocation (location);
  359. }
  360. void FlushText ()
  361. {
  362. string t = text.ToString ();
  363. text.Length = 0;
  364. if (inScript) {
  365. // TODO: store location
  366. tparser.Scripts.Add (t);
  367. return;
  368. }
  369. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  370. throw new ParseException (location, "Content not valid for application file.");
  371. ControlBuilder current = stack.Builder;
  372. current.AppendLiteralString (t);
  373. if (current.NeedsTagInnerText ()) {
  374. tagInnerText.Append (t);
  375. }
  376. }
  377. bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
  378. {
  379. if ((atts == null || !atts.IsRunAtServer ()) && String.Compare (tagid, "tbody", true) == 0) {
  380. // MS completely ignores tbody or, if runat="server", fails when compiling
  381. if (stack.Count > 0)
  382. return stack.Builder.ChildrenAsProperties;
  383. return false;
  384. }
  385. if (isApplication) {
  386. if (String.Compare (tagid, "object", true) != 0)
  387. throw new ParseException (location, "Invalid tag for application file.");
  388. }
  389. ControlBuilder parent = stack.Builder;
  390. ControlBuilder builder = null;
  391. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  392. if (stack.Count > 1) {
  393. try {
  394. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  395. } catch (TypeLoadException e) {
  396. throw new ParseException (Location, "Type not found.", e);
  397. } catch (Exception e) {
  398. throw new ParseException (Location, e.Message, e);
  399. }
  400. }
  401. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  402. string id = htable ["id"] as string;
  403. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  404. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  405. try {
  406. builder = rootBuilder.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)
  414. return false;
  415. builder.location = location;
  416. builder.ID = htable ["id"] as string;
  417. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  418. if (inForm)
  419. throw new ParseException (location, "Only one <form> allowed.");
  420. inForm = true;
  421. }
  422. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  423. if (builder is TemplateBuilder) {
  424. // push the id list
  425. }
  426. stack.Push (builder, location);
  427. } else {
  428. if (!isApplication && builder is ObjectTagBuilder) {
  429. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  430. if (ot.Scope != null && ot.Scope != "")
  431. throw new ParseException (location, "Scope not allowed here");
  432. if (tagtype == TagType.Tag) {
  433. stack.Push (builder, location);
  434. return true;
  435. }
  436. }
  437. parent.AppendSubBuilder (builder);
  438. builder.CloseControl ();
  439. }
  440. return true;
  441. }
  442. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  443. {
  444. if (tagtype != TagType.Close) {
  445. if (attributes != null && attributes.IsRunAtServer ()) {
  446. CheckLanguage ((string) attributes ["language"]);
  447. if (tagtype == TagType.Tag) {
  448. Parser.VerbatimID = "script";
  449. inScript = true;
  450. } //else if (tagtype == TagType.SelfClosing)
  451. // load script file here
  452. return true;
  453. } else {
  454. if (tagtype != TagType.SelfClosing) {
  455. Parser.VerbatimID = "script";
  456. javascript = true;
  457. }
  458. TextParsed (location, location.PlainText);
  459. return true;
  460. }
  461. }
  462. bool result;
  463. if (inScript) {
  464. result = inScript;
  465. inScript = false;
  466. } else {
  467. result = javascript;
  468. javascript = false;
  469. TextParsed (location, location.PlainText);
  470. }
  471. return result;
  472. }
  473. bool CloseControl (string tagid)
  474. {
  475. ControlBuilder current = stack.Builder;
  476. string btag = current.TagName;
  477. if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
  478. if (!current.ChildrenAsProperties) {
  479. try {
  480. TextParsed (location, location.PlainText);
  481. FlushText ();
  482. } catch {}
  483. }
  484. return true;
  485. }
  486. if (0 != String.Compare (tagid, btag, true))
  487. return false;
  488. // if (current is TemplateBuilder)
  489. // pop from the id list
  490. if (current.NeedsTagInnerText ()) {
  491. try {
  492. current.SetTagInnerText (tagInnerText.ToString ());
  493. } catch (Exception e) {
  494. throw new ParseException (current.location, e.Message, e);
  495. }
  496. tagInnerText.Length = 0;
  497. }
  498. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  499. inForm = false;
  500. }
  501. current.CloseControl ();
  502. stack.Pop ();
  503. stack.Builder.AppendSubBuilder (current);
  504. return true;
  505. }
  506. bool ProcessCode (TagType tagtype, string code, ILocation location)
  507. {
  508. ControlBuilder b = null;
  509. if (tagtype == TagType.CodeRender)
  510. b = new CodeRenderBuilder (code, false, location);
  511. else if (tagtype == TagType.CodeRenderExpression)
  512. b = new CodeRenderBuilder (code, true, location);
  513. else if (tagtype == TagType.DataBinding)
  514. b = new DataBindingBuilder (code, location);
  515. else
  516. throw new HttpException ("Should never happen");
  517. stack.Builder.AppendSubBuilder (b);
  518. return true;
  519. }
  520. public ILocation Location {
  521. get { return location; }
  522. }
  523. void CheckLanguage (string lang)
  524. {
  525. if (lang == null || lang == "")
  526. return;
  527. if (String.Compare (lang, tparser.Language, true) == 0)
  528. return;
  529. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  530. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang)) {
  531. throw new ParseException (Location,
  532. String.Format ("Trying to mix language '{0}' and '{1}'.",
  533. tparser.Language, lang));
  534. }
  535. }
  536. // Used to get CodeRender tags in attribute values
  537. class CodeRenderParser
  538. {
  539. string str;
  540. ControlBuilder builder;
  541. public CodeRenderParser (string str, ControlBuilder builder)
  542. {
  543. this.str = str;
  544. this.builder = builder;
  545. }
  546. public void AddChildren ()
  547. {
  548. int index = str.IndexOf ("<%");
  549. if (index > 0) {
  550. TextParsed (null, str.Substring (0, index));
  551. str = str.Substring (index);
  552. }
  553. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  554. parser.Error += new ParseErrorHandler (ParseError);
  555. parser.TagParsed += new TagParsedHandler (TagParsed);
  556. parser.TextParsed += new TextParsedHandler (TextParsed);
  557. parser.Parse ();
  558. }
  559. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  560. {
  561. if (tagtype == TagType.CodeRender)
  562. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  563. else if (tagtype == TagType.CodeRenderExpression)
  564. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  565. else if (tagtype == TagType.DataBinding)
  566. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  567. else
  568. builder.AppendLiteralString (location.PlainText);
  569. }
  570. void TextParsed (ILocation location, string text)
  571. {
  572. builder.AppendLiteralString (text);
  573. }
  574. void ParseError (ILocation location, string message)
  575. {
  576. throw new ParseException (location, message);
  577. }
  578. }
  579. }
  580. }