DTDReader.cs 42 KB

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