AspGenerator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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.Util;
  37. namespace System.Web.Compilation
  38. {
  39. class BuilderLocation
  40. {
  41. public ControlBuilder Builder;
  42. public ILocation Location;
  43. public BuilderLocation (ControlBuilder builder, ILocation location)
  44. {
  45. this.Builder = builder;
  46. this.Location = location;
  47. }
  48. }
  49. class BuilderLocationStack : Stack
  50. {
  51. public override void Push (object o)
  52. {
  53. if (!(o is BuilderLocation))
  54. throw new InvalidOperationException ();
  55. base.Push (o);
  56. }
  57. public virtual void Push (ControlBuilder builder, ILocation location)
  58. {
  59. BuilderLocation bl = new BuilderLocation (builder, location);
  60. Push (bl);
  61. }
  62. public new BuilderLocation Peek ()
  63. {
  64. return (BuilderLocation) base.Peek ();
  65. }
  66. public new BuilderLocation Pop ()
  67. {
  68. return (BuilderLocation) base.Pop ();
  69. }
  70. public ControlBuilder Builder {
  71. get { return Peek ().Builder; }
  72. }
  73. }
  74. class ParserStack
  75. {
  76. Hashtable files;
  77. Stack parsers;
  78. AspParser current;
  79. public ParserStack ()
  80. {
  81. files = new Hashtable (); // may be this should be case sensitive for windows
  82. parsers = new Stack ();
  83. }
  84. public bool Push (AspParser parser)
  85. {
  86. if (files.Contains (parser.Filename))
  87. return false;
  88. files [parser.Filename] = true;
  89. parsers.Push (parser);
  90. current = parser;
  91. return true;
  92. }
  93. public AspParser Pop ()
  94. {
  95. if (parsers.Count == 0)
  96. return null;
  97. files.Remove (current.Filename);
  98. AspParser result = (AspParser) parsers.Pop ();
  99. if (parsers.Count > 0)
  100. current = (AspParser) parsers.Peek ();
  101. else
  102. current = null;
  103. return result;
  104. }
  105. public AspParser Parser {
  106. get { return current; }
  107. }
  108. public string Filename {
  109. get { return current.Filename; }
  110. }
  111. }
  112. class AspGenerator
  113. {
  114. ParserStack pstack;
  115. BuilderLocationStack stack;
  116. TemplateParser tparser;
  117. StringBuilder text;
  118. RootBuilder rootBuilder;
  119. bool inScript, javascript;
  120. ILocation location;
  121. bool isApplication;
  122. static Hashtable emptyHash = new Hashtable ();
  123. public AspGenerator (TemplateParser tparser)
  124. {
  125. this.tparser = tparser;
  126. tparser.AddDependency (tparser.InputFile);
  127. text = new StringBuilder ();
  128. stack = new BuilderLocationStack ();
  129. rootBuilder = new RootBuilder (tparser);
  130. stack.Push (rootBuilder, null);
  131. tparser.RootBuilder = rootBuilder;
  132. pstack = new ParserStack ();
  133. }
  134. public AspParser Parser {
  135. get { return pstack.Parser; }
  136. }
  137. public string Filename {
  138. get { return pstack.Filename; }
  139. }
  140. BaseCompiler GetCompilerFromType ()
  141. {
  142. Type type = tparser.GetType ();
  143. if (type == typeof (PageParser))
  144. return new PageCompiler ((PageParser) tparser);
  145. if (type == typeof (ApplicationFileParser))
  146. return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
  147. if (type == typeof (UserControlParser))
  148. return new UserControlCompiler ((UserControlParser) tparser);
  149. throw new Exception ("Got type: " + type);
  150. }
  151. void InitParser (string filename)
  152. {
  153. StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
  154. AspParser parser = new AspParser (filename, reader);
  155. reader.Close ();
  156. parser.Error += new ParseErrorHandler (ParseError);
  157. parser.TagParsed += new TagParsedHandler (TagParsed);
  158. parser.TextParsed += new TextParsedHandler (TextParsed);
  159. if (!pstack.Push (parser))
  160. throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
  161. tparser.AddDependency (filename);
  162. }
  163. void DoParse ()
  164. {
  165. pstack.Parser.Parse ();
  166. if (text.Length > 0)
  167. FlushText ();
  168. pstack.Pop ();
  169. }
  170. public Type GetCompiledType ()
  171. {
  172. Type type = (Type) HttpRuntime.Cache.Get ("@@Type" + tparser.InputFile);
  173. if (type != null) {
  174. return type;
  175. }
  176. isApplication = tparser.DefaultDirectiveName == "application";
  177. InitParser (Path.GetFullPath (tparser.InputFile));
  178. DoParse ();
  179. #if DEBUG
  180. PrintTree (rootBuilder, 0);
  181. #endif
  182. if (stack.Count > 1)
  183. throw new ParseException (stack.Builder.location,
  184. "Expecting </" + stack.Builder.TagName + ">" + stack.Builder);
  185. BaseCompiler compiler = GetCompilerFromType ();
  186. type = compiler.GetCompiledType ();
  187. CacheDependency cd = new CacheDependency ((string[])
  188. tparser.Dependencies.ToArray (typeof (string)));
  189. HttpRuntime.Cache.Insert ("@@Type" + tparser.InputFile, type, cd);
  190. return type;
  191. }
  192. #if DEBUG
  193. static void PrintTree (ControlBuilder builder, int indent)
  194. {
  195. if (builder == null)
  196. return;
  197. string i = new string ('\t', indent);
  198. Console.Write (i);
  199. Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
  200. builder, builder.ID, builder.ControlType, builder.parentBuilder);
  201. if (builder.Children != null)
  202. foreach (object o in builder.Children) {
  203. if (o is ControlBuilder)
  204. PrintTree ((ControlBuilder) o, indent++);
  205. }
  206. }
  207. #endif
  208. static void PrintLocation (ILocation loc)
  209. {
  210. Console.WriteLine ("\tFile name: " + loc.Filename);
  211. Console.WriteLine ("\tBegin line: " + loc.BeginLine);
  212. Console.WriteLine ("\tEnd line: " + loc.EndLine);
  213. Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
  214. Console.WriteLine ("\tEnd column: " + loc.EndColumn);
  215. Console.WriteLine ("\tPlainText: " + loc.PlainText);
  216. Console.WriteLine ();
  217. }
  218. void ParseError (ILocation location, string message)
  219. {
  220. throw new ParseException (location, message);
  221. }
  222. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  223. {
  224. this.location = new Location (location);
  225. if (tparser != null)
  226. tparser.Location = location;
  227. if (text.Length != 0)
  228. FlushText ();
  229. if (0 == String.Compare (tagid, "script", true)) {
  230. if (ProcessScript (tagtype, attributes))
  231. return;
  232. }
  233. switch (tagtype) {
  234. case TagType.Directive:
  235. if (tagid == "")
  236. tagid = tparser.DefaultDirectiveName;
  237. tparser.AddDirective (tagid, attributes.GetDictionary (null));
  238. break;
  239. case TagType.Tag:
  240. if (!ProcessTag (tagid, attributes, tagtype))
  241. TextParsed (location, location.PlainText);
  242. break;
  243. case TagType.Close:
  244. if (!CloseControl (tagid))
  245. TextParsed (location, location.PlainText);
  246. break;
  247. case TagType.SelfClosing:
  248. int count = stack.Count;
  249. if (!ProcessTag (tagid, attributes, tagtype)) {
  250. TextParsed (location, location.PlainText);
  251. } else if (stack.Count != count) {
  252. CloseControl (tagid);
  253. }
  254. break;
  255. case TagType.DataBinding:
  256. goto case TagType.CodeRender;
  257. case TagType.CodeRenderExpression:
  258. goto case TagType.CodeRender;
  259. case TagType.CodeRender:
  260. if (isApplication)
  261. throw new ParseException (location, "Invalid content for application file.");
  262. ProcessCode (tagtype, tagid, location);
  263. break;
  264. case TagType.Include:
  265. if (isApplication)
  266. throw new ParseException (location, "Invalid content for application file.");
  267. string file = attributes ["virtual"] as string;
  268. bool isvirtual = (file != null);
  269. if (!isvirtual)
  270. file = attributes ["file"] as string;
  271. if (isvirtual) {
  272. file = tparser.MapPath (file);
  273. } else if (!Path.IsPathRooted (file)) {
  274. file = UrlUtils.Combine (tparser.BaseVirtualDir, file);
  275. }
  276. InitParser (file);
  277. DoParse ();
  278. break;
  279. default:
  280. break;
  281. }
  282. //PrintLocation (location);
  283. }
  284. void TextParsed (ILocation location, string text)
  285. {
  286. if (text.IndexOf ("<%") != -1 && !inScript) {
  287. if (this.text.Length > 0)
  288. FlushText ();
  289. CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
  290. r.AddChildren ();
  291. return;
  292. }
  293. this.text.Append (text);
  294. //PrintLocation (location);
  295. }
  296. void FlushText ()
  297. {
  298. string t = text.ToString ();
  299. text.Length = 0;
  300. if (inScript) {
  301. // TODO: store location
  302. tparser.Scripts.Add (t);
  303. return;
  304. }
  305. if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
  306. throw new ParseException (location, "Content not valid for application file.");
  307. stack.Builder.AppendLiteralString (t);
  308. }
  309. bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
  310. {
  311. if ((atts == null || !atts.IsRunAtServer ()) && String.Compare (tagid, "tbody", true) == 0) {
  312. // MS completely ignores tbody or, if runat="server", fails when compiling
  313. if (stack.Count > 0)
  314. return stack.Builder.ChildrenAsProperties;
  315. return false;
  316. }
  317. if (isApplication) {
  318. if (String.Compare (tagid, "object", true) != 0)
  319. throw new ParseException (location, "Invalid tag for application file.");
  320. }
  321. ControlBuilder parent = stack.Builder;
  322. ControlBuilder builder = null;
  323. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  324. if (stack.Count > 1) {
  325. try {
  326. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  327. } catch (TypeLoadException e) {
  328. throw new ParseException (Location, "Type not found.", e);
  329. } catch (Exception e) {
  330. throw new ParseException (Location, e.Message, e);
  331. }
  332. }
  333. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  334. string id = htable ["id"] as string;
  335. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  336. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  337. try {
  338. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  339. } catch (TypeLoadException e) {
  340. throw new ParseException (Location, "Type not found.", e);
  341. } catch (Exception e) {
  342. throw new ParseException (Location, e.Message, e);
  343. }
  344. }
  345. if (builder == null)
  346. return false;
  347. builder.location = location;
  348. builder.ID = htable ["id"] as string;
  349. if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
  350. if (builder is TemplateBuilder) {
  351. // push the id list
  352. }
  353. stack.Push (builder, location);
  354. } else {
  355. if (!isApplication && builder is ObjectTagBuilder) {
  356. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  357. if (ot.Scope != null && ot.Scope != "")
  358. throw new ParseException (location, "Scope not allowed here");
  359. if (tagtype == TagType.Tag) {
  360. stack.Push (builder, location);
  361. return true;
  362. }
  363. }
  364. parent.AppendSubBuilder (builder);
  365. builder.CloseControl ();
  366. }
  367. return true;
  368. }
  369. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  370. {
  371. if (tagtype != TagType.Close) {
  372. if (attributes != null && attributes.IsRunAtServer ()) {
  373. CheckLanguage ((string) attributes ["language"]);
  374. if (tagtype == TagType.Tag) {
  375. Parser.VerbatimID = "script";
  376. inScript = true;
  377. } //else if (tagtype == TagType.SelfClosing)
  378. // load script file here
  379. return true;
  380. } else {
  381. Parser.VerbatimID = "script";
  382. javascript = true;
  383. TextParsed (location, location.PlainText);
  384. return true;
  385. }
  386. }
  387. bool result;
  388. if (inScript) {
  389. result = inScript;
  390. inScript = false;
  391. } else {
  392. result = javascript;
  393. javascript = false;
  394. TextParsed (location, location.PlainText);
  395. }
  396. return result;
  397. }
  398. bool CloseControl (string tagid)
  399. {
  400. ControlBuilder current = stack.Builder;
  401. if (String.Compare (tagid, "tbody", true) == 0) {
  402. if (!current.ChildrenAsProperties) {
  403. try {
  404. TextParsed (location, location.PlainText);
  405. FlushText ();
  406. } catch {}
  407. }
  408. return true;
  409. }
  410. string btag = current.TagName;
  411. if (0 != String.Compare (tagid, btag, true))
  412. return false;
  413. // if (current is TemplateBuilder)
  414. // pop from the id list
  415. current.CloseControl ();
  416. stack.Pop ();
  417. stack.Builder.AppendSubBuilder (current);
  418. return true;
  419. }
  420. bool ProcessCode (TagType tagtype, string code, ILocation location)
  421. {
  422. ControlBuilder b = null;
  423. if (tagtype == TagType.CodeRender)
  424. b = new CodeRenderBuilder (code, false, location);
  425. else if (tagtype == TagType.CodeRenderExpression)
  426. b = new CodeRenderBuilder (code, true, location);
  427. else if (tagtype == TagType.DataBinding)
  428. b = new DataBindingBuilder (code, location);
  429. else
  430. throw new HttpException ("Should never happen");
  431. stack.Builder.AppendSubBuilder (b);
  432. return true;
  433. }
  434. public ILocation Location {
  435. get { return location; }
  436. }
  437. void CheckLanguage (string lang)
  438. {
  439. if (lang == null || lang == "")
  440. return;
  441. if (String.Compare (lang, tparser.Language, true) != 0) {
  442. throw new ParseException (Location,
  443. String.Format ("Trying to mix language '{0}' and '{1}'.",
  444. tparser.Language, lang));
  445. }
  446. }
  447. // Used to get CodeRender tags in attribute values
  448. class CodeRenderParser
  449. {
  450. string str;
  451. ControlBuilder builder;
  452. public CodeRenderParser (string str, ControlBuilder builder)
  453. {
  454. this.str = str;
  455. this.builder = builder;
  456. }
  457. public void AddChildren ()
  458. {
  459. int index = str.IndexOf ("<%");
  460. if (index > 0) {
  461. TextParsed (null, str.Substring (0, index));
  462. str = str.Substring (index);
  463. }
  464. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  465. parser.Error += new ParseErrorHandler (ParseError);
  466. parser.TagParsed += new TagParsedHandler (TagParsed);
  467. parser.TextParsed += new TextParsedHandler (TextParsed);
  468. parser.Parse ();
  469. }
  470. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  471. {
  472. if (tagtype == TagType.CodeRender)
  473. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  474. else if (tagtype == TagType.CodeRenderExpression)
  475. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  476. else if (tagtype == TagType.DataBinding)
  477. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  478. else
  479. builder.AppendLiteralString (location.PlainText);
  480. }
  481. void TextParsed (ILocation location, string text)
  482. {
  483. builder.AppendLiteralString (text);
  484. }
  485. void ParseError (ILocation location, string message)
  486. {
  487. throw new ParseException (location, message);
  488. }
  489. }
  490. }
  491. }