DTDReader.cs 48 KB

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