DTDReader.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. //
  2. // System.Xml.DTDReader
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  8. //
  9. // This code is almost imported from existing XmlTextReader.cs
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Specialized;
  14. using System.IO;
  15. using System.Text;
  16. using Mono.Xml;
  17. using System.Xml.Schema;
  18. using Mono.Xml.Native;
  19. namespace System.Xml
  20. {
  21. internal class DTDReader //: IXmlLineInfo
  22. {
  23. private XmlParserInput currentInput;
  24. private Stack parserInputStack;
  25. private string entityReferenceName;
  26. private char [] nameBuffer;
  27. private int nameLength;
  28. private int nameCapacity;
  29. private const int initialNameCapacity = 256;
  30. private StringBuilder valueBuffer;
  31. private int currentLinkedNodeLineNumber;
  32. private int currentLinkedNodeLinePosition;
  33. // Parameter entity placeholder
  34. private int dtdIncludeSect;
  35. string cachedPublicId;
  36. string cachedSystemId;
  37. DTDObjectModel DTD;
  38. // .ctor()
  39. public DTDReader (DTDObjectModel dtd,
  40. int startLineNumber,
  41. int startLinePosition)
  42. {
  43. this.DTD = dtd;
  44. currentLinkedNodeLineNumber = startLineNumber;
  45. currentLinkedNodeLinePosition = startLinePosition;
  46. Init ();
  47. }
  48. // Properties
  49. public string BaseURI {
  50. get { return currentInput.BaseURI; }
  51. }
  52. // A buffer for ReadContent for ReadOuterXml
  53. private StringBuilder CurrentTag {
  54. get {
  55. return currentInput.CurrentMarkup;
  56. }
  57. }
  58. // Methods
  59. private void Init ()
  60. {
  61. parserInputStack = new Stack ();
  62. entityReferenceName = String.Empty;
  63. nameBuffer = new char [initialNameCapacity];
  64. nameLength = 0;
  65. nameCapacity = initialNameCapacity;
  66. valueBuffer = new StringBuilder (512);
  67. }
  68. internal DTDObjectModel GenerateDTDObjectModel ()
  69. {
  70. // now compile DTD
  71. int originalParserDepth = parserInputStack.Count;
  72. bool more;
  73. if (DTD.InternalSubset != null && DTD.InternalSubset.Length > 0) {
  74. XmlParserInput original = currentInput;
  75. currentInput = new XmlParserInput (
  76. new StringReader (DTD.InternalSubset),
  77. DTD.BaseURI,
  78. currentLinkedNodeLineNumber,
  79. currentLinkedNodeLinePosition);
  80. currentInput.InitialState = false;
  81. do {
  82. more = ProcessDTDSubset ();
  83. if (PeekChar () == -1 && parserInputStack.Count > 0)
  84. PopParserInput ();
  85. } while (more || parserInputStack.Count > originalParserDepth);
  86. if (dtdIncludeSect != 0)
  87. throw new XmlException (this as IXmlLineInfo,"INCLUDE section is not ended correctly.");
  88. currentInput = original;
  89. }
  90. if (DTD.SystemId != null && DTD.SystemId != String.Empty && DTD.Resolver != null) {
  91. PushParserInput (DTD.SystemId);
  92. do {
  93. more = ProcessDTDSubset ();
  94. if (PeekChar () == -1 && parserInputStack.Count > 1)
  95. PopParserInput ();
  96. } while (more || parserInputStack.Count > originalParserDepth + 1);
  97. PopParserInput ();
  98. }
  99. StringCollection sc = new StringCollection ();
  100. // /*
  101. // Entity recursion check.
  102. foreach (DTDEntityDeclaration ent in DTD.EntityDecls.Values) {
  103. ent.ScanEntityValue (sc);
  104. sc.Clear ();
  105. }
  106. // */
  107. return DTD;
  108. }
  109. // Read any one of following:
  110. // elementdecl, AttlistDecl, EntityDecl, NotationDecl,
  111. // PI, Comment, Parameter Entity, or doctype termination char(']')
  112. //
  113. // Returns true if it may have any more contents, or false if not.
  114. private bool ProcessDTDSubset ()
  115. {
  116. SkipWhitespace ();
  117. switch(PeekChar ())
  118. {
  119. case -1:
  120. return false;
  121. case '%':
  122. // It affects on entity references' well-formedness
  123. if (this.parserInputStack.Count == 0)
  124. DTD.InternalSubsetHasPEReference = true;
  125. ReadChar ();
  126. string peName = ReadName ();
  127. Expect (';');
  128. currentInput.InsertParameterEntityBuffer (" ");
  129. currentInput.InsertParameterEntityBuffer (GetPEValue (peName));
  130. currentInput.InsertParameterEntityBuffer (" ");
  131. int currentLine = currentInput.LineNumber;
  132. int currentColumn = currentInput.LinePosition;
  133. while (currentInput.HasPEBuffer)
  134. ProcessDTDSubset ();
  135. if (currentInput.LineNumber != currentLine ||
  136. currentInput.LinePosition != currentColumn)
  137. throw new XmlException (this as IXmlLineInfo,
  138. "Incorrectly nested parameter entity.");
  139. break;
  140. case '<':
  141. ReadChar ();
  142. switch(ReadChar ())
  143. {
  144. case '?':
  145. // Only read, no store.
  146. ReadProcessingInstruction ();
  147. break;
  148. case '!':
  149. CompileDeclaration ();
  150. break;
  151. default:
  152. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<' character.");
  153. }
  154. break;
  155. case ']':
  156. if (dtdIncludeSect == 0)
  157. throw new XmlException (this as IXmlLineInfo, "Unbalanced end of INCLUDE/IGNORE section.");
  158. // End of inclusion
  159. Expect ("]]>");
  160. dtdIncludeSect--;
  161. SkipWhitespace ();
  162. // return false;
  163. break;
  164. default:
  165. throw new XmlException (this as IXmlLineInfo,String.Format ("Syntax Error inside doctypedecl markup : {0}({1})", PeekChar (), (char) PeekChar ()));
  166. }
  167. currentInput.InitialState = false;
  168. return true;
  169. }
  170. private void CompileDeclaration ()
  171. {
  172. switch(ReadChar ())
  173. {
  174. case '-':
  175. Expect ('-');
  176. // Only read, no store.
  177. ReadComment ();
  178. break;
  179. case 'E':
  180. switch(ReadChar ())
  181. {
  182. case 'N':
  183. Expect ("TITY");
  184. if (!SkipWhitespace ())
  185. throw new XmlException (this as IXmlLineInfo,
  186. "Whitespace is required after '<!ENTITY' in DTD entity declaration.");
  187. LOOPBACK:
  188. if (PeekChar () == '%') {
  189. ReadChar ();
  190. if (!SkipWhitespace ()) {
  191. ExpandPERef ();
  192. goto LOOPBACK;
  193. } else {
  194. TryExpandPERef ();
  195. SkipWhitespace ();
  196. if (XmlChar.IsNameChar (PeekChar ()))
  197. ReadParameterEntityDecl ();
  198. else
  199. throw new XmlException (this as IXmlLineInfo,"expected name character");
  200. }
  201. break;
  202. }
  203. DTDEntityDeclaration ent = ReadEntityDecl ();
  204. if (DTD.EntityDecls [ent.Name] == null)
  205. DTD.EntityDecls.Add (ent.Name, ent);
  206. break;
  207. case 'L':
  208. Expect ("EMENT");
  209. DTDElementDeclaration el = ReadElementDecl ();
  210. DTD.ElementDecls.Add (el.Name, el);
  211. break;
  212. default:
  213. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<!E' (ELEMENT or ENTITY must be found)");
  214. }
  215. break;
  216. case 'A':
  217. Expect ("TTLIST");
  218. DTDAttListDeclaration atl = ReadAttListDecl ();
  219. DTD.AttListDecls.Add (atl.Name, atl);
  220. break;
  221. case 'N':
  222. Expect ("OTATION");
  223. DTDNotationDeclaration not = ReadNotationDecl ();
  224. DTD.NotationDecls.Add (not.Name, not);
  225. break;
  226. case '[':
  227. // conditional sections
  228. SkipWhitespace ();
  229. TryExpandPERef ();
  230. SkipWhitespace ();
  231. Expect ('I');
  232. switch (ReadChar ()) {
  233. case 'N':
  234. Expect ("CLUDE");
  235. SkipWhitespace ();
  236. Expect ('[');
  237. dtdIncludeSect++;
  238. break;
  239. case 'G':
  240. Expect ("NORE");
  241. ReadIgnoreSect ();
  242. break;
  243. }
  244. break;
  245. default:
  246. throw new XmlException (this as IXmlLineInfo,"Syntax Error after '<!' characters.");
  247. }
  248. }
  249. private void ReadIgnoreSect ()
  250. {
  251. bool skip = false;
  252. SkipWhitespace ();
  253. Expect ('[');
  254. int dtdIgnoreSect = 1;
  255. while (dtdIgnoreSect > 0) {
  256. switch (skip ? PeekChar () : ReadChar ()) {
  257. case -1:
  258. throw new XmlException (this as IXmlLineInfo,"Unexpected IGNORE section end.");
  259. case '<':
  260. if (ReadChar () == '!' && ReadChar () == '[')
  261. dtdIgnoreSect++;
  262. break;
  263. case ']':
  264. if (ReadChar () == ']') {
  265. if (ReadChar () == '>')
  266. dtdIgnoreSect--;
  267. else
  268. skip = true;
  269. }
  270. break;
  271. }
  272. skip = false;
  273. }
  274. }
  275. // The reader is positioned on the head of the name.
  276. private DTDElementDeclaration ReadElementDecl ()
  277. {
  278. DTDElementDeclaration decl = new DTDElementDeclaration (DTD);
  279. if (!SkipWhitespace ())
  280. throw new XmlException (this as IXmlLineInfo,
  281. "Whitespace is required between '<!ELEMENT' and name in DTD element declaration.");
  282. TryExpandPERef ();
  283. SkipWhitespace ();
  284. decl.Name = ReadName ();
  285. if (!SkipWhitespace ())
  286. throw new XmlException (this as IXmlLineInfo,
  287. "Whitespace is required between name and content in DTD element declaration.");
  288. TryExpandPERef ();
  289. ReadContentSpec (decl);
  290. SkipWhitespace ();
  291. // This expanding is only allowed as a non-validating parser.
  292. TryExpandPERef ();
  293. SkipWhitespace ();
  294. Expect ('>');
  295. return decl;
  296. }
  297. // read 'children'(BNF) of contentspec
  298. private void ReadContentSpec (DTDElementDeclaration decl)
  299. {
  300. TryExpandPERef ();
  301. SkipWhitespace ();
  302. switch(PeekChar ())
  303. {
  304. case 'E':
  305. decl.IsEmpty = true;
  306. Expect ("EMPTY");
  307. break;
  308. case 'A':
  309. decl.IsAny = true;
  310. Expect ("ANY");
  311. break;
  312. case '(':
  313. DTDContentModel model = decl.ContentModel;
  314. ReadChar ();
  315. SkipWhitespace ();
  316. TryExpandPERef ();
  317. SkipWhitespace ();
  318. if(PeekChar () == '#') {
  319. // Mixed Contents. "#PCDATA" must appear first.
  320. decl.IsMixedContent = true;
  321. model.Occurence = DTDOccurence.ZeroOrMore;
  322. model.OrderType = DTDContentOrderType.Or;
  323. Expect ("#PCDATA");
  324. SkipWhitespace ();
  325. TryExpandPERef ();
  326. SkipWhitespace ();
  327. while(PeekChar () != ')') {
  328. Expect('|');
  329. SkipWhitespace ();
  330. TryExpandPERef ();
  331. SkipWhitespace ();
  332. DTDContentModel elem = new DTDContentModel (DTD, decl.Name);
  333. elem.LineNumber = currentInput.LineNumber;
  334. elem.LinePosition = currentInput.LinePosition;
  335. elem.ElementName = ReadName ();
  336. this.AddContentModel (model.ChildModels, elem);
  337. SkipWhitespace ();
  338. TryExpandPERef ();
  339. SkipWhitespace ();
  340. }
  341. Expect (')');
  342. if (model.ChildModels.Count > 0)
  343. Expect ('*');
  344. else if (PeekChar () == '*')
  345. Expect ('*');
  346. } else {
  347. // Non-Mixed Contents
  348. model.ChildModels.Add (ReadCP (decl));
  349. SkipWhitespace ();
  350. do { // copied from ReadCP() ...;-)
  351. TryExpandPERef ();
  352. SkipWhitespace ();
  353. if(PeekChar ()=='|') {
  354. // CPType=Or
  355. if (model.OrderType == DTDContentOrderType.Seq)
  356. throw new XmlException (this as IXmlLineInfo,
  357. "Inconsistent choice markup in sequence cp.");
  358. model.OrderType = DTDContentOrderType.Or;
  359. ReadChar ();
  360. SkipWhitespace ();
  361. AddContentModel (model.ChildModels, ReadCP (decl));
  362. SkipWhitespace ();
  363. }
  364. else if(PeekChar () == ',')
  365. {
  366. // CPType=Seq
  367. if (model.OrderType == DTDContentOrderType.Or)
  368. throw new XmlException (this as IXmlLineInfo,
  369. "Inconsistent sequence markup in choice cp.");
  370. model.OrderType = DTDContentOrderType.Seq;
  371. ReadChar ();
  372. SkipWhitespace ();
  373. model.ChildModels.Add (ReadCP (decl));
  374. SkipWhitespace ();
  375. }
  376. else
  377. break;
  378. }
  379. while(true);
  380. Expect (')');
  381. switch(PeekChar ())
  382. {
  383. case '?':
  384. model.Occurence = DTDOccurence.Optional;
  385. ReadChar ();
  386. break;
  387. case '*':
  388. model.Occurence = DTDOccurence.ZeroOrMore;
  389. ReadChar ();
  390. break;
  391. case '+':
  392. model.Occurence = DTDOccurence.OneOrMore;
  393. ReadChar ();
  394. break;
  395. }
  396. SkipWhitespace ();
  397. }
  398. SkipWhitespace ();
  399. break;
  400. default:
  401. throw new XmlException (this as IXmlLineInfo, "ContentSpec is missing.");
  402. }
  403. }
  404. // Read 'cp' (BNF) of contentdecl (BNF)
  405. private DTDContentModel ReadCP (DTDElementDeclaration elem)
  406. {
  407. DTDContentModel model = null;
  408. TryExpandPERef ();
  409. SkipWhitespace ();
  410. if(PeekChar () == '(') {
  411. model = new DTDContentModel (DTD, elem.Name);
  412. model.BaseURI = this.BaseURI;
  413. model.LineNumber = currentInput.LineNumber;
  414. model.LinePosition = currentInput.LinePosition;
  415. ReadChar ();
  416. SkipWhitespace ();
  417. model.ChildModels.Add (ReadCP (elem));
  418. SkipWhitespace ();
  419. do {
  420. TryExpandPERef ();
  421. SkipWhitespace ();
  422. if(PeekChar ()=='|') {
  423. // CPType=Or
  424. if (model.OrderType == DTDContentOrderType.Seq)
  425. throw new XmlException (this as IXmlLineInfo,
  426. "Inconsistent choice markup in sequence cp.");
  427. model.OrderType = DTDContentOrderType.Or;
  428. ReadChar ();
  429. SkipWhitespace ();
  430. AddContentModel (model.ChildModels, ReadCP (elem));
  431. SkipWhitespace ();
  432. }
  433. else if(PeekChar () == ',') {
  434. // CPType=Seq
  435. if (model.OrderType == DTDContentOrderType.Or)
  436. throw new XmlException (this as IXmlLineInfo,
  437. "Inconsistent sequence markup in choice cp.");
  438. model.OrderType = DTDContentOrderType.Seq;
  439. ReadChar ();
  440. SkipWhitespace ();
  441. model.ChildModels.Add (ReadCP (elem));
  442. SkipWhitespace ();
  443. }
  444. else
  445. break;
  446. }
  447. while(true);
  448. SkipWhitespace ();
  449. Expect (')');
  450. }
  451. else {
  452. TryExpandPERef ();
  453. model = new DTDContentModel (DTD, elem.Name);
  454. model.BaseURI = this.BaseURI;
  455. model.LineNumber = currentInput.LineNumber;
  456. model.LinePosition = currentInput.LinePosition;
  457. SkipWhitespace ();
  458. model.ElementName = ReadName ();
  459. }
  460. switch(PeekChar ()) {
  461. case '?':
  462. model.Occurence = DTDOccurence.Optional;
  463. ReadChar ();
  464. break;
  465. case '*':
  466. model.Occurence = DTDOccurence.ZeroOrMore;
  467. ReadChar ();
  468. break;
  469. case '+':
  470. model.Occurence = DTDOccurence.OneOrMore;
  471. ReadChar ();
  472. break;
  473. }
  474. return model;
  475. }
  476. private void AddContentModel (DTDContentModelCollection cmc, DTDContentModel cm)
  477. {
  478. if (cm.ElementName != null) {
  479. for (int i = 0; i < cmc.Count; i++) {
  480. if (cmc [i].ElementName == cm.ElementName) {
  481. DTD.AddError (new XmlSchemaException ("Element content must be unique inside mixed content model.",
  482. cm.LineNumber,
  483. cm.LinePosition,
  484. null,
  485. cm.BaseURI,
  486. null));
  487. return;
  488. }
  489. }
  490. }
  491. cmc.Add (cm);
  492. }
  493. // The reader is positioned on the first name char.
  494. private void ReadParameterEntityDecl ()
  495. {
  496. DTDParameterEntityDeclaration decl =
  497. new DTDParameterEntityDeclaration();
  498. decl.BaseURI = BaseURI;
  499. decl.Name = ReadName ();
  500. if (!SkipWhitespace ())
  501. throw new XmlException (this as IXmlLineInfo,
  502. "Whitespace is required after name in DTD parameter entity declaration.");
  503. if (PeekChar () == 'S' || PeekChar () == 'P') {
  504. // read publicId/systemId
  505. ReadExternalID ();
  506. decl.PublicId = cachedPublicId;
  507. decl.SystemId = cachedSystemId;
  508. SkipWhitespace ();
  509. decl.Resolve (this.DTD.Resolver);
  510. }
  511. else {
  512. TryExpandPERef ();
  513. int quoteChar = ReadChar ();
  514. int start = CurrentTag.Length;
  515. ClearValueBuffer ();
  516. bool loop = true;
  517. while (loop) {
  518. int c = PeekChar ();
  519. switch (c) {
  520. case -1:
  521. throw new XmlException ("unexpected end of stream in entity value definition.");
  522. case '"':
  523. ReadChar ();
  524. if (quoteChar == '"')
  525. loop = false;
  526. else
  527. AppendValueChar ('"');
  528. break;
  529. case '\'':
  530. ReadChar ();
  531. if (quoteChar == '\'')
  532. loop = false;
  533. else
  534. AppendValueChar ('\'');
  535. break;
  536. case '&':
  537. ReadChar ();
  538. if (PeekChar () == '#') {
  539. ReadChar ();
  540. ReadCharacterReference ();
  541. }
  542. else
  543. AppendValueChar ('&');
  544. break;
  545. case '%':
  546. ReadChar ();
  547. string peName = ReadName ();
  548. Expect (';');
  549. valueBuffer.Append (GetPEValue (peName));
  550. break;
  551. default:
  552. AppendValueChar (ReadChar ());
  553. break;
  554. }
  555. }
  556. decl.LiteralEntityValue = CreateValueString (); // currentTag.ToString (start, currentTag.Length - start - 1);
  557. ClearValueBuffer ();
  558. }
  559. SkipWhitespace ();
  560. Expect ('>');
  561. if (DTD.PEDecls [decl.Name] == null) {
  562. DTD.PEDecls.Add (decl.Name, decl);
  563. }
  564. }
  565. private string GetPEValue (string peName)
  566. {
  567. DTDParameterEntityDeclaration peDecl =
  568. DTD.PEDecls [peName] as DTDParameterEntityDeclaration;
  569. if (peDecl != null)
  570. return peDecl.Value;
  571. // See XML 1.0 section 4.1 for both WFC and VC.
  572. if ((DTD.SystemId == null && !DTD.InternalSubsetHasPEReference) || DTD.IsStandalone)
  573. throw new XmlException (this as IXmlLineInfo,
  574. "Parameter entity " + peName + " not found.");
  575. DTD.AddError (new XmlSchemaException (
  576. "Parameter entity " + peName + " not found.", null));
  577. return "";
  578. }
  579. private void TryExpandPERef ()
  580. {
  581. if (PeekChar () == '%') {
  582. ExpandPERef ();
  583. }
  584. }
  585. // reader is positioned on '%'
  586. private void ExpandPERef ()
  587. {
  588. ReadChar ();
  589. string peName = ReadName ();
  590. Expect (';');
  591. DTDParameterEntityDeclaration peDecl =
  592. DTD.PEDecls [peName] as DTDParameterEntityDeclaration;
  593. if (peDecl == null) {
  594. DTD.AddError (new XmlSchemaException ("Parameter entity " + peName + " not found.", null));
  595. return; // do nothing
  596. }
  597. currentInput.InsertParameterEntityBuffer (" " + peDecl.Value + " ");
  598. }
  599. // The reader is positioned on the head of the name.
  600. private DTDEntityDeclaration ReadEntityDecl ()
  601. {
  602. DTDEntityDeclaration decl = new DTDEntityDeclaration (DTD);
  603. decl.IsInternalSubset = (parserInputStack.Count == 0);
  604. TryExpandPERef ();
  605. SkipWhitespace ();
  606. decl.Name = ReadName ();
  607. if (!SkipWhitespace ())
  608. throw new XmlException (this as IXmlLineInfo,
  609. "Whitespace is required between name and content in DTD entity declaration.");
  610. TryExpandPERef ();
  611. SkipWhitespace ();
  612. if (PeekChar () == 'S' || PeekChar () == 'P') {
  613. // external entity
  614. ReadExternalID ();
  615. decl.PublicId = cachedPublicId;
  616. decl.SystemId = cachedSystemId;
  617. if (SkipWhitespace ()) {
  618. if (PeekChar () == 'N') {
  619. // NDataDecl
  620. Expect ("NDATA");
  621. if (!SkipWhitespace ())
  622. throw new XmlException (this as IXmlLineInfo,
  623. "Whitespace is required after NDATA.");
  624. decl.NotationName = ReadName (); // ndata_name
  625. }
  626. }
  627. }
  628. else {
  629. // literal entity
  630. ReadEntityValueDecl (decl);
  631. }
  632. SkipWhitespace ();
  633. // This expanding is only allowed as a non-validating parser.
  634. TryExpandPERef ();
  635. SkipWhitespace ();
  636. Expect ('>');
  637. return decl;
  638. }
  639. private void ReadEntityValueDecl (DTDEntityDeclaration decl)
  640. {
  641. SkipWhitespace ();
  642. // quotation char will be finally removed on unescaping
  643. int quoteChar = ReadChar ();
  644. int start = CurrentTag.Length;
  645. if (quoteChar != '\'' && quoteChar != '"')
  646. throw new XmlException ("quotation char was expected.");
  647. ClearValueBuffer ();
  648. while (PeekChar () != quoteChar) {
  649. switch (PeekChar ()) {
  650. case '%':
  651. ReadChar ();
  652. string name = ReadName ();
  653. Expect (';');
  654. if (decl.IsInternalSubset)
  655. throw new XmlException (this as IXmlLineInfo,
  656. "Parameter entity is not allowed in internal subset entity '" + name + "'");
  657. valueBuffer.Append (GetPEValue (name));
  658. break;
  659. case -1:
  660. throw new XmlException ("unexpected end of stream.");
  661. default:
  662. AppendValueChar (ReadChar ());
  663. break;
  664. }
  665. }
  666. string value = Dereference (CreateValueString (), false);
  667. ClearValueBuffer ();
  668. Expect (quoteChar);
  669. decl.LiteralEntityValue = value;
  670. }
  671. private DTDAttListDeclaration ReadAttListDecl ()
  672. {
  673. TryExpandPERef ();
  674. if (!SkipWhitespace ())
  675. throw new XmlException (this as IXmlLineInfo,
  676. "Whitespace is required between ATTLIST and name in DTD attlist declaration.");
  677. TryExpandPERef ();
  678. SkipWhitespace ();
  679. string name = ReadName (); // target element name
  680. DTDAttListDeclaration decl =
  681. DTD.AttListDecls [name] as DTDAttListDeclaration;
  682. if (decl == null)
  683. decl = new DTDAttListDeclaration (DTD);
  684. decl.IsInternalSubset = (parserInputStack.Count == 0);
  685. decl.Name = name;
  686. if (!SkipWhitespace ())
  687. if (PeekChar () != '>')
  688. throw new XmlException (this as IXmlLineInfo,
  689. "Whitespace is required between name and content in non-empty DTD attlist declaration.");
  690. TryExpandPERef ();
  691. SkipWhitespace ();
  692. while (XmlChar.IsNameChar ((char) PeekChar ())) {
  693. DTDAttributeDefinition def = ReadAttributeDefinition ();
  694. // There must not be two or more ID attributes.
  695. if (def.Datatype.TokenizedType == XmlTokenizedType.ID) {
  696. for (int i = 0; i < decl.Definitions.Count; i++) {
  697. DTDAttributeDefinition d = decl [i];
  698. if (d.Datatype.TokenizedType == XmlTokenizedType.ID) {
  699. DTD.AddError (new XmlSchemaException ("AttList declaration must not contain two or more ID attributes.",
  700. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  701. break;
  702. }
  703. }
  704. }
  705. if (decl [def.Name] == null)
  706. decl.Add (def);
  707. SkipWhitespace ();
  708. TryExpandPERef ();
  709. SkipWhitespace ();
  710. }
  711. SkipWhitespace ();
  712. // This expanding is only allowed as a non-validating parser.
  713. TryExpandPERef ();
  714. SkipWhitespace ();
  715. Expect ('>');
  716. return decl;
  717. }
  718. private DTDAttributeDefinition ReadAttributeDefinition ()
  719. {
  720. DTDAttributeDefinition def = new DTDAttributeDefinition (DTD);
  721. def.IsInternalSubset = (parserInputStack.Count == 0);
  722. // attr_name
  723. TryExpandPERef ();
  724. SkipWhitespace ();
  725. def.Name = ReadName ();
  726. if (!SkipWhitespace ())
  727. throw new XmlException (this as IXmlLineInfo,
  728. "Whitespace is required between name and content in DTD attribute definition.");
  729. // attr_value
  730. TryExpandPERef ();
  731. SkipWhitespace ();
  732. switch(PeekChar ()) {
  733. case 'C': // CDATA
  734. Expect ("CDATA");
  735. def.Datatype = XmlSchemaDatatype.FromName ("normalizedString");
  736. break;
  737. case 'I': // ID, IDREF, IDREFS
  738. Expect ("ID");
  739. if(PeekChar () == 'R') {
  740. Expect ("REF");
  741. if(PeekChar () == 'S') {
  742. // IDREFS
  743. ReadChar ();
  744. def.Datatype = XmlSchemaDatatype.FromName ("IDREFS");
  745. }
  746. else // IDREF
  747. def.Datatype = XmlSchemaDatatype.FromName ("IDREF");
  748. }
  749. else // ID
  750. def.Datatype = XmlSchemaDatatype.FromName ("ID");
  751. break;
  752. case 'E': // ENTITY, ENTITIES
  753. Expect ("ENTIT");
  754. switch(ReadChar ()) {
  755. case 'Y': // ENTITY
  756. def.Datatype = XmlSchemaDatatype.FromName ("ENTITY");
  757. break;
  758. case 'I': // ENTITIES
  759. Expect ("ES");
  760. def.Datatype = XmlSchemaDatatype.FromName ("ENTITIES");
  761. break;
  762. }
  763. break;
  764. case 'N': // NMTOKEN, NMTOKENS, NOTATION
  765. ReadChar ();
  766. switch(PeekChar ()) {
  767. case 'M':
  768. Expect ("MTOKEN");
  769. if(PeekChar ()=='S') { // NMTOKENS
  770. ReadChar ();
  771. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKENS");
  772. }
  773. else // NMTOKEN
  774. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN");
  775. break;
  776. case 'O':
  777. Expect ("OTATION");
  778. def.Datatype = XmlSchemaDatatype.FromName ("NOTATION");
  779. if (!SkipWhitespace ())
  780. throw new XmlException (this as IXmlLineInfo,
  781. "Whitespace is required between name and content in DTD attribute definition.");
  782. Expect ('(');
  783. SkipWhitespace ();
  784. def.EnumeratedNotations.Add (ReadName ()); // notation name
  785. SkipWhitespace ();
  786. while(PeekChar () == '|') {
  787. ReadChar ();
  788. SkipWhitespace ();
  789. def.EnumeratedNotations.Add (ReadName ()); // notation name
  790. SkipWhitespace ();
  791. }
  792. Expect (')');
  793. break;
  794. default:
  795. throw new XmlException ("attribute declaration syntax error.");
  796. }
  797. break;
  798. default: // Enumerated Values
  799. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN");
  800. TryExpandPERef ();
  801. SkipWhitespace ();
  802. Expect ('(');
  803. SkipWhitespace ();
  804. def.EnumeratedAttributeDeclaration.Add (
  805. def.Datatype.Normalize (ReadNmToken ())); // enum value
  806. SkipWhitespace ();
  807. while(PeekChar () == '|') {
  808. ReadChar ();
  809. SkipWhitespace ();
  810. def.EnumeratedAttributeDeclaration.Add (
  811. def.Datatype.Normalize (ReadNmToken ())); // enum value
  812. SkipWhitespace ();
  813. }
  814. Expect (')');
  815. break;
  816. }
  817. TryExpandPERef ();
  818. if (!SkipWhitespace ())
  819. throw new XmlException (this as IXmlLineInfo,
  820. "Whitespace is required between type and occurence in DTD attribute definition.");
  821. // def_value
  822. if(PeekChar () == '#')
  823. {
  824. ReadChar ();
  825. switch(PeekChar ())
  826. {
  827. case 'R':
  828. Expect ("REQUIRED");
  829. def.OccurenceType = DTDAttributeOccurenceType.Required;
  830. break;
  831. case 'I':
  832. Expect ("IMPLIED");
  833. def.OccurenceType = DTDAttributeOccurenceType.Optional;
  834. break;
  835. case 'F':
  836. Expect ("FIXED");
  837. def.OccurenceType = DTDAttributeOccurenceType.Fixed;
  838. if (!SkipWhitespace ())
  839. throw new XmlException (this as IXmlLineInfo,
  840. "Whitespace is required between FIXED and actual value in DTD attribute definition.");
  841. def.UnresolvedDefaultValue = ReadDefaultAttribute ();
  842. break;
  843. }
  844. } else {
  845. // one of the enumerated value
  846. SkipWhitespace ();
  847. TryExpandPERef ();
  848. SkipWhitespace ();
  849. def.UnresolvedDefaultValue = ReadDefaultAttribute ();
  850. }
  851. // VC: If default value exists, it should be valid.
  852. if (def.DefaultValue != null) {
  853. string normalized = def.Datatype.Normalize (def.DefaultValue);
  854. bool breakup = false;
  855. object parsed = null;
  856. // enumeration validity
  857. if (def.EnumeratedAttributeDeclaration.Count > 0) {
  858. if (!def.EnumeratedAttributeDeclaration.Contains (normalized)) {
  859. DTD.AddError (new XmlSchemaException ("Default value is not one of the enumerated values.",
  860. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  861. breakup = true;
  862. }
  863. }
  864. if (def.EnumeratedNotations.Count > 0) {
  865. if (!def.EnumeratedNotations.Contains (normalized)) {
  866. DTD.AddError (new XmlSchemaException ("Default value is not one of the enumerated notation values.",
  867. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  868. breakup = true;
  869. }
  870. }
  871. // type based validity
  872. if (!breakup) {
  873. try {
  874. parsed = def.Datatype.ParseValue (normalized, DTD.NameTable, null);
  875. } catch (Exception ex) { // FIXME: (wishlist) bad catch ;-(
  876. DTD.AddError (new XmlSchemaException ("Invalid default value for ENTITY type.",
  877. def.LineNumber, def.LinePosition, null, def.BaseURI, ex));
  878. breakup = true;
  879. }
  880. }
  881. if (!breakup) {
  882. switch (def.Datatype.TokenizedType) {
  883. case XmlTokenizedType.ENTITY:
  884. if (DTD.EntityDecls [normalized] == null)
  885. DTD.AddError (new XmlSchemaException ("Specified entity declaration used by default attribute value was not found.",
  886. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  887. break;
  888. case XmlTokenizedType.ENTITIES:
  889. string [] entities = parsed as string [];
  890. for (int i = 0; i < entities.Length; i++) {
  891. string entity = entities [i];
  892. if (DTD.EntityDecls [entity] == null)
  893. DTD.AddError (new XmlSchemaException ("Specified entity declaration used by default attribute value was not found.",
  894. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  895. }
  896. break;
  897. }
  898. }
  899. }
  900. // Extra ID attribute validity check.
  901. if (def.Datatype != null && def.Datatype.TokenizedType == XmlTokenizedType.ID)
  902. if (def.UnresolvedDefaultValue != null)
  903. DTD.AddError (new XmlSchemaException ("ID attribute must not have fixed value constraint.",
  904. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  905. return def;
  906. }
  907. private DTDNotationDeclaration ReadNotationDecl()
  908. {
  909. DTDNotationDeclaration decl = new DTDNotationDeclaration (DTD);
  910. if (!SkipWhitespace ())
  911. throw new XmlException (this as IXmlLineInfo,
  912. "Whitespace is required between NOTATION and name in DTD notation declaration.");
  913. TryExpandPERef ();
  914. SkipWhitespace ();
  915. decl.Name = ReadName (); // notation name
  916. /*
  917. if (namespaces) { // copy from SetProperties ;-)
  918. int indexOfColon = decl.Name.IndexOf (':');
  919. if (indexOfColon == -1) {
  920. decl.Prefix = String.Empty;
  921. decl.LocalName = decl.Name;
  922. } else {
  923. decl.Prefix = decl.Name.Substring (0, indexOfColon);
  924. decl.LocalName = decl.Name.Substring (indexOfColon + 1);
  925. }
  926. } else {
  927. */
  928. decl.Prefix = String.Empty;
  929. decl.LocalName = decl.Name;
  930. // }
  931. SkipWhitespace ();
  932. if(PeekChar () == 'P') {
  933. decl.PublicId = ReadPubidLiteral ();
  934. bool wsSkipped = SkipWhitespace ();
  935. if (PeekChar () == '\'' || PeekChar () == '"') {
  936. if (!wsSkipped)
  937. throw new XmlException (this as IXmlLineInfo,
  938. "Whitespace is required between public id and system id.");
  939. decl.SystemId = ReadSystemLiteral (false);
  940. SkipWhitespace ();
  941. }
  942. } else if(PeekChar () == 'S') {
  943. decl.SystemId = ReadSystemLiteral (true);
  944. SkipWhitespace ();
  945. }
  946. if(decl.PublicId == null && decl.SystemId == null)
  947. throw new XmlException ("public or system declaration required for \"NOTATION\" declaration.");
  948. // This expanding is only allowed as a non-validating parser.
  949. TryExpandPERef ();
  950. SkipWhitespace ();
  951. Expect ('>');
  952. return decl;
  953. }
  954. private void ReadExternalID () {
  955. switch (PeekChar ()) {
  956. case 'S':
  957. cachedSystemId = ReadSystemLiteral (true);
  958. break;
  959. case 'P':
  960. cachedPublicId = ReadPubidLiteral ();
  961. if (!SkipWhitespace ())
  962. throw new XmlException (this as IXmlLineInfo,
  963. "Whitespace is required between PUBLIC id and SYSTEM id.");
  964. cachedSystemId = ReadSystemLiteral (false);
  965. break;
  966. }
  967. }
  968. // The reader is positioned on the first 'S' of "SYSTEM".
  969. private string ReadSystemLiteral (bool expectSYSTEM)
  970. {
  971. if(expectSYSTEM) {
  972. Expect ("SYSTEM");
  973. if (!SkipWhitespace ())
  974. throw new XmlException (this as IXmlLineInfo,
  975. "Whitespace is required after 'SYSTEM'.");
  976. }
  977. else
  978. SkipWhitespace ();
  979. int quoteChar = ReadChar (); // apos or quot
  980. int startPos = CurrentTag.Length;
  981. int c = 0;
  982. ClearValueBuffer ();
  983. while (c != quoteChar) {
  984. c = ReadChar ();
  985. if (c < 0)
  986. throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  987. if (c != quoteChar)
  988. AppendValueChar (c);
  989. }
  990. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  991. }
  992. private string ReadPubidLiteral()
  993. {
  994. Expect ("PUBLIC");
  995. if (!SkipWhitespace ())
  996. throw new XmlException (this as IXmlLineInfo,
  997. "Whitespace is required after 'PUBLIC'.");
  998. int quoteChar = ReadChar ();
  999. int startPos = CurrentTag.Length;
  1000. int c = 0;
  1001. ClearValueBuffer ();
  1002. while(c != quoteChar)
  1003. {
  1004. c = ReadChar ();
  1005. if(c < 0) throw new XmlException (this as IXmlLineInfo,"Unexpected end of stream in ExternalID.");
  1006. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  1007. throw new XmlException (this as IXmlLineInfo,"character '" + (char)c + "' not allowed for PUBLIC ID");
  1008. if (c != quoteChar)
  1009. AppendValueChar (c);
  1010. }
  1011. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1012. }
  1013. // The reader is positioned on the first character
  1014. // of the name.
  1015. internal string ReadName ()
  1016. {
  1017. return ReadNameOrNmToken(false);
  1018. }
  1019. // The reader is positioned on the first character
  1020. // of the name.
  1021. private string ReadNmToken ()
  1022. {
  1023. return ReadNameOrNmToken(true);
  1024. }
  1025. private string ReadNameOrNmToken(bool isNameToken)
  1026. {
  1027. int ch = PeekChar ();
  1028. if(isNameToken) {
  1029. if (!XmlChar.IsNameChar ((char) ch))
  1030. throw new XmlException (this as IXmlLineInfo,String.Format ("a nmtoken did not start with a legal character {0} ({1})", ch, (char)ch));
  1031. }
  1032. else {
  1033. if (!XmlChar.IsFirstNameChar (ch))
  1034. throw new XmlException (this as IXmlLineInfo,String.Format ("a name did not start with a legal character {0} ({1})", ch, (char)ch));
  1035. }
  1036. nameLength = 0;
  1037. AppendNameChar (ReadChar ());
  1038. while (XmlChar.IsNameChar (PeekChar ())) {
  1039. AppendNameChar (ReadChar ());
  1040. }
  1041. return CreateNameString ();
  1042. }
  1043. // Read the next character and compare it against the
  1044. // specified character.
  1045. private void Expect (int expected)
  1046. {
  1047. int ch = ReadChar ();
  1048. if (ch != expected) {
  1049. throw new XmlException (this as IXmlLineInfo,
  1050. String.Format (
  1051. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  1052. (char)expected,
  1053. expected,
  1054. (char)ch,
  1055. ch));
  1056. }
  1057. }
  1058. private void Expect (string expected)
  1059. {
  1060. int len = expected.Length;
  1061. for(int i=0; i< len; i++)
  1062. Expect (expected[i]);
  1063. }
  1064. // Does not consume the first non-whitespace character.
  1065. private bool SkipWhitespace ()
  1066. {
  1067. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  1068. while (XmlChar.IsWhitespace (PeekChar ()))
  1069. ReadChar ();
  1070. return skipped;
  1071. }
  1072. private string Dereference (string unresolved, bool expandPredefined)
  1073. {
  1074. StringBuilder resolved = new StringBuilder();
  1075. int pos = 0;
  1076. int next = unresolved.IndexOf ('&');
  1077. if(next < 0)
  1078. return unresolved;
  1079. while(next >= 0) {
  1080. if(pos < next)
  1081. resolved.Append (unresolved.Substring (pos, next - pos));// - 1);
  1082. int endPos = unresolved.IndexOf (';', next+1);
  1083. string entityName =
  1084. unresolved.Substring (next + 1, endPos - next - 1);
  1085. if(entityName [0] == '#') {
  1086. char c;
  1087. // character entity
  1088. if(entityName [1] == 'x') {
  1089. // hexadecimal
  1090. c = (char) int.Parse ("0" + entityName.Substring (2),
  1091. System.Globalization.NumberStyles.HexNumber);
  1092. } else {
  1093. // decimal
  1094. c = (char) int.Parse (entityName.Substring (1));
  1095. }
  1096. resolved.Append (c);
  1097. } else {
  1098. char predefined = XmlChar.GetPredefinedEntity (entityName);
  1099. if (expandPredefined && predefined != 0)
  1100. resolved.Append (predefined);
  1101. else
  1102. // With respect to "Value", MS document is helpless
  1103. // and the implemention returns inconsistent value
  1104. // (e.g. XML: "&ent; &amp;ent;" ---> Value: "&ent; &ent;".)
  1105. resolved.Append ("&" + entityName + ";");
  1106. }
  1107. pos = endPos + 1;
  1108. if(pos > unresolved.Length)
  1109. break;
  1110. next = unresolved.IndexOf('&', pos);
  1111. }
  1112. resolved.Append (unresolved.Substring(pos));
  1113. return resolved.ToString();
  1114. }
  1115. private int PeekChar ()
  1116. {
  1117. return currentInput.PeekChar ();
  1118. }
  1119. private int ReadChar ()
  1120. {
  1121. return currentInput.ReadChar ();
  1122. }
  1123. // The reader is positioned on the first character after
  1124. // the leading '<!--'.
  1125. private void ReadComment ()
  1126. {
  1127. currentInput.InitialState = false;
  1128. // ClearValueBuffer ();
  1129. while (PeekChar () != -1) {
  1130. int ch = ReadChar ();
  1131. if (ch == '-' && PeekChar () == '-') {
  1132. ReadChar ();
  1133. if (PeekChar () != '>')
  1134. throw new XmlException (this as IXmlLineInfo,"comments cannot contain '--'");
  1135. ReadChar ();
  1136. break;
  1137. }
  1138. if (XmlConstructs.IsInvalid (ch))
  1139. throw new XmlException (this as IXmlLineInfo,
  1140. "Not allowed character was found.");
  1141. // AppendValueChar ((char)ch);
  1142. }
  1143. /*
  1144. SetProperties (
  1145. XmlNodeType.Comment, // nodeType
  1146. String.Empty, // name
  1147. false, // isEmptyElement
  1148. true, // clearAttributes
  1149. valueBuffer // value
  1150. );
  1151. */
  1152. }
  1153. // The reader is positioned on the first character
  1154. // of the target.
  1155. //
  1156. // It may be xml declaration or processing instruction.
  1157. private void ReadProcessingInstruction ()
  1158. {
  1159. string target = ReadName ();
  1160. if (target == "xml") {
  1161. ReadTextDeclaration ();
  1162. return;
  1163. } else if (target.ToLower () == "xml")
  1164. throw new XmlException (this as IXmlLineInfo,
  1165. "Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1166. currentInput.InitialState = false;
  1167. if (!SkipWhitespace ())
  1168. if (PeekChar () != '?')
  1169. throw new XmlException (this as IXmlLineInfo,
  1170. "Invalid processing instruction name was found.");
  1171. // ClearValueBuffer ();
  1172. while (PeekChar () != -1) {
  1173. int ch = ReadChar ();
  1174. if (ch == '?' && PeekChar () == '>') {
  1175. ReadChar ();
  1176. break;
  1177. }
  1178. // AppendValueChar ((char)ch);
  1179. }
  1180. /*
  1181. SetProperties (
  1182. XmlNodeType.ProcessingInstruction, // nodeType
  1183. target, // name
  1184. false, // isEmptyElement
  1185. true, // clearAttributes
  1186. valueBuffer // value
  1187. );
  1188. */
  1189. }
  1190. // The reader is positioned after "<?xml "
  1191. private void ReadTextDeclaration ()
  1192. {
  1193. if (!currentInput.InitialState)
  1194. throw new XmlException (this as IXmlLineInfo,
  1195. "Text declaration cannot appear in this state.");
  1196. currentInput.InitialState = false;
  1197. SkipWhitespace ();
  1198. // version decl
  1199. if (PeekChar () == 'v') {
  1200. Expect ("version");
  1201. SkipWhitespace ();
  1202. Expect ('=');
  1203. SkipWhitespace ();
  1204. int quoteChar = ReadChar ();
  1205. char [] expect1_0 = new char [3];
  1206. int versionLength = 0;
  1207. switch (quoteChar) {
  1208. case '\'':
  1209. case '"':
  1210. while (PeekChar () != quoteChar) {
  1211. if (PeekChar () == -1)
  1212. throw new XmlException (this as IXmlLineInfo,
  1213. "Invalid version declaration inside text declaration.");
  1214. else if (versionLength == 3)
  1215. throw new XmlException (this as IXmlLineInfo,
  1216. "Invalid version number inside text declaration.");
  1217. else {
  1218. expect1_0 [versionLength] = (char) ReadChar ();
  1219. versionLength++;
  1220. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1221. throw new XmlException (this as IXmlLineInfo,
  1222. "Invalid version number inside text declaration.");
  1223. }
  1224. }
  1225. ReadChar ();
  1226. SkipWhitespace ();
  1227. break;
  1228. default:
  1229. throw new XmlException (this as IXmlLineInfo,
  1230. "Invalid version declaration inside text declaration.");
  1231. }
  1232. }
  1233. if (PeekChar () == 'e') {
  1234. Expect ("encoding");
  1235. SkipWhitespace ();
  1236. Expect ('=');
  1237. SkipWhitespace ();
  1238. int quoteChar = ReadChar ();
  1239. switch (quoteChar) {
  1240. case '\'':
  1241. case '"':
  1242. while (PeekChar () != quoteChar)
  1243. if (ReadChar () == -1)
  1244. throw new XmlException (this as IXmlLineInfo,
  1245. "Invalid encoding declaration inside text declaration.");
  1246. ReadChar ();
  1247. SkipWhitespace ();
  1248. break;
  1249. default:
  1250. throw new XmlException (this as IXmlLineInfo,
  1251. "Invalid encoding declaration inside text declaration.");
  1252. }
  1253. // Encoding value should be checked inside XmlInputStream.
  1254. }
  1255. else
  1256. throw new XmlException (this as IXmlLineInfo,
  1257. "Encoding declaration is mandatory in text declaration.");
  1258. Expect ("?>");
  1259. }
  1260. private void ReadCharacterReference ()
  1261. {
  1262. int value = 0;
  1263. if (PeekChar () == 'x') {
  1264. ReadChar ();
  1265. while (PeekChar () != ';' && PeekChar () != -1) {
  1266. int ch = ReadChar ();
  1267. if (ch >= '0' && ch <= '9')
  1268. value = (value << 4) + ch - '0';
  1269. else if (ch >= 'A' && ch <= 'F')
  1270. value = (value << 4) + ch - 'A' + 10;
  1271. else if (ch >= 'a' && ch <= 'f')
  1272. value = (value << 4) + ch - 'a' + 10;
  1273. else
  1274. throw new XmlException (this as IXmlLineInfo,
  1275. String.Format (
  1276. "invalid hexadecimal digit: {0} (#x{1:X})",
  1277. (char)ch,
  1278. ch));
  1279. }
  1280. } else {
  1281. while (PeekChar () != ';' && PeekChar () != -1) {
  1282. int ch = ReadChar ();
  1283. if (ch >= '0' && ch <= '9')
  1284. value = value * 10 + ch - '0';
  1285. else
  1286. throw new XmlException (this as IXmlLineInfo,
  1287. String.Format (
  1288. "invalid decimal digit: {0} (#x{1:X})",
  1289. (char)ch,
  1290. ch));
  1291. }
  1292. }
  1293. ReadChar (); // ';'
  1294. // There is no way to save surrogate pairs...
  1295. if (value < 0xffff && !XmlConstructs.IsValid (value))
  1296. throw new XmlException (this as IXmlLineInfo,
  1297. "Referenced character was not allowed in XML.");
  1298. AppendValueChar (value);
  1299. }
  1300. private void AppendNameChar (int ch)
  1301. {
  1302. CheckNameCapacity ();
  1303. nameBuffer [nameLength++] = (char)ch;
  1304. }
  1305. private void CheckNameCapacity ()
  1306. {
  1307. if (nameLength == nameCapacity) {
  1308. nameCapacity = nameCapacity * 2;
  1309. char [] oldNameBuffer = nameBuffer;
  1310. nameBuffer = new char [nameCapacity];
  1311. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1312. }
  1313. }
  1314. private string CreateNameString ()
  1315. {
  1316. return DTD.NameTable.Add (nameBuffer, 0, nameLength);
  1317. }
  1318. private void AppendValueChar (int ch)
  1319. {
  1320. valueBuffer.Append ((char)ch);
  1321. }
  1322. private string CreateValueString ()
  1323. {
  1324. return valueBuffer.ToString ();
  1325. }
  1326. private void ClearValueBuffer ()
  1327. {
  1328. valueBuffer.Length = 0;
  1329. }
  1330. // The reader is positioned on the quote character.
  1331. // *Keeps quote char* to value to get_QuoteChar() correctly.
  1332. private string ReadDefaultAttribute ()
  1333. {
  1334. ClearValueBuffer ();
  1335. int quoteChar = ReadChar ();
  1336. if (quoteChar != '\'' && quoteChar != '\"')
  1337. throw new XmlException (this as IXmlLineInfo,"an attribute value was not quoted");
  1338. AppendValueChar (quoteChar);
  1339. while (PeekChar () != quoteChar) {
  1340. int ch = ReadChar ();
  1341. switch (ch)
  1342. {
  1343. case '<':
  1344. throw new XmlException (this as IXmlLineInfo,"attribute values cannot contain '<'");
  1345. case -1:
  1346. throw new XmlException (this as IXmlLineInfo,"unexpected end of file in an attribute value");
  1347. case '&':
  1348. AppendValueChar (ch);
  1349. if (PeekChar () == '#')
  1350. break;
  1351. // Check XML 1.0 section 3.1 WFC.
  1352. string entName = ReadName ();
  1353. Expect (';');
  1354. if (XmlChar.GetPredefinedEntity (entName) == 0) {
  1355. DTDEntityDeclaration entDecl =
  1356. DTD == null ? null : DTD.EntityDecls [entName];
  1357. if (entDecl == null || entDecl.SystemId != null)
  1358. // WFC: Entity Declared (see 4.1)
  1359. if (DTD.IsStandalone || (DTD.SystemId == null && !DTD.InternalSubsetHasPEReference))
  1360. throw new XmlException (this as IXmlLineInfo,
  1361. "Reference to external entities is not allowed in attribute value.");
  1362. }
  1363. valueBuffer.Append (entName);
  1364. AppendValueChar (';');
  1365. break;
  1366. default:
  1367. AppendValueChar (ch);
  1368. break;
  1369. }
  1370. }
  1371. ReadChar (); // quoteChar
  1372. AppendValueChar (quoteChar);
  1373. return CreateValueString ();
  1374. }
  1375. private void PushParserInput (string url)
  1376. {
  1377. Uri baseUri = null;
  1378. try {
  1379. baseUri = new Uri (DTD.BaseURI);
  1380. } catch (UriFormatException) {
  1381. }
  1382. Uri absUri = DTD.Resolver.ResolveUri (baseUri, url);
  1383. string absPath = absUri.ToString ();
  1384. foreach (XmlParserInput i in parserInputStack.ToArray ()) {
  1385. if (i.BaseURI == absPath)
  1386. throw new XmlException (this as IXmlLineInfo, "Nested inclusion is not allowed: " + url);
  1387. }
  1388. parserInputStack.Push (currentInput);
  1389. try {
  1390. currentInput = new XmlParserInput (new XmlStreamReader (url, false, DTD.Resolver, DTD.BaseURI), absPath);
  1391. } catch (Exception ex) { // FIXME: (wishlist) Bad exception catch ;-(
  1392. int line = currentInput == null ? 0 : currentInput.LineNumber;
  1393. int col = currentInput == null ? 0 : currentInput.LinePosition;
  1394. string bu = (currentInput == null) ? String.Empty : currentInput.BaseURI;
  1395. DTD.AddError (new XmlSchemaException ("Specified external entity not found. Target URL is " + url + " .",
  1396. line, col, null, bu, ex));
  1397. currentInput = new XmlParserInput (new StringReader (String.Empty), absPath);
  1398. }
  1399. }
  1400. private void PopParserInput ()
  1401. {
  1402. currentInput = parserInputStack.Pop () as XmlParserInput;
  1403. }
  1404. }
  1405. }