DTDReader.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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.AllowTextDecl = 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. DTDParameterEntityDeclaration peDecl = GetPEDecl (peName);
  175. if (peDecl == null)
  176. break;
  177. currentInput.PushPEBuffer (peDecl);
  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.AllowTextDecl = 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.XmlResolver = DTD.Resolver;
  541. decl.Name = ReadName ();
  542. if (!SkipWhitespace ())
  543. throw NotWFError ("Whitespace is required after name in DTD parameter entity declaration.");
  544. if (PeekChar () == 'S' || PeekChar () == 'P') {
  545. // read publicId/systemId
  546. ReadExternalID ();
  547. decl.PublicId = cachedPublicId;
  548. decl.SystemId = cachedSystemId;
  549. SkipWhitespace ();
  550. decl.Resolve ();
  551. ResolveExternalEntityReplacementText (decl);
  552. } else {
  553. TryExpandPERef ();
  554. int quoteChar = ReadChar ();
  555. if (quoteChar != '\'' && quoteChar != '"')
  556. throw NotWFError ("quotation char was expected.");
  557. ClearValueBuffer ();
  558. bool loop = true;
  559. while (loop) {
  560. int c = ReadChar ();
  561. switch (c) {
  562. case -1:
  563. throw NotWFError ("unexpected end of stream in entity value definition.");
  564. case '"':
  565. if (quoteChar == '"')
  566. loop = false;
  567. else
  568. AppendValueChar ('"');
  569. break;
  570. case '\'':
  571. if (quoteChar == '\'')
  572. loop = false;
  573. else
  574. AppendValueChar ('\'');
  575. break;
  576. default:
  577. if (XmlChar.IsInvalid (c))
  578. throw NotWFError ("Invalid character was used to define parameter entity.");
  579. AppendValueChar (c);
  580. break;
  581. }
  582. }
  583. decl.LiteralEntityValue = CreateValueString ();
  584. ClearValueBuffer ();
  585. ResolveInternalEntityReplacementText (decl);
  586. }
  587. ExpectAfterWhitespace ('>');
  588. if (DTD.PEDecls [decl.Name] == null) {
  589. DTD.PEDecls.Add (decl.Name, decl);
  590. }
  591. }
  592. private void ResolveExternalEntityReplacementText (DTDEntityBase decl)
  593. {
  594. if (decl.SystemId != null && decl.SystemId.Length > 0) {
  595. // FIXME: not always it should be read in Element context
  596. XmlTextReader xtr = new XmlTextReader (decl.LiteralEntityValue, XmlNodeType.Element, null);
  597. if (decl is DTDEntityDeclaration && DTD.EntityDecls [decl.Name] == null) {
  598. // GE - also checked as valid contents
  599. StringBuilder sb = new StringBuilder ();
  600. xtr.Normalization = this.Normalization;
  601. xtr.Read ();
  602. while (!xtr.EOF)
  603. sb.Append (xtr.ReadOuterXml ());
  604. decl.ReplacementText = sb.ToString ();
  605. }
  606. else
  607. // PE
  608. decl.ReplacementText = xtr.GetRemainder ().ReadToEnd ();
  609. }
  610. else
  611. decl.ReplacementText = decl.LiteralEntityValue;
  612. }
  613. private void ResolveInternalEntityReplacementText (DTDEntityBase decl)
  614. {
  615. string value = decl.LiteralEntityValue;
  616. int len = value.Length;
  617. ClearValueBuffer ();
  618. for (int i = 0; i < len; i++) {
  619. int ch = value [i];
  620. int end = 0;
  621. string name;
  622. switch (ch) {
  623. case '&':
  624. i++;
  625. end = value.IndexOf (';', i);
  626. if (end < i + 1)
  627. throw new XmlException (decl, decl.BaseURI, "Invalid reference markup.");
  628. // expand charref
  629. if (value [i] == '#') {
  630. i++;
  631. ch = GetCharacterReference (decl, value, ref i, end);
  632. if (XmlChar.IsInvalid (ch))
  633. throw NotWFError ("Invalid character was used to define parameter entity.");
  634. } else {
  635. name = value.Substring (i, end - i);
  636. // don't expand "general" entity.
  637. AppendValueChar ('&');
  638. valueBuffer.Append (name);
  639. AppendValueChar (';');
  640. i = end;
  641. break;
  642. }
  643. if (XmlChar.IsInvalid (ch))
  644. throw new XmlException (decl, decl.BaseURI, "Invalid character was found in the entity declaration.");
  645. AppendValueChar (ch);
  646. break;
  647. case '%':
  648. i++;
  649. end = value.IndexOf (';', i);
  650. if (end < i + 1)
  651. throw new XmlException (decl, decl.BaseURI, "Invalid reference markup.");
  652. name = value.Substring (i, end - i);
  653. valueBuffer.Append (GetPEValue (name));
  654. i = end;
  655. break;
  656. default:
  657. AppendValueChar (ch);
  658. break;
  659. }
  660. }
  661. decl.ReplacementText = CreateValueString ();
  662. ClearValueBuffer ();
  663. }
  664. private int GetCharacterReference (DTDEntityBase li, string value, ref int index, int end)
  665. {
  666. int ret = 0;
  667. if (value [index] == 'x') {
  668. try {
  669. ret = int.Parse (value.Substring (index + 1, end - index - 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  670. } catch (FormatException) {
  671. throw new XmlException (li, li.BaseURI, "Invalid number for a character reference.");
  672. }
  673. } else {
  674. try {
  675. ret = int.Parse (value.Substring (index, end - index), CultureInfo.InvariantCulture);
  676. } catch (FormatException) {
  677. throw new XmlException (li, li.BaseURI, "Invalid number for a character reference.");
  678. }
  679. }
  680. index = end;
  681. return ret;
  682. }
  683. private string GetPEValue (string peName)
  684. {
  685. DTDParameterEntityDeclaration peDecl = GetPEDecl (peName);
  686. return peDecl != null ?
  687. peDecl.ReplacementText : String.Empty;
  688. }
  689. private DTDParameterEntityDeclaration GetPEDecl (string peName)
  690. {
  691. DTDParameterEntityDeclaration peDecl =
  692. DTD.PEDecls [peName] as DTDParameterEntityDeclaration;
  693. if (peDecl != null) {
  694. if (peDecl.IsInternalSubset)
  695. throw NotWFError ("Parameter entity is not allowed in internal subset entity '" + peName + "'");
  696. return peDecl;
  697. }
  698. // See XML 1.0 section 4.1 for both WFC and VC.
  699. if ((DTD.SystemId == null && !DTD.InternalSubsetHasPEReference) || DTD.IsStandalone)
  700. throw NotWFError (String.Format ("Parameter entity '{0}' not found.",peName));
  701. HandleError (new XmlSchemaException (
  702. "Parameter entity " + peName + " not found.", null));
  703. return null;
  704. }
  705. private bool TryExpandPERef ()
  706. {
  707. if (PeekChar () != '%')
  708. return false;
  709. while (PeekChar () == '%') {
  710. TryExpandPERefSpaceKeep ();
  711. SkipWhitespace ();
  712. }
  713. return true;
  714. }
  715. // Tries to expand parameter entities, but it should not skip spaces
  716. private bool TryExpandPERefSpaceKeep ()
  717. {
  718. if (PeekChar () == '%') {
  719. if (this.processingInternalSubset)
  720. throw NotWFError ("Parameter entity reference is not allowed inside internal subset.");
  721. ReadChar ();
  722. ExpandPERef ();
  723. return true;
  724. }
  725. else
  726. return false;
  727. }
  728. // reader is positioned after '%'
  729. private void ExpandPERef ()
  730. {
  731. string peName = ReadName ();
  732. Expect (';');
  733. DTDParameterEntityDeclaration peDecl =
  734. DTD.PEDecls [peName] as DTDParameterEntityDeclaration;
  735. if (peDecl == null) {
  736. HandleError (new XmlSchemaException ("Parameter entity " + peName + " not found.", null));
  737. return; // do nothing
  738. }
  739. currentInput.PushPEBuffer (peDecl);
  740. }
  741. // The reader is positioned on the head of the name.
  742. private DTDEntityDeclaration ReadEntityDecl ()
  743. {
  744. DTDEntityDeclaration decl = new DTDEntityDeclaration (DTD);
  745. decl.BaseURI = BaseURI;
  746. decl.XmlResolver = DTD.Resolver;
  747. decl.IsInternalSubset = this.processingInternalSubset;
  748. TryExpandPERef ();
  749. decl.Name = ReadName ();
  750. if (!SkipWhitespace ())
  751. throw NotWFError ("Whitespace is required between name and content in DTD entity declaration.");
  752. TryExpandPERef ();
  753. if (PeekChar () == 'S' || PeekChar () == 'P') {
  754. // external entity
  755. ReadExternalID ();
  756. decl.PublicId = cachedPublicId;
  757. decl.SystemId = cachedSystemId;
  758. if (SkipWhitespace ()) {
  759. if (PeekChar () == 'N') {
  760. // NDataDecl
  761. Expect ("NDATA");
  762. if (!SkipWhitespace ())
  763. throw NotWFError ("Whitespace is required after NDATA.");
  764. decl.NotationName = ReadName (); // ndata_name
  765. }
  766. }
  767. if (decl.NotationName == null) {
  768. decl.Resolve ();
  769. ResolveExternalEntityReplacementText (decl);
  770. } else {
  771. // Unparsed entity.
  772. decl.LiteralEntityValue = String.Empty;
  773. decl.ReplacementText = String.Empty;
  774. }
  775. }
  776. else {
  777. // literal entity
  778. ReadEntityValueDecl (decl);
  779. ResolveInternalEntityReplacementText (decl);
  780. }
  781. SkipWhitespace ();
  782. // This expanding is only allowed as a non-validating parser.
  783. TryExpandPERef ();
  784. Expect ('>');
  785. return decl;
  786. }
  787. private void ReadEntityValueDecl (DTDEntityDeclaration decl)
  788. {
  789. SkipWhitespace ();
  790. // quotation char will be finally removed on unescaping
  791. int quoteChar = ReadChar ();
  792. if (quoteChar != '\'' && quoteChar != '"')
  793. throw NotWFError ("quotation char was expected.");
  794. ClearValueBuffer ();
  795. while (PeekChar () != quoteChar) {
  796. int ch = ReadChar ();
  797. switch (ch) {
  798. case '%':
  799. string name = ReadName ();
  800. Expect (';');
  801. if (decl.IsInternalSubset)
  802. throw NotWFError (String.Format ("Parameter entity is not allowed in internal subset entity '{0}'", name));
  803. valueBuffer.Append (GetPEValue (name));
  804. break;
  805. case -1:
  806. throw NotWFError ("unexpected end of stream.");
  807. default:
  808. if (this.normalization && XmlChar.IsInvalid (ch))
  809. throw NotWFError ("Invalid character was found in the entity declaration.");
  810. AppendValueChar (ch);
  811. break;
  812. }
  813. }
  814. // string value = Dereference (CreateValueString (), false);
  815. string value = CreateValueString ();
  816. ClearValueBuffer ();
  817. Expect (quoteChar);
  818. decl.LiteralEntityValue = value;
  819. }
  820. private DTDAttListDeclaration ReadAttListDecl ()
  821. {
  822. TryExpandPERefSpaceKeep ();
  823. if (!SkipWhitespace ())
  824. throw NotWFError ("Whitespace is required between ATTLIST and name in DTD attlist declaration.");
  825. TryExpandPERef ();
  826. string name = ReadName (); // target element name
  827. DTDAttListDeclaration decl =
  828. DTD.AttListDecls [name] as DTDAttListDeclaration;
  829. if (decl == null)
  830. decl = new DTDAttListDeclaration (DTD);
  831. decl.IsInternalSubset = this.processingInternalSubset;
  832. decl.Name = name;
  833. if (!SkipWhitespace ())
  834. if (PeekChar () != '>')
  835. throw NotWFError ("Whitespace is required between name and content in non-empty DTD attlist declaration.");
  836. TryExpandPERef ();
  837. while (XmlChar.IsNameChar (PeekChar ())) {
  838. DTDAttributeDefinition def = ReadAttributeDefinition ();
  839. // There must not be two or more ID attributes.
  840. if (def.Datatype.TokenizedType == XmlTokenizedType.ID) {
  841. for (int i = 0; i < decl.Definitions.Count; i++) {
  842. DTDAttributeDefinition d = decl [i];
  843. if (d.Datatype.TokenizedType == XmlTokenizedType.ID) {
  844. HandleError (new XmlSchemaException ("AttList declaration must not contain two or more ID attributes.",
  845. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  846. break;
  847. }
  848. }
  849. }
  850. if (decl [def.Name] == null)
  851. decl.Add (def);
  852. SkipWhitespace ();
  853. TryExpandPERef ();
  854. }
  855. SkipWhitespace ();
  856. // This expanding is only allowed as a non-validating parser.
  857. TryExpandPERef ();
  858. Expect ('>');
  859. return decl;
  860. }
  861. private DTDAttributeDefinition ReadAttributeDefinition ()
  862. {
  863. DTDAttributeDefinition def = new DTDAttributeDefinition (DTD);
  864. def.IsInternalSubset = this.processingInternalSubset;
  865. // attr_name
  866. TryExpandPERef ();
  867. def.Name = ReadName ();
  868. if (!SkipWhitespace ())
  869. throw NotWFError ("Whitespace is required between name and content in DTD attribute definition.");
  870. // attr_value
  871. TryExpandPERef ();
  872. switch(PeekChar ()) {
  873. case 'C': // CDATA
  874. Expect ("CDATA");
  875. def.Datatype = XmlSchemaDatatype.FromName ("normalizedString", XmlSchema.Namespace);
  876. break;
  877. case 'I': // ID, IDREF, IDREFS
  878. Expect ("ID");
  879. if(PeekChar () == 'R') {
  880. Expect ("REF");
  881. if(PeekChar () == 'S') {
  882. // IDREFS
  883. ReadChar ();
  884. def.Datatype = XmlSchemaDatatype.FromName ("IDREFS", XmlSchema.Namespace);
  885. }
  886. else // IDREF
  887. def.Datatype = XmlSchemaDatatype.FromName ("IDREF", XmlSchema.Namespace);
  888. }
  889. else // ID
  890. def.Datatype = XmlSchemaDatatype.FromName ("ID", XmlSchema.Namespace);
  891. break;
  892. case 'E': // ENTITY, ENTITIES
  893. Expect ("ENTIT");
  894. switch(ReadChar ()) {
  895. case 'Y': // ENTITY
  896. def.Datatype = XmlSchemaDatatype.FromName ("ENTITY", XmlSchema.Namespace);
  897. break;
  898. case 'I': // ENTITIES
  899. Expect ("ES");
  900. def.Datatype = XmlSchemaDatatype.FromName ("ENTITIES", XmlSchema.Namespace);
  901. break;
  902. }
  903. break;
  904. case 'N': // NMTOKEN, NMTOKENS, NOTATION
  905. ReadChar ();
  906. switch(PeekChar ()) {
  907. case 'M':
  908. Expect ("MTOKEN");
  909. if(PeekChar ()=='S') { // NMTOKENS
  910. ReadChar ();
  911. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKENS", XmlSchema.Namespace);
  912. }
  913. else // NMTOKEN
  914. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN", XmlSchema.Namespace);
  915. break;
  916. case 'O':
  917. Expect ("OTATION");
  918. def.Datatype = XmlSchemaDatatype.FromName ("NOTATION", XmlSchema.Namespace);
  919. if (!SkipWhitespace ())
  920. throw NotWFError ("Whitespace is required between name and content in DTD attribute definition.");
  921. Expect ('(');
  922. SkipWhitespace ();
  923. def.EnumeratedNotations.Add (ReadName ()); // notation name
  924. SkipWhitespace ();
  925. while(PeekChar () == '|') {
  926. ReadChar ();
  927. SkipWhitespace ();
  928. def.EnumeratedNotations.Add (ReadName ()); // notation name
  929. SkipWhitespace ();
  930. }
  931. Expect (')');
  932. break;
  933. default:
  934. throw NotWFError ("attribute declaration syntax error.");
  935. }
  936. break;
  937. default: // Enumerated Values
  938. def.Datatype = XmlSchemaDatatype.FromName ("NMTOKEN", XmlSchema.Namespace);
  939. TryExpandPERef ();
  940. Expect ('(');
  941. SkipWhitespace ();
  942. def.EnumeratedAttributeDeclaration.Add (
  943. def.Datatype.Normalize (ReadNmToken ())); // enum value
  944. SkipWhitespace ();
  945. while(PeekChar () == '|') {
  946. ReadChar ();
  947. SkipWhitespace ();
  948. def.EnumeratedAttributeDeclaration.Add (
  949. def.Datatype.Normalize (ReadNmToken ())); // enum value
  950. SkipWhitespace ();
  951. }
  952. Expect (')');
  953. break;
  954. }
  955. TryExpandPERefSpaceKeep ();
  956. if (!SkipWhitespace ())
  957. throw NotWFError ("Whitespace is required between type and occurence in DTD attribute definition.");
  958. // def_value
  959. ReadAttributeDefaultValue (def);
  960. return def;
  961. }
  962. private void ReadAttributeDefaultValue (DTDAttributeDefinition def)
  963. {
  964. if(PeekChar () == '#')
  965. {
  966. ReadChar ();
  967. switch(PeekChar ())
  968. {
  969. case 'R':
  970. Expect ("REQUIRED");
  971. def.OccurenceType = DTDAttributeOccurenceType.Required;
  972. break;
  973. case 'I':
  974. Expect ("IMPLIED");
  975. def.OccurenceType = DTDAttributeOccurenceType.Optional;
  976. break;
  977. case 'F':
  978. Expect ("FIXED");
  979. def.OccurenceType = DTDAttributeOccurenceType.Fixed;
  980. if (!SkipWhitespace ())
  981. throw NotWFError ("Whitespace is required between FIXED and actual value in DTD attribute definition.");
  982. def.UnresolvedDefaultValue = ReadDefaultAttribute ();
  983. break;
  984. }
  985. } else {
  986. // one of the enumerated value
  987. SkipWhitespace ();
  988. TryExpandPERef ();
  989. def.UnresolvedDefaultValue = ReadDefaultAttribute ();
  990. }
  991. // VC: If default value exists, it should be valid.
  992. if (def.DefaultValue != null) {
  993. string normalized = def.Datatype.Normalize (def.DefaultValue);
  994. bool breakup = false;
  995. object parsed = null;
  996. // enumeration validity
  997. if (def.EnumeratedAttributeDeclaration.Count > 0) {
  998. if (!def.EnumeratedAttributeDeclaration.Contains (normalized)) {
  999. HandleError (new XmlSchemaException ("Default value is not one of the enumerated values.",
  1000. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  1001. breakup = true;
  1002. }
  1003. }
  1004. if (def.EnumeratedNotations.Count > 0) {
  1005. if (!def.EnumeratedNotations.Contains (normalized)) {
  1006. HandleError (new XmlSchemaException ("Default value is not one of the enumerated notation values.",
  1007. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  1008. breakup = true;
  1009. }
  1010. }
  1011. // type based validity
  1012. if (!breakup) {
  1013. try {
  1014. parsed = def.Datatype.ParseValue (normalized, DTD.NameTable, null);
  1015. } catch (Exception ex) { // FIXME: (wishlist) bad catch ;-(
  1016. HandleError (new XmlSchemaException ("Invalid default value for ENTITY type.",
  1017. def.LineNumber, def.LinePosition, null, def.BaseURI, ex));
  1018. breakup = true;
  1019. }
  1020. }
  1021. if (!breakup) {
  1022. switch (def.Datatype.TokenizedType) {
  1023. case XmlTokenizedType.ENTITY:
  1024. if (DTD.EntityDecls [normalized] == null)
  1025. HandleError (new XmlSchemaException ("Specified entity declaration used by default attribute value was not found.",
  1026. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  1027. break;
  1028. case XmlTokenizedType.ENTITIES:
  1029. string [] entities = parsed as string [];
  1030. for (int i = 0; i < entities.Length; i++) {
  1031. string entity = entities [i];
  1032. if (DTD.EntityDecls [entity] == null)
  1033. HandleError (new XmlSchemaException ("Specified entity declaration used by default attribute value was not found.",
  1034. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  1035. }
  1036. break;
  1037. }
  1038. }
  1039. }
  1040. // Extra ID attribute validity check.
  1041. if (def.Datatype != null && def.Datatype.TokenizedType == XmlTokenizedType.ID)
  1042. if (def.UnresolvedDefaultValue != null)
  1043. HandleError (new XmlSchemaException ("ID attribute must not have fixed value constraint.",
  1044. def.LineNumber, def.LinePosition, null, def.BaseURI, null));
  1045. }
  1046. private DTDNotationDeclaration ReadNotationDecl()
  1047. {
  1048. DTDNotationDeclaration decl = new DTDNotationDeclaration (DTD);
  1049. if (!SkipWhitespace ())
  1050. throw NotWFError ("Whitespace is required between NOTATION and name in DTD notation declaration.");
  1051. TryExpandPERef ();
  1052. decl.Name = ReadName (); // notation name
  1053. /*
  1054. if (namespaces) { // copy from SetProperties ;-)
  1055. int indexOfColon = decl.Name.IndexOf (':');
  1056. if (indexOfColon == -1) {
  1057. decl.Prefix = String.Empty;
  1058. decl.LocalName = decl.Name;
  1059. } else {
  1060. decl.Prefix = decl.Name.Substring (0, indexOfColon);
  1061. decl.LocalName = decl.Name.Substring (indexOfColon + 1);
  1062. }
  1063. } else {
  1064. */
  1065. decl.Prefix = String.Empty;
  1066. decl.LocalName = decl.Name;
  1067. // }
  1068. SkipWhitespace ();
  1069. if(PeekChar () == 'P') {
  1070. decl.PublicId = ReadPubidLiteral ();
  1071. bool wsSkipped = SkipWhitespace ();
  1072. if (PeekChar () == '\'' || PeekChar () == '"') {
  1073. if (!wsSkipped)
  1074. throw NotWFError ("Whitespace is required between public id and system id.");
  1075. decl.SystemId = ReadSystemLiteral (false);
  1076. SkipWhitespace ();
  1077. }
  1078. } else if(PeekChar () == 'S') {
  1079. decl.SystemId = ReadSystemLiteral (true);
  1080. SkipWhitespace ();
  1081. }
  1082. if(decl.PublicId == null && decl.SystemId == null)
  1083. throw NotWFError ("public or system declaration required for \"NOTATION\" declaration.");
  1084. // This expanding is only allowed as a non-validating parser.
  1085. TryExpandPERef ();
  1086. Expect ('>');
  1087. return decl;
  1088. }
  1089. private void ReadExternalID () {
  1090. switch (PeekChar ()) {
  1091. case 'S':
  1092. cachedSystemId = ReadSystemLiteral (true);
  1093. break;
  1094. case 'P':
  1095. cachedPublicId = ReadPubidLiteral ();
  1096. if (!SkipWhitespace ())
  1097. throw NotWFError ("Whitespace is required between PUBLIC id and SYSTEM id.");
  1098. cachedSystemId = ReadSystemLiteral (false);
  1099. break;
  1100. }
  1101. }
  1102. // The reader is positioned on the first 'S' of "SYSTEM".
  1103. private string ReadSystemLiteral (bool expectSYSTEM)
  1104. {
  1105. if(expectSYSTEM) {
  1106. Expect ("SYSTEM");
  1107. if (!SkipWhitespace ())
  1108. throw NotWFError ("Whitespace is required after 'SYSTEM'.");
  1109. }
  1110. else
  1111. SkipWhitespace ();
  1112. int quoteChar = ReadChar (); // apos or quot
  1113. int c = 0;
  1114. ClearValueBuffer ();
  1115. while (c != quoteChar) {
  1116. c = ReadChar ();
  1117. if (c < 0)
  1118. throw NotWFError ("Unexpected end of stream in ExternalID.");
  1119. if (c != quoteChar)
  1120. AppendValueChar (c);
  1121. }
  1122. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1123. }
  1124. private string ReadPubidLiteral()
  1125. {
  1126. Expect ("PUBLIC");
  1127. if (!SkipWhitespace ())
  1128. throw NotWFError ("Whitespace is required after 'PUBLIC'.");
  1129. int quoteChar = ReadChar ();
  1130. int c = 0;
  1131. ClearValueBuffer ();
  1132. while(c != quoteChar)
  1133. {
  1134. c = ReadChar ();
  1135. if(c < 0) throw NotWFError ("Unexpected end of stream in ExternalID.");
  1136. if(c != quoteChar && !XmlChar.IsPubidChar (c))
  1137. throw NotWFError (String.Format ("character '{0}' not allowed for PUBLIC ID", (char) c));
  1138. if (c != quoteChar)
  1139. AppendValueChar (c);
  1140. }
  1141. return CreateValueString (); //currentTag.ToString (startPos, currentTag.Length - 1 - startPos);
  1142. }
  1143. // The reader is positioned on the first character
  1144. // of the name.
  1145. internal string ReadName ()
  1146. {
  1147. return ReadNameOrNmToken(false);
  1148. }
  1149. // The reader is positioned on the first character
  1150. // of the name.
  1151. private string ReadNmToken ()
  1152. {
  1153. return ReadNameOrNmToken(true);
  1154. }
  1155. private string ReadNameOrNmToken(bool isNameToken)
  1156. {
  1157. int ch = PeekChar ();
  1158. if(isNameToken) {
  1159. if (!XmlChar.IsNameChar (ch))
  1160. throw NotWFError (String.Format ("a nmtoken did not start with a legal character {0} ({1})", ch, (char) ch));
  1161. }
  1162. else {
  1163. if (!XmlChar.IsFirstNameChar (ch))
  1164. throw NotWFError (String.Format ("a name did not start with a legal character {0} ({1})", ch, (char) ch));
  1165. }
  1166. nameLength = 0;
  1167. AppendNameChar (ReadChar ());
  1168. while (XmlChar.IsNameChar (PeekChar ())) {
  1169. AppendNameChar (ReadChar ());
  1170. }
  1171. return CreateNameString ();
  1172. }
  1173. // Read the next character and compare it against the
  1174. // specified character.
  1175. private void Expect (int expected)
  1176. {
  1177. int ch = ReadChar ();
  1178. if (ch != expected) {
  1179. throw NotWFError (String.Format (CultureInfo.InvariantCulture,
  1180. "expected '{0}' ({1:X}) but found '{2}' ({3:X})",
  1181. (char) expected,
  1182. expected,
  1183. (char) ch,
  1184. ch));
  1185. }
  1186. }
  1187. private void Expect (string expected)
  1188. {
  1189. int len = expected.Length;
  1190. for (int i=0; i< len; i++)
  1191. Expect (expected [i]);
  1192. }
  1193. private void ExpectAfterWhitespace (char c)
  1194. {
  1195. while (true) {
  1196. int i = ReadChar ();
  1197. if (XmlChar.IsWhitespace (i))
  1198. continue;
  1199. if (c != i)
  1200. throw NotWFError (String.Format (CultureInfo.InvariantCulture, "Expected {0} but found {1} [{2}].", c, (char) i, i));
  1201. break;
  1202. }
  1203. }
  1204. // Does not consume the first non-whitespace character.
  1205. private bool SkipWhitespace ()
  1206. {
  1207. bool skipped = XmlChar.IsWhitespace (PeekChar ());
  1208. while (XmlChar.IsWhitespace (PeekChar ()))
  1209. ReadChar ();
  1210. return skipped;
  1211. }
  1212. private int PeekChar ()
  1213. {
  1214. return currentInput.PeekChar ();
  1215. }
  1216. private int ReadChar ()
  1217. {
  1218. return currentInput.ReadChar ();
  1219. }
  1220. // The reader is positioned on the first character after
  1221. // the leading '<!--'.
  1222. private void ReadComment ()
  1223. {
  1224. currentInput.AllowTextDecl = false;
  1225. while (PeekChar () != -1) {
  1226. int ch = ReadChar ();
  1227. if (ch == '-' && PeekChar () == '-') {
  1228. ReadChar ();
  1229. if (PeekChar () != '>')
  1230. throw NotWFError ("comments cannot contain '--'");
  1231. ReadChar ();
  1232. break;
  1233. }
  1234. if (XmlChar.IsInvalid (ch))
  1235. throw NotWFError ("Not allowed character was found.");
  1236. }
  1237. }
  1238. // The reader is positioned on the first character
  1239. // of the target.
  1240. //
  1241. // It may be xml declaration or processing instruction.
  1242. private void ReadProcessingInstruction ()
  1243. {
  1244. string target = ReadName ();
  1245. if (target == "xml") {
  1246. ReadTextDeclaration ();
  1247. return;
  1248. } else if (String.Compare (target, "xml", true, CultureInfo.InvariantCulture) == 0)
  1249. throw NotWFError ("Not allowed processing instruction name which starts with 'X', 'M', 'L' was found.");
  1250. currentInput.AllowTextDecl = false;
  1251. if (!SkipWhitespace ())
  1252. if (PeekChar () != '?')
  1253. throw NotWFError ("Invalid processing instruction name was found.");
  1254. while (PeekChar () != -1) {
  1255. int ch = ReadChar ();
  1256. if (ch == '?' && PeekChar () == '>') {
  1257. ReadChar ();
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. // The reader is positioned after "<?xml "
  1263. private void ReadTextDeclaration ()
  1264. {
  1265. if (!currentInput.AllowTextDecl)
  1266. throw NotWFError ("Text declaration cannot appear in this state.");
  1267. currentInput.AllowTextDecl = false;
  1268. SkipWhitespace ();
  1269. // version decl
  1270. if (PeekChar () == 'v') {
  1271. Expect ("version");
  1272. ExpectAfterWhitespace ('=');
  1273. SkipWhitespace ();
  1274. int quoteChar = ReadChar ();
  1275. char [] expect1_0 = new char [3];
  1276. int versionLength = 0;
  1277. switch (quoteChar) {
  1278. case '\'':
  1279. case '"':
  1280. while (PeekChar () != quoteChar) {
  1281. if (PeekChar () == -1)
  1282. throw NotWFError ("Invalid version declaration inside text declaration.");
  1283. else if (versionLength == 3)
  1284. throw NotWFError ("Invalid version number inside text declaration.");
  1285. else {
  1286. expect1_0 [versionLength] = (char) ReadChar ();
  1287. versionLength++;
  1288. if (versionLength == 3 && new String (expect1_0) != "1.0")
  1289. throw NotWFError ("Invalid version number inside text declaration.");
  1290. }
  1291. }
  1292. ReadChar ();
  1293. SkipWhitespace ();
  1294. break;
  1295. default:
  1296. throw NotWFError ("Invalid version declaration inside text declaration.");
  1297. }
  1298. }
  1299. if (PeekChar () == 'e') {
  1300. Expect ("encoding");
  1301. ExpectAfterWhitespace ('=');
  1302. SkipWhitespace ();
  1303. int quoteChar = ReadChar ();
  1304. switch (quoteChar) {
  1305. case '\'':
  1306. case '"':
  1307. while (PeekChar () != quoteChar)
  1308. if (ReadChar () == -1)
  1309. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1310. ReadChar ();
  1311. SkipWhitespace ();
  1312. break;
  1313. default:
  1314. throw NotWFError ("Invalid encoding declaration inside text declaration.");
  1315. }
  1316. // Encoding value should be checked inside XmlInputStream.
  1317. }
  1318. else
  1319. throw NotWFError ("Encoding declaration is mandatory in text declaration.");
  1320. Expect ("?>");
  1321. }
  1322. // Note that now this method behaves differently from
  1323. // XmlTextReader's one. It calles AppendValueChar() internally.
  1324. private int ReadCharacterReference ()
  1325. {
  1326. int value = 0;
  1327. if (PeekChar () == 'x') {
  1328. ReadChar ();
  1329. while (PeekChar () != ';' && PeekChar () != -1) {
  1330. int ch = ReadChar ();
  1331. if (ch >= '0' && ch <= '9')
  1332. value = (value << 4) + ch - '0';
  1333. else if (ch >= 'A' && ch <= 'F')
  1334. value = (value << 4) + ch - 'A' + 10;
  1335. else if (ch >= 'a' && ch <= 'f')
  1336. value = (value << 4) + ch - 'a' + 10;
  1337. else
  1338. throw NotWFError (String.Format (
  1339. CultureInfo.InvariantCulture,
  1340. "invalid hexadecimal digit: {0} (#x{1:X})",
  1341. (char) ch,
  1342. ch));
  1343. }
  1344. } else {
  1345. while (PeekChar () != ';' && PeekChar () != -1) {
  1346. int ch = ReadChar ();
  1347. if (ch >= '0' && ch <= '9')
  1348. value = value * 10 + ch - '0';
  1349. else
  1350. throw NotWFError (String.Format (
  1351. CultureInfo.InvariantCulture,
  1352. "invalid decimal digit: {0} (#x{1:X})",
  1353. (char) ch,
  1354. ch));
  1355. }
  1356. }
  1357. ReadChar (); // ';'
  1358. // There is no way to save surrogate pairs...
  1359. if (XmlChar.IsInvalid (value))
  1360. throw NotWFError ("Referenced character was not allowed in XML.");
  1361. AppendValueChar (value);
  1362. return value;
  1363. }
  1364. private void AppendNameChar (int ch)
  1365. {
  1366. CheckNameCapacity ();
  1367. if (ch < Char.MaxValue)
  1368. nameBuffer [nameLength++] = (char) ch;
  1369. else {
  1370. nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
  1371. CheckNameCapacity ();
  1372. nameBuffer [nameLength++] = (char) (ch % 0x10000 + 0xDC00);
  1373. }
  1374. }
  1375. private void CheckNameCapacity ()
  1376. {
  1377. if (nameLength == nameCapacity) {
  1378. nameCapacity = nameCapacity * 2;
  1379. char [] oldNameBuffer = nameBuffer;
  1380. nameBuffer = new char [nameCapacity];
  1381. Array.Copy (oldNameBuffer, nameBuffer, nameLength);
  1382. }
  1383. }
  1384. private string CreateNameString ()
  1385. {
  1386. return DTD.NameTable.Add (nameBuffer, 0, nameLength);
  1387. }
  1388. private void AppendValueChar (int ch)
  1389. {
  1390. //See http://www.faqs.org/rfcs/rfc2781.html for used algorithm
  1391. if (ch < 0x10000) {
  1392. valueBuffer.Append ((char) ch);
  1393. return;
  1394. }
  1395. if (ch > 0x10FFFF)
  1396. throw new XmlException ("The numeric entity value is too large", null, LineNumber, LinePosition);
  1397. else
  1398. {
  1399. int utag = ch - 0x10000;
  1400. valueBuffer.Append((char) ((utag >> 10) + 0xD800));
  1401. valueBuffer.Append((char) ((utag & 0x3FF) + 0xDC00));
  1402. }
  1403. }
  1404. private string CreateValueString ()
  1405. {
  1406. return valueBuffer.ToString ();
  1407. }
  1408. private void ClearValueBuffer ()
  1409. {
  1410. valueBuffer.Length = 0;
  1411. }
  1412. // The reader is positioned on the quote character.
  1413. // *Keeps quote char* to value to get_QuoteChar() correctly.
  1414. private string ReadDefaultAttribute ()
  1415. {
  1416. ClearValueBuffer ();
  1417. TryExpandPERef ();
  1418. int quoteChar = ReadChar ();
  1419. if (quoteChar != '\'' && quoteChar != '\"')
  1420. throw NotWFError ("an attribute value was not quoted");
  1421. AppendValueChar (quoteChar);
  1422. while (PeekChar () != quoteChar) {
  1423. int ch = ReadChar ();
  1424. switch (ch)
  1425. {
  1426. case '<':
  1427. throw NotWFError ("attribute values cannot contain '<'");
  1428. case -1:
  1429. throw NotWFError ("unexpected end of file in an attribute value");
  1430. case '&':
  1431. AppendValueChar (ch);
  1432. if (PeekChar () == '#')
  1433. break;
  1434. // Check XML 1.0 section 3.1 WFC.
  1435. string entName = ReadName ();
  1436. Expect (';');
  1437. if (XmlChar.GetPredefinedEntity (entName) < 0) {
  1438. DTDEntityDeclaration entDecl =
  1439. DTD == null ? null : DTD.EntityDecls [entName];
  1440. if (entDecl == null || entDecl.SystemId != null)
  1441. // WFC: Entity Declared (see 4.1)
  1442. if (DTD.IsStandalone || (DTD.SystemId == null && !DTD.InternalSubsetHasPEReference))
  1443. throw NotWFError ("Reference to external entities is not allowed in attribute value.");
  1444. }
  1445. valueBuffer.Append (entName);
  1446. AppendValueChar (';');
  1447. break;
  1448. default:
  1449. AppendValueChar (ch);
  1450. break;
  1451. }
  1452. }
  1453. ReadChar (); // quoteChar
  1454. AppendValueChar (quoteChar);
  1455. return CreateValueString ();
  1456. }
  1457. private void PushParserInput (string url)
  1458. {
  1459. Uri baseUri = null;
  1460. try {
  1461. if (DTD.BaseURI != null && DTD.BaseURI.Length > 0)
  1462. baseUri = new Uri (DTD.BaseURI);
  1463. } catch (UriFormatException) {
  1464. }
  1465. Uri absUri = url != null && url.Length > 0 ?
  1466. DTD.Resolver.ResolveUri (baseUri, url) : baseUri;
  1467. string absPath = absUri != null ? absUri.ToString () : String.Empty;
  1468. foreach (XmlParserInput i in parserInputStack.ToArray ()) {
  1469. if (i.BaseURI == absPath)
  1470. throw NotWFError ("Nested inclusion is not allowed: " + url);
  1471. }
  1472. parserInputStack.Push (currentInput);
  1473. Stream s = null;
  1474. try {
  1475. 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. if (s != null)
  1479. s.Close ();
  1480. int line = currentInput == null ? 0 : currentInput.LineNumber;
  1481. int col = currentInput == null ? 0 : currentInput.LinePosition;
  1482. string bu = (currentInput == null) ? String.Empty : currentInput.BaseURI;
  1483. HandleError (new XmlSchemaException ("Specified external entity not found. Target URL is " + url + " .",
  1484. line, col, null, bu, ex));
  1485. currentInput = new XmlParserInput (new StringReader (String.Empty), absPath);
  1486. }
  1487. }
  1488. private void PopParserInput ()
  1489. {
  1490. currentInput.Close ();
  1491. currentInput = parserInputStack.Pop () as XmlParserInput;
  1492. }
  1493. private void HandleError (XmlSchemaException ex)
  1494. {
  1495. #if DTD_HANDLE_EVENTS
  1496. if (this.ValidationEventHandler != null)
  1497. ValidationEventHandler (this, new ValidationEventArgs (ex, ex.Message, XmlSeverityType.Error));
  1498. #else
  1499. DTD.AddError (ex);
  1500. #endif
  1501. }
  1502. }
  1503. }