AspGenerator.cs 14 KB

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