AspGenerator.cs 13 KB

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