DTDReader.cs 48 KB

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