DTDReader.cs 42 KB

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