DTDReader.cs 44 KB

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