AspGenerator.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. BuilderLocation bl = null;
  304. Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
  305. if (stack.Count > 1) {
  306. try {
  307. builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
  308. } catch (TypeLoadException e) {
  309. throw new ParseException (Location, "Type not found.", e);
  310. } catch (Exception e) {
  311. throw new ParseException (Location, e.Message, e);
  312. }
  313. }
  314. if (builder == null && atts != null && atts.IsRunAtServer ()) {
  315. string id = htable ["id"] as string;
  316. if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
  317. throw new ParseException (Location, "'" + id + "' is not a valid identifier");
  318. try {
  319. builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
  320. } catch (TypeLoadException e) {
  321. throw new ParseException (Location, "Type not found.", e);
  322. } catch (Exception e) {
  323. throw new ParseException (Location, e.Message, e);
  324. }
  325. }
  326. if (builder == null)
  327. return false;
  328. builder.location = location;
  329. builder.ID = htable ["id"] as string;
  330. if (builder.HasBody ()) {
  331. if (builder is TemplateBuilder) {
  332. // push the id list
  333. }
  334. stack.Push (builder, location);
  335. } else {
  336. if (!isApplication && builder is ObjectTagBuilder) {
  337. ObjectTagBuilder ot = (ObjectTagBuilder) builder;
  338. if (ot.Scope != null && ot.Scope != "")
  339. throw new ParseException (location, "Scope not allowed here");
  340. if (tagtype == TagType.Tag) {
  341. stack.Push (builder, location);
  342. return true;
  343. }
  344. }
  345. parent.AppendSubBuilder (builder);
  346. builder.CloseControl ();
  347. }
  348. return true;
  349. }
  350. bool ProcessScript (TagType tagtype, TagAttributes attributes)
  351. {
  352. if (tagtype != TagType.Close) {
  353. if (attributes != null && attributes.IsRunAtServer ()) {
  354. CheckLanguage ((string) attributes ["language"]);
  355. if (tagtype == TagType.Tag) {
  356. Parser.VerbatimID = "script";
  357. inScript = true;
  358. } //else if (tagtype == TagType.SelfClosing)
  359. // load script file here
  360. return true;
  361. } else {
  362. Parser.VerbatimID = "script";
  363. javascript = true;
  364. TextParsed (location, location.PlainText);
  365. return true;
  366. }
  367. }
  368. bool result;
  369. if (inScript) {
  370. result = inScript;
  371. inScript = false;
  372. } else {
  373. result = javascript;
  374. javascript = false;
  375. TextParsed (location, location.PlainText);
  376. }
  377. return result;
  378. }
  379. bool CloseControl (string tagid)
  380. {
  381. ControlBuilder current = stack.Builder;
  382. if (String.Compare (tagid, "tbody", true) == 0) {
  383. if (!current.ChildrenAsProperties) {
  384. try {
  385. TextParsed (location, location.PlainText);
  386. FlushText ();
  387. } catch {}
  388. }
  389. return true;
  390. }
  391. string btag = current.TagName;
  392. if (0 != String.Compare (tagid, btag, true))
  393. return false;
  394. // if (current is TemplateBuilder)
  395. // pop from the id list
  396. current.CloseControl ();
  397. stack.Pop ();
  398. stack.Builder.AppendSubBuilder (current);
  399. return true;
  400. }
  401. bool ProcessCode (TagType tagtype, string code, ILocation location)
  402. {
  403. ControlBuilder b = null;
  404. if (tagtype == TagType.CodeRender)
  405. b = new CodeRenderBuilder (code, false, location);
  406. else if (tagtype == TagType.CodeRenderExpression)
  407. b = new CodeRenderBuilder (code, true, location);
  408. else if (tagtype == TagType.DataBinding)
  409. b = new DataBindingBuilder (code, location);
  410. else
  411. throw new HttpException ("Should never happen");
  412. stack.Builder.AppendSubBuilder (b);
  413. return true;
  414. }
  415. public ILocation Location {
  416. get { return location; }
  417. }
  418. void CheckLanguage (string lang)
  419. {
  420. if (lang == null || lang == "")
  421. return;
  422. if (String.Compare (lang, tparser.Language, true) != 0) {
  423. throw new ParseException (Location,
  424. String.Format ("Trying to mix language '{0}' and '{1}'.",
  425. tparser.Language, lang));
  426. }
  427. }
  428. // Used to get CodeRender tags in attribute values
  429. class CodeRenderParser
  430. {
  431. string str;
  432. ControlBuilder builder;
  433. public CodeRenderParser (string str, ControlBuilder builder)
  434. {
  435. this.str = str;
  436. this.builder = builder;
  437. }
  438. public void AddChildren ()
  439. {
  440. int index = str.IndexOf ("<%");
  441. if (index > 0) {
  442. TextParsed (null, str.Substring (0, index));
  443. str = str.Substring (index);
  444. }
  445. AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
  446. parser.Error += new ParseErrorHandler (ParseError);
  447. parser.TagParsed += new TagParsedHandler (TagParsed);
  448. parser.TextParsed += new TextParsedHandler (TextParsed);
  449. parser.Parse ();
  450. }
  451. void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
  452. {
  453. if (tagtype == TagType.CodeRender)
  454. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
  455. else if (tagtype == TagType.CodeRenderExpression)
  456. builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
  457. else if (tagtype == TagType.DataBinding)
  458. builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
  459. else
  460. builder.AppendLiteralString (location.PlainText);
  461. }
  462. void TextParsed (ILocation location, string text)
  463. {
  464. builder.AppendLiteralString (text);
  465. }
  466. void ParseError (ILocation location, string message)
  467. {
  468. throw new ParseException (location, message);
  469. }
  470. }
  471. }
  472. }