AspGenerator.cs
上传用户:whwld168
上传日期:2008-02-07
资源大小:10177k
文件大小:16k
源码类别:

.net编程

开发平台:

C#

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