AspGenerator.cs 18 KB

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