DTDReader.cs 48 KB

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