DTDReader.cs 42 KB

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