AspGenerator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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 (inScript || (tagtype != TagType.Close && attributes != null)) {
  269. if ((inScript || attributes.IsRunAtServer ()) && ProcessScript (tagtype, attributes))
  270. return;
  271. }
  272. }
  273. switch (tagtype) {
  274. case TagType.Directive:
  275. if (tagid == "")
  276. tagid = tparser.DefaultDirectiveName;
  277. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  278. break;
  279. case TagType.Tag:
  280. if (ProcessTag (tagid, attributes, tagtype)) {
  281. useOtherTags = true;
  282. break;
  283. }
  284. if (useOtherTags) {
  285. stack.Builder.EnsureOtherTags ();
  286. stack.Builder.OtherTags.Add (tagid);
  287. }
  288. TextParsed (location, location.PlainText);
  289. break;
  290. case TagType.Close:
  291. bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
  292. if (!notServer && CloseControl (tagid))
  293. break;
  294. TextParsed (location, location.PlainText);
  295. break;
  296. case TagType.SelfClosing:
  297. int count = stack.Count;
  298. if (!ProcessTag (tagid, attributes, tagtype)) {
  299. TextParsed (location, location.PlainText);
  300. } else if (stack.Count != count) {
  301. CloseControl (tagid);
  302. }
  303. break;
  304. case TagType.DataBinding:
  305. goto case TagType.CodeRender;
  306. case TagType.CodeRenderExpression:
  307. goto case TagType.CodeRender;
  308. case TagType.CodeRender:
  309. if (isApplication)
  310. throw new ParseException (location, "Invalid content for application file.");
  311. ProcessCode (tagtype, tagid, location);
  312. break;
  313. case TagType.Include:
  314. if (isApplication)
  315. throw new ParseException (location, "Invalid content for application file.");
  316. string file = attributes ["virtual"] as string;
  317. bool isvirtual = (file != null);
  318. if (!isvirtual)
  319. file = attributes ["file"] as string;
  320. if (isvirtual) {
  321. file = tparser.MapPath (file);
  322. } else {
  323. file = GetIncludeFilePath (tparser.BaseDir, file);
  324. }
  325. InitParser (file);
  326. DoParse ();
  327. break;
  328. default:
  329. break;
  330. }
  331. //PrintLocation (location);
  332. }
  333. static bool TryRemoveTag (string tagid, ArrayList otags)
  334. {
  335. if (otags == null || otags.Count == 0)
  336. return false;
  337. int idx = otags.Count - 1;
  338. string otagid = (string) otags [idx];
  339. if (0 != String.Compare (tagid, otagid, true))
  340. return false;
  341. otags.RemoveAt (idx);
  342. return true;
  343. }
  344. static string GetIncludeFilePath (string basedir, string filename)
  345. {
  346. if (Path.DirectorySeparatorChar == '/')
  347. filename = filename.Replace ("\\", "/");
  348. return Path.GetFullPath (Path.Combine (basedir, filename));
  349. }
  350. void TextParsed (ILocation location, string text)
  351. {
  352. if (text.IndexOf ("<%") != -1 && !inScript) {
  353. if (this.text.Length > 0)
  354. FlushText ();
  355. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  356. r.AddChildren ();
  357. return;
  358. }
  359. this.text.Append (text);
  360. //PrintLocation (location);
  361. }
  362. void FlushText ()
  363. {
  364. string t = text.ToString ();
  365. text.Length = 0;
  366. if (inScript) {
  367. // TODO: store location
  368. tparser.Scripts.Add (t);
  369. return;
  370. }
  371. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  372. throw new ParseException (location, "Content not valid for application file.");
  373. ControlBuilder current = stack.Builder;
  374. current.AppendLiteralString (t);
  375. if (current.NeedsTagInnerText ()) {
  376. tagInnerText.Append (t);
  377. }
  378. }
  379. bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
  380. {
  381. if ((atts == null || !atts.IsRunAtServer ()) && String.Compare (tagid, "tbody", true) == 0) {
  382. // MS completely ignores tbody or, if runat="server", fails when compiling
  383. if (stack.Count > 0)
  384. return stack.Builder.ChildrenAsProperties;
  385. return false;
  386. }
  387. if (isApplication) {
  388. if (String.Compare (tagid, "object", true) != 0)
  389. throw new ParseException (location, "Invalid tag for application file.");
  390. }
  391. ControlBuilder parent = stack.Builder;
  392. ControlBuilder builder = null;
  393. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  394. if (stack.Count > 1) {
  395. try {
  396. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  397. } catch (TypeLoadException e) {
  398. throw new ParseException (Location, "Type not found.", e);
  399. } catch (Exception e) {
  400. throw new ParseException (Location, e.Message, e);
  401. }
  402. }
  403. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  404. string id = htable ["id"] as string;
  405. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  406. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  407. try {
  408. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  409. } catch (TypeLoadException e) {
  410. throw new ParseException (Location, "Type not found.", e);
  411. } catch (Exception e) {
  412. throw new ParseException (Location, e.Message, e);
  413. }
  414. }
  415. if (builder == null)
  416. return false;
  417. builder.location = location;
  418. builder.ID = htable ["id"] as string;
  419. if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
  420. if (inForm)
  421. throw new ParseException (location, "Only one <form> allowed.");
  422. inForm = true;
  423. }
  424. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  425. if (builder is TemplateBuilder) {
  426. // push the id list
  427. }
  428. stack.Push (builder, location);
  429. } else {
  430. if (!isApplication && builder is ObjectTagBuilder) {
  431. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  432. if (ot.Scope != null && ot.Scope != "")
  433. throw new ParseException (location, "Scope not allowed here");
  434. if (tagtype == TagType.Tag) {
  435. stack.Push (builder, location);
  436. return true;
  437. }
  438. }
  439. parent.AppendSubBuilder (builder);
  440. builder.CloseControl ();
  441. }
  442. return true;
  443. }
  444. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  445. {
  446. if (tagtype != TagType.Close) {
  447. if (attributes != null && attributes.IsRunAtServer ()) {
  448. CheckLanguage ((string) attributes ["language"]);
  449. if (tagtype == TagType.Tag) {
  450. Parser.VerbatimID = "script";
  451. inScript = true;
  452. } //else if (tagtype == TagType.SelfClosing)
  453. // load script file here
  454. return true;
  455. } else {
  456. if (tagtype != TagType.SelfClosing) {
  457. Parser.VerbatimID = "script";
  458. javascript = true;
  459. }
  460. TextParsed (location, location.PlainText);
  461. return true;
  462. }
  463. }
  464. bool result;
  465. if (inScript) {
  466. result = inScript;
  467. inScript = false;
  468. } else {
  469. result = javascript;
  470. javascript = false;
  471. TextParsed (location, location.PlainText);
  472. }
  473. return result;
  474. }
  475. bool CloseControl (string tagid)
  476. {
  477. ControlBuilder current = stack.Builder;
  478. string btag = current.TagName;
  479. if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
  480. if (!current.ChildrenAsProperties) {
  481. try {
  482. TextParsed (location, location.PlainText);
  483. FlushText ();
  484. } catch {}
  485. }
  486. return true;
  487. }
  488. if (0 != String.Compare (tagid, btag, true))
  489. return false;
  490. // if (current is TemplateBuilder)
  491. // pop from the id list
  492. if (current.NeedsTagInnerText ()) {
  493. try {
  494. current.SetTagInnerText (tagInnerText.ToString ());
  495. } catch (Exception e) {
  496. throw new ParseException (current.location, e.Message, e);
  497. }
  498. tagInnerText.Length = 0;
  499. }
  500. if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
  501. inForm = false;
  502. }
  503. current.CloseControl ();
  504. stack.Pop ();
  505. stack.Builder.AppendSubBuilder (current);
  506. return true;
  507. }
  508. bool ProcessCode (TagType tagtype, string code, ILocation location)
  509. {
  510. ControlBuilder b = null;
  511. if (tagtype == TagType.CodeRender)
  512. b = new CodeRenderBuilder (code, false, location);
  513. else if (tagtype == TagType.CodeRenderExpression)
  514. b = new CodeRenderBuilder (code, true, location);
  515. else if (tagtype == TagType.DataBinding)
  516. b = new DataBindingBuilder (code, location);
  517. else
  518. throw new HttpException ("Should never happen");
  519. stack.Builder.AppendSubBuilder (b);
  520. return true;
  521. }
  522. public ILocation Location {
  523. get { return location; }
  524. }
  525. void CheckLanguage (string lang)
  526. {
  527. if (lang == null || lang == "")
  528. return;
  529. if (String.Compare (lang, tparser.Language, true) == 0)
  530. return;
  531. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  532. if (!cfg.Compilers.CompareLanguages (tparser.Language, lang)) {
  533. throw new ParseException (Location,
  534. String.Format ("Trying to mix language '{0}' and '{1}'.",
  535. tparser.Language, lang));
  536. }
  537. }
  538. // Used to get CodeRender tags in attribute values
  539. class CodeRenderParser
  540. {
  541. string str;
  542. ControlBuilder builder;
  543. public CodeRenderParser (string str, ControlBuilder builder)
  544. {
  545. this.str = str;
  546. this.builder = builder;
  547. }
  548. public void AddChildren ()
  549. {
  550. int index = str.IndexOf ("<%");
  551. if (index > 0) {
  552. TextParsed (null, str.Substring (0, index));
  553. str = str.Substring (index);
  554. }
  555. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  556. parser.Error += new ParseErrorHandler (ParseError);
  557. parser.TagParsed += new TagParsedHandler (TagParsed);
  558. parser.TextParsed += new TextParsedHandler (TextParsed);
  559. parser.Parse ();
  560. }
  561. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  562. {
  563. if (tagtype == TagType.CodeRender)
  564. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  565. else if (tagtype == TagType.CodeRenderExpression)
  566. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  567. else if (tagtype == TagType.DataBinding)
  568. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  569. else
  570. builder.AppendLiteralString (location.PlainText);
  571. }
  572. void TextParsed (ILocation location, string text)
  573. {
  574. builder.AppendLiteralString (text);
  575. }
  576. void ParseError (ILocation location, string message)
  577. {
  578. throw new ParseException (location, message);
  579. }
  580. }
  581. }
  582. }