DTDReader.cs 48 KB

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