2
0

DTDReader.cs 48 KB

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