DTDReader.cs 46 KB

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