DTDObjectModel.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. //
  2. // Mono.Xml.DTDObjectModel
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.Text;
  34. using System.Xml;
  35. using System.Xml.Schema;
  36. using Mono.Xml.Schema;
  37. #if NET_2_0
  38. using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
  39. #else
  40. using XmlTextReaderImpl = System.Xml.XmlTextReader;
  41. #endif
  42. namespace Mono.Xml
  43. {
  44. internal class DTDObjectModel
  45. {
  46. // This specifies the max number of dependent external entities
  47. // per a DTD can consume. A malicious external document server
  48. // might send users' document processing server a large number
  49. // of external entities.
  50. public const int AllowedExternalEntitiesMax = 256;
  51. DTDAutomataFactory factory;
  52. DTDElementAutomata rootAutomata;
  53. DTDEmptyAutomata emptyAutomata;
  54. DTDAnyAutomata anyAutomata;
  55. DTDInvalidAutomata invalidAutomata;
  56. DTDElementDeclarationCollection elementDecls;
  57. DTDAttListDeclarationCollection attListDecls;
  58. DTDParameterEntityDeclarationCollection peDecls;
  59. DTDEntityDeclarationCollection entityDecls;
  60. DTDNotationDeclarationCollection notationDecls;
  61. ArrayList validationErrors;
  62. XmlResolver resolver;
  63. XmlNameTable nameTable;
  64. Hashtable externalResources;
  65. string baseURI;
  66. string name;
  67. string publicId;
  68. string systemId;
  69. string intSubset;
  70. bool intSubsetHasPERef;
  71. bool isStandalone;
  72. int lineNumber;
  73. int linePosition;
  74. public DTDObjectModel (XmlNameTable nameTable)
  75. {
  76. this.nameTable = nameTable;
  77. elementDecls = new DTDElementDeclarationCollection (this);
  78. attListDecls = new DTDAttListDeclarationCollection (this);
  79. entityDecls = new DTDEntityDeclarationCollection (this);
  80. peDecls = new DTDParameterEntityDeclarationCollection (this);
  81. notationDecls = new DTDNotationDeclarationCollection (this);
  82. factory = new DTDAutomataFactory (this);
  83. validationErrors = new ArrayList ();
  84. externalResources = new Hashtable ();
  85. }
  86. public string BaseURI {
  87. get { return baseURI; }
  88. set { baseURI = value; }
  89. }
  90. public bool IsStandalone {
  91. get { return isStandalone; }
  92. set { isStandalone = value; }
  93. }
  94. public string Name {
  95. get { return name; }
  96. set { name = value; }
  97. }
  98. public XmlNameTable NameTable {
  99. get { return nameTable; }
  100. }
  101. public string PublicId {
  102. get { return publicId; }
  103. set { publicId = value; }
  104. }
  105. public string SystemId {
  106. get { return systemId; }
  107. set { systemId = value; }
  108. }
  109. public string InternalSubset {
  110. get { return intSubset; }
  111. set { intSubset = value; }
  112. }
  113. public bool InternalSubsetHasPEReference {
  114. get { return intSubsetHasPERef; }
  115. set { intSubsetHasPERef = value; }
  116. }
  117. public int LineNumber {
  118. get { return lineNumber; }
  119. set { lineNumber = value; }
  120. }
  121. public int LinePosition {
  122. get { return linePosition; }
  123. set { linePosition = value; }
  124. }
  125. internal XmlSchema CreateXsdSchema ()
  126. {
  127. XmlSchema s = new XmlSchema ();
  128. s.SourceUri = BaseURI;
  129. s.LineNumber = LineNumber;
  130. s.LinePosition = LinePosition;
  131. foreach (DTDElementDeclaration el in ElementDecls.Values)
  132. s.Items.Add (el.CreateXsdElement ());
  133. return s;
  134. }
  135. public string ResolveEntity (string name)
  136. {
  137. DTDEntityDeclaration decl = EntityDecls [name]
  138. as DTDEntityDeclaration;
  139. if (decl == null) {
  140. AddError (new XmlSchemaException ("Required entity was not found.",
  141. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  142. return " ";
  143. }
  144. else
  145. return decl.EntityValue;
  146. }
  147. internal XmlResolver Resolver {
  148. get { return resolver; }
  149. }
  150. public XmlResolver XmlResolver {
  151. set { resolver = value; }
  152. }
  153. internal Hashtable ExternalResources {
  154. get { return externalResources; }
  155. }
  156. public DTDAutomataFactory Factory {
  157. get { return factory; }
  158. }
  159. public DTDElementDeclaration RootElement {
  160. get { return ElementDecls [Name]; }
  161. }
  162. public DTDElementDeclarationCollection ElementDecls {
  163. get { return elementDecls; }
  164. }
  165. public DTDAttListDeclarationCollection AttListDecls {
  166. get { return attListDecls; }
  167. }
  168. public DTDEntityDeclarationCollection EntityDecls {
  169. get { return entityDecls; }
  170. }
  171. public DTDParameterEntityDeclarationCollection PEDecls {
  172. get { return peDecls; }
  173. }
  174. public DTDNotationDeclarationCollection NotationDecls {
  175. get { return notationDecls; }
  176. }
  177. public DTDAutomata RootAutomata {
  178. get {
  179. if (rootAutomata == null)
  180. rootAutomata = new DTDElementAutomata (this, this.Name);
  181. return rootAutomata;
  182. }
  183. }
  184. public DTDEmptyAutomata Empty {
  185. get {
  186. if (emptyAutomata == null)
  187. emptyAutomata = new DTDEmptyAutomata (this);
  188. return emptyAutomata;
  189. }
  190. }
  191. public DTDAnyAutomata Any {
  192. get {
  193. if (anyAutomata == null)
  194. anyAutomata = new DTDAnyAutomata (this);
  195. return anyAutomata;
  196. }
  197. }
  198. public DTDInvalidAutomata Invalid {
  199. get {
  200. if (invalidAutomata == null)
  201. invalidAutomata = new DTDInvalidAutomata (this);
  202. return invalidAutomata;
  203. }
  204. }
  205. public XmlSchemaException [] Errors {
  206. get { return validationErrors.ToArray (typeof (XmlSchemaException)) as XmlSchemaException []; }
  207. }
  208. public void AddError (XmlSchemaException ex)
  209. {
  210. validationErrors.Add (ex);
  211. }
  212. internal string GenerateEntityAttributeText (string entityName)
  213. {
  214. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  215. if (entity == null)
  216. return null;
  217. return entity.EntityValue;
  218. }
  219. internal XmlTextReaderImpl GenerateEntityContentReader (string entityName, XmlParserContext context)
  220. {
  221. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  222. if (entity == null)
  223. return null;
  224. if (entity.SystemId != null) {
  225. Uri baseUri = entity.BaseURI == String.Empty ? null : new Uri (entity.BaseURI);
  226. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  227. return new XmlTextReaderImpl (stream, XmlNodeType.Element, context);
  228. }
  229. else
  230. return new XmlTextReaderImpl (entity.EntityValue, XmlNodeType.Element, context);
  231. }
  232. }
  233. internal class DTDCollectionBase : DictionaryBase
  234. {
  235. DTDObjectModel root;
  236. protected DTDCollectionBase (DTDObjectModel root)
  237. {
  238. this.root = root;
  239. }
  240. protected DTDObjectModel Root {
  241. get { return root; }
  242. }
  243. public ICollection Keys {
  244. get { return InnerHashtable.Keys; }
  245. }
  246. public ICollection Values {
  247. get { return InnerHashtable.Values; }
  248. }
  249. }
  250. internal class DTDElementDeclarationCollection : DTDCollectionBase
  251. {
  252. public DTDElementDeclarationCollection (DTDObjectModel root) : base (root) {}
  253. public DTDElementDeclaration this [string name] {
  254. get { return Get (name); }
  255. }
  256. public DTDElementDeclaration Get (string name)
  257. {
  258. return InnerHashtable [name] as DTDElementDeclaration;
  259. }
  260. public void Add (string name, DTDElementDeclaration decl)
  261. {
  262. if (InnerHashtable.Contains (name)) {
  263. Root.AddError (new XmlSchemaException (String.Format (
  264. "Element declaration for {0} was already added.",
  265. name), null));
  266. return;
  267. }
  268. decl.SetRoot (Root);
  269. InnerHashtable.Add (name, decl);
  270. }
  271. }
  272. internal class DTDAttListDeclarationCollection : DTDCollectionBase
  273. {
  274. public DTDAttListDeclarationCollection (DTDObjectModel root) : base (root) {}
  275. public DTDAttListDeclaration this [string name] {
  276. get { return InnerHashtable [name] as DTDAttListDeclaration; }
  277. }
  278. public void Add (string name, DTDAttListDeclaration decl)
  279. {
  280. DTDAttListDeclaration existing = this [name];
  281. if (existing != null) {
  282. // It is valid, that is additive declaration.
  283. foreach (DTDAttributeDefinition def in decl.Definitions)
  284. if (decl.Get (def.Name) == null)
  285. existing.Add (def);
  286. } else {
  287. decl.SetRoot (Root);
  288. InnerHashtable.Add (name, decl);
  289. }
  290. }
  291. }
  292. internal class DTDEntityDeclarationCollection : DTDCollectionBase
  293. {
  294. public DTDEntityDeclarationCollection (DTDObjectModel root) : base (root) {}
  295. public DTDEntityDeclaration this [string name] {
  296. get { return InnerHashtable [name] as DTDEntityDeclaration; }
  297. }
  298. public void Add (string name, DTDEntityDeclaration decl)
  299. {
  300. if (InnerHashtable [name] != null)
  301. throw new InvalidOperationException (String.Format (
  302. "Entity declaration for {0} was already added.",
  303. name));
  304. decl.SetRoot (Root);
  305. InnerHashtable.Add (name, decl);
  306. }
  307. }
  308. internal class DTDNotationDeclarationCollection : DTDCollectionBase
  309. {
  310. public DTDNotationDeclarationCollection (DTDObjectModel root) : base (root) {}
  311. public DTDNotationDeclaration this [string name] {
  312. get { return InnerHashtable [name] as DTDNotationDeclaration; }
  313. }
  314. public void Add (string name, DTDNotationDeclaration decl)
  315. {
  316. if (InnerHashtable [name] != null)
  317. throw new InvalidOperationException (String.Format (
  318. "Notation declaration for {0} was already added.",
  319. name));
  320. decl.SetRoot (Root);
  321. InnerHashtable.Add (name, decl);
  322. }
  323. }
  324. // This class contains either ElementName or ChildModels.
  325. internal class DTDContentModel : DTDNode
  326. {
  327. DTDObjectModel root;
  328. DTDAutomata compiledAutomata;
  329. string ownerElementName;
  330. string elementName;
  331. DTDContentOrderType orderType = DTDContentOrderType.None;
  332. DTDContentModelCollection childModels = new DTDContentModelCollection ();
  333. DTDOccurence occurence = DTDOccurence.One;
  334. internal DTDContentModel (DTDObjectModel root, string ownerElementName)
  335. {
  336. this.root = root;
  337. this.ownerElementName = ownerElementName;
  338. }
  339. public DTDContentModelCollection ChildModels {
  340. get { return childModels; }
  341. set { childModels = value; }
  342. }
  343. public DTDElementDeclaration ElementDecl {
  344. get { return root.ElementDecls [ownerElementName]; }
  345. }
  346. public string ElementName {
  347. get { return elementName; }
  348. set { elementName = value; }
  349. }
  350. public DTDOccurence Occurence {
  351. get { return occurence; }
  352. set { occurence = value; }
  353. }
  354. public DTDContentOrderType OrderType {
  355. get { return orderType; }
  356. set { orderType = value; }
  357. }
  358. public DTDAutomata GetAutomata ()
  359. {
  360. if (compiledAutomata == null)
  361. Compile ();
  362. return compiledAutomata;
  363. }
  364. public DTDAutomata Compile ()
  365. {
  366. compiledAutomata = CompileInternal ();
  367. return compiledAutomata;
  368. }
  369. internal XmlSchemaParticle CreateXsdParticle ()
  370. {
  371. XmlSchemaParticle p = CreateXsdParticleCore ();
  372. if (p == null)
  373. return null;
  374. switch (Occurence) {
  375. case DTDOccurence.Optional:
  376. p.MinOccurs = 0;
  377. break;
  378. case DTDOccurence.OneOrMore:
  379. p.MaxOccursString = "unbounded";
  380. break;
  381. case DTDOccurence.ZeroOrMore:
  382. p.MinOccurs = 0;
  383. p.MaxOccursString = "unbounded";
  384. break;
  385. }
  386. return p;
  387. }
  388. XmlSchemaParticle CreateXsdParticleCore ()
  389. {
  390. XmlSchemaParticle p = null;
  391. if (ElementName != null) {
  392. XmlSchemaElement el = new XmlSchemaElement ();
  393. SetLineInfo (el);
  394. el.RefName = new XmlQualifiedName (ElementName);
  395. return el;
  396. }
  397. else if (ChildModels.Count == 0)
  398. return null;
  399. else {
  400. XmlSchemaGroupBase gb =
  401. (OrderType == DTDContentOrderType.Seq) ?
  402. (XmlSchemaGroupBase)
  403. new XmlSchemaSequence () :
  404. new XmlSchemaChoice ();
  405. SetLineInfo (gb);
  406. foreach (DTDContentModel cm in ChildModels.Items) {
  407. XmlSchemaParticle c = cm.CreateXsdParticle ();
  408. if (c != null)
  409. gb.Items.Add (c);
  410. }
  411. p = gb;
  412. }
  413. return p;
  414. }
  415. private DTDAutomata CompileInternal ()
  416. {
  417. if (ElementDecl.IsAny)
  418. return root.Any;
  419. if (ElementDecl.IsEmpty)
  420. return root.Empty;
  421. DTDAutomata basis = GetBasicContentAutomata ();
  422. switch (Occurence) {
  423. case DTDOccurence.One:
  424. return basis;
  425. case DTDOccurence.Optional:
  426. return Choice (root.Empty, basis);
  427. case DTDOccurence.OneOrMore:
  428. return new DTDOneOrMoreAutomata (root, basis);
  429. case DTDOccurence.ZeroOrMore:
  430. return Choice (root.Empty, new DTDOneOrMoreAutomata (root, basis));
  431. }
  432. throw new InvalidOperationException ();
  433. }
  434. private DTDAutomata GetBasicContentAutomata ()
  435. {
  436. if (ElementName != null)
  437. return new DTDElementAutomata (root, ElementName);
  438. switch (ChildModels.Count) {
  439. case 0:
  440. return root.Empty;
  441. case 1:
  442. return ChildModels [0].GetAutomata ();
  443. }
  444. DTDAutomata current = null;
  445. int childCount = ChildModels.Count;
  446. switch (OrderType) {
  447. case DTDContentOrderType.Seq:
  448. current = Sequence (
  449. ChildModels [childCount - 2].GetAutomata (),
  450. ChildModels [childCount - 1].GetAutomata ());
  451. for (int i = childCount - 2; i > 0; i--)
  452. current = Sequence (
  453. ChildModels [i - 1].GetAutomata (), current);
  454. return current;
  455. case DTDContentOrderType.Or:
  456. current = Choice (
  457. ChildModels [childCount - 2].GetAutomata (),
  458. ChildModels [childCount - 1].GetAutomata ());
  459. for (int i = childCount - 2; i > 0; i--)
  460. current = Choice (
  461. ChildModels [i - 1].GetAutomata (), current);
  462. return current;
  463. default:
  464. throw new InvalidOperationException ("Invalid pattern specification");
  465. }
  466. }
  467. private DTDAutomata Sequence (DTDAutomata l, DTDAutomata r)
  468. {
  469. return root.Factory.Sequence (l, r);
  470. }
  471. private DTDAutomata Choice (DTDAutomata l, DTDAutomata r)
  472. {
  473. return l.MakeChoice (r);
  474. }
  475. }
  476. internal class DTDContentModelCollection
  477. {
  478. ArrayList contentModel = new ArrayList ();
  479. public DTDContentModelCollection ()
  480. {
  481. }
  482. public IList Items {
  483. get { return contentModel; }
  484. }
  485. public DTDContentModel this [int i] {
  486. get { return contentModel [i] as DTDContentModel; }
  487. }
  488. public int Count {
  489. get { return contentModel.Count; }
  490. }
  491. public void Add (DTDContentModel model)
  492. {
  493. contentModel.Add (model);
  494. }
  495. }
  496. internal abstract class DTDNode : IXmlLineInfo
  497. {
  498. DTDObjectModel root;
  499. bool isInternalSubset;
  500. string baseURI;
  501. int lineNumber;
  502. int linePosition;
  503. public virtual string BaseURI {
  504. get { return baseURI; }
  505. set { baseURI = value; }
  506. }
  507. public bool IsInternalSubset {
  508. get { return isInternalSubset; }
  509. set { isInternalSubset = value; }
  510. }
  511. public int LineNumber {
  512. get { return lineNumber; }
  513. set { lineNumber = value; }
  514. }
  515. public int LinePosition {
  516. get { return linePosition; }
  517. set { linePosition = value; }
  518. }
  519. public bool HasLineInfo ()
  520. {
  521. return lineNumber != 0;
  522. }
  523. internal void SetRoot (DTDObjectModel root)
  524. {
  525. this.root = root;
  526. if (baseURI == null)
  527. this.BaseURI = root.BaseURI;
  528. }
  529. protected DTDObjectModel Root {
  530. get { return root; }
  531. }
  532. internal XmlException NotWFError (string message)
  533. {
  534. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  535. }
  536. public void SetLineInfo (XmlSchemaObject obj)
  537. {
  538. obj.SourceUri = BaseURI;
  539. obj.LineNumber = LineNumber;
  540. obj.LinePosition = LinePosition;
  541. }
  542. }
  543. internal class DTDElementDeclaration : DTDNode
  544. {
  545. DTDObjectModel root;
  546. DTDContentModel contentModel;
  547. string name;
  548. bool isEmpty;
  549. bool isAny;
  550. bool isMixedContent;
  551. internal DTDElementDeclaration (DTDObjectModel root)
  552. {
  553. this.root = root;
  554. }
  555. public string Name {
  556. get { return name; }
  557. set { name = value; }
  558. }
  559. public bool IsEmpty {
  560. get { return isEmpty; }
  561. set { isEmpty = value; }
  562. }
  563. public bool IsAny {
  564. get { return isAny; }
  565. set { isAny = value; }
  566. }
  567. public bool IsMixedContent {
  568. get { return isMixedContent; }
  569. set { isMixedContent = value; }
  570. }
  571. public DTDContentModel ContentModel {
  572. get {
  573. if (contentModel == null)
  574. contentModel = new DTDContentModel (root, Name);
  575. return contentModel;
  576. }
  577. }
  578. public DTDAttListDeclaration Attributes {
  579. get {
  580. return Root.AttListDecls [Name];
  581. }
  582. }
  583. internal XmlSchemaElement CreateXsdElement ()
  584. {
  585. XmlSchemaElement el = new XmlSchemaElement ();
  586. SetLineInfo (el);
  587. el.Name = Name;
  588. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  589. el.SchemaType = ct;
  590. if (Attributes != null) {
  591. SetLineInfo (ct);
  592. foreach (DTDAttributeDefinition a in
  593. Attributes.Definitions)
  594. ct.Attributes.Add (a.CreateXsdAttribute ());
  595. }
  596. if (IsEmpty)
  597. ; // nothing to do
  598. else if (IsAny) {
  599. XmlSchemaAny any = new XmlSchemaAny ();
  600. any.MinOccurs = 0;
  601. any.MaxOccursString = "unbounded";
  602. ct.Particle = any;
  603. }
  604. else {
  605. if (IsMixedContent)
  606. ct.IsMixed = true;
  607. ct.Particle = ContentModel.CreateXsdParticle ();
  608. }
  609. /*
  610. if (IsEmpty) {
  611. el.SchemaType = new XmlSchemaComplexType ();
  612. SetLineInfo (el.SchemaType);
  613. }
  614. else if (IsAny)
  615. el.SchemaTypeName = new XmlQualifiedName (
  616. "anyType", XmlSchema.Namespace);
  617. else {
  618. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  619. SetLineInfo (ct);
  620. if (Attributes != null)
  621. foreach (DTDAttributeDefinition a in
  622. Attributes.Definitions)
  623. ct.Attributes.Add (a.CreateXsdAttribute ());
  624. if (IsMixedContent)
  625. ct.IsMixed = true;
  626. ct.Particle = ContentModel.CreateXsdParticle ();
  627. el.SchemaType = ct;
  628. }
  629. */
  630. return el;
  631. }
  632. }
  633. internal class DTDAttributeDefinition : DTDNode
  634. {
  635. string name;
  636. XmlSchemaDatatype datatype;
  637. ArrayList enumeratedLiterals;
  638. string unresolvedDefault;
  639. ArrayList enumeratedNotations;
  640. DTDAttributeOccurenceType occurenceType = DTDAttributeOccurenceType.None;
  641. string resolvedDefaultValue;
  642. string resolvedNormalizedDefaultValue;
  643. internal DTDAttributeDefinition (DTDObjectModel root)
  644. {
  645. this.SetRoot (root);
  646. }
  647. public string Name {
  648. get { return name; }
  649. set { name =value; }
  650. }
  651. public XmlSchemaDatatype Datatype {
  652. get { return datatype; }
  653. set { datatype = value; }
  654. }
  655. public DTDAttributeOccurenceType OccurenceType {
  656. get { return this.occurenceType; }
  657. set { this.occurenceType = value; }
  658. }
  659. // entity reference inside enumerated values are not allowed,
  660. // but on the other hand, they are allowed inside default value.
  661. // Then I decided to use string ArrayList for enumerated values,
  662. // and unresolved string value for DefaultValue.
  663. public ArrayList EnumeratedAttributeDeclaration {
  664. get {
  665. if (enumeratedLiterals == null)
  666. enumeratedLiterals = new ArrayList ();
  667. return this.enumeratedLiterals;
  668. }
  669. }
  670. public ArrayList EnumeratedNotations {
  671. get {
  672. if (enumeratedNotations == null)
  673. enumeratedNotations = new ArrayList ();
  674. return this.enumeratedNotations;
  675. }
  676. }
  677. public string DefaultValue {
  678. get {
  679. if (resolvedDefaultValue == null)
  680. resolvedDefaultValue = ComputeDefaultValue ();
  681. return resolvedDefaultValue;
  682. }
  683. }
  684. public string NormalizedDefaultValue {
  685. get {
  686. if (resolvedNormalizedDefaultValue == null) {
  687. string s = ComputeDefaultValue ();
  688. try {
  689. object o = Datatype.ParseValue (s, null, null);
  690. resolvedNormalizedDefaultValue =
  691. (o is string []) ?
  692. String.Join (" ", (string []) o) :
  693. o is IFormattable ? ((IFormattable) o).ToString (null, CultureInfo.InvariantCulture) : o.ToString ();
  694. } catch (Exception) {
  695. // This is for non-error-reporting reader
  696. resolvedNormalizedDefaultValue = Datatype.Normalize (s);
  697. }
  698. }
  699. return resolvedNormalizedDefaultValue;
  700. }
  701. }
  702. public string UnresolvedDefaultValue {
  703. get { return this.unresolvedDefault; }
  704. set { this.unresolvedDefault = value; }
  705. }
  706. public char QuoteChar {
  707. get {
  708. return UnresolvedDefaultValue.Length > 0 ?
  709. this.UnresolvedDefaultValue [0] :
  710. '"';
  711. }
  712. }
  713. internal XmlSchemaAttribute CreateXsdAttribute ()
  714. {
  715. XmlSchemaAttribute a = new XmlSchemaAttribute ();
  716. SetLineInfo (a);
  717. a.Name = Name;
  718. a.DefaultValue = resolvedNormalizedDefaultValue;
  719. if (OccurenceType != DTDAttributeOccurenceType.Required)
  720. a.Use = XmlSchemaUse.Optional;
  721. XmlQualifiedName qname = XmlQualifiedName.Empty;
  722. ArrayList enumeration = null;
  723. if (enumeratedNotations != null && enumeratedNotations.Count > 0) {
  724. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace);
  725. enumeration = enumeratedNotations;
  726. }
  727. else if (enumeratedLiterals != null)
  728. enumeration = enumeratedLiterals;
  729. else {
  730. switch (Datatype.TokenizedType) {
  731. case XmlTokenizedType.ID:
  732. qname = new XmlQualifiedName ("ID", XmlSchema.Namespace); break;
  733. case XmlTokenizedType.IDREF:
  734. qname = new XmlQualifiedName ("IDREF", XmlSchema.Namespace); break;
  735. case XmlTokenizedType.IDREFS:
  736. qname = new XmlQualifiedName ("IDREFS", XmlSchema.Namespace); break;
  737. case XmlTokenizedType.ENTITY:
  738. qname = new XmlQualifiedName ("ENTITY", XmlSchema.Namespace); break;
  739. case XmlTokenizedType.ENTITIES:
  740. qname = new XmlQualifiedName ("ENTITIES", XmlSchema.Namespace); break;
  741. case XmlTokenizedType.NMTOKEN:
  742. qname = new XmlQualifiedName ("NMTOKEN", XmlSchema.Namespace); break;
  743. case XmlTokenizedType.NMTOKENS:
  744. qname = new XmlQualifiedName ("NMTOKENS", XmlSchema.Namespace); break;
  745. case XmlTokenizedType.NOTATION:
  746. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace); break;
  747. }
  748. }
  749. if (enumeration != null) {
  750. XmlSchemaSimpleType st = new XmlSchemaSimpleType ();
  751. SetLineInfo (st);
  752. XmlSchemaSimpleTypeRestriction r =
  753. new XmlSchemaSimpleTypeRestriction ();
  754. SetLineInfo (r);
  755. r.BaseTypeName = qname;
  756. if (enumeratedNotations != null) {
  757. foreach (string name in enumeratedNotations) {
  758. XmlSchemaEnumerationFacet f =
  759. new XmlSchemaEnumerationFacet ();
  760. SetLineInfo (f);
  761. r.Facets.Add (f);
  762. f.Value = name;
  763. }
  764. }
  765. st.Content = r;
  766. }
  767. else if (qname != XmlQualifiedName.Empty)
  768. a.SchemaTypeName = qname;
  769. return a;
  770. }
  771. internal string ComputeDefaultValue ()
  772. {
  773. if (UnresolvedDefaultValue == null)
  774. return null;
  775. StringBuilder sb = new StringBuilder ();
  776. int pos = 0;
  777. int next = 0;
  778. string value = this.UnresolvedDefaultValue;
  779. while ((next = value.IndexOf ('&', pos)) >= 0) {
  780. int semicolon = value.IndexOf (';', next);
  781. if (value [next + 1] == '#') {
  782. // character reference.
  783. char c = value [next + 2];
  784. NumberStyles style = NumberStyles.Integer;
  785. string spec;
  786. if (c == 'x' || c == 'X') {
  787. spec = value.Substring (next + 3, semicolon - next - 3);
  788. style |= NumberStyles.HexNumber;
  789. }
  790. else
  791. spec = value.Substring (next + 2, semicolon - next - 2);
  792. sb.Append ((char) int.Parse (spec, style, CultureInfo.InvariantCulture));
  793. } else {
  794. sb.Append (value.Substring (pos, next - 1));
  795. string name = value.Substring (next + 1, semicolon - 2);
  796. int predefined = XmlChar.GetPredefinedEntity (name);
  797. if (predefined >= 0)
  798. sb.Append (predefined);
  799. else
  800. sb.Append (Root.ResolveEntity (name));
  801. }
  802. pos = semicolon + 1;
  803. }
  804. sb.Append (value.Substring (pos));
  805. // strip quote chars
  806. string ret = sb.ToString (1, sb.Length - 2);
  807. sb.Length = 0;
  808. return ret;
  809. }
  810. }
  811. internal class DTDAttListDeclaration : DTDNode
  812. {
  813. string name;
  814. Hashtable attributeOrders = new Hashtable ();
  815. ArrayList attributes = new ArrayList ();
  816. internal DTDAttListDeclaration (DTDObjectModel root)
  817. {
  818. SetRoot (root);
  819. }
  820. public string Name {
  821. get { return name; }
  822. set { name = value; }
  823. }
  824. public DTDAttributeDefinition this [int i] {
  825. get { return Get (i); }
  826. }
  827. public DTDAttributeDefinition this [string name] {
  828. get { return Get (name); }
  829. }
  830. public DTDAttributeDefinition Get (int i)
  831. {
  832. return attributes [i] as DTDAttributeDefinition;
  833. }
  834. public DTDAttributeDefinition Get (string name)
  835. {
  836. object o = attributeOrders [name];
  837. if (o != null)
  838. return attributes [(int) o] as DTDAttributeDefinition;
  839. else
  840. return null;
  841. }
  842. public IList Definitions {
  843. get { return attributes; }
  844. }
  845. public void Add (DTDAttributeDefinition def)
  846. {
  847. if (attributeOrders [def.Name] != null)
  848. throw new InvalidOperationException (String.Format (
  849. "Attribute definition for {0} was already added at element {1}.",
  850. def.Name, this.Name));
  851. def.SetRoot (Root);
  852. attributeOrders.Add (def.Name, attributes.Count);
  853. attributes.Add (def);
  854. }
  855. public int Count {
  856. get { return attributeOrders.Count; }
  857. }
  858. }
  859. internal class DTDEntityBase : DTDNode
  860. {
  861. string name;
  862. string publicId;
  863. string systemId;
  864. string literalValue;
  865. string replacementText;
  866. string uriString;
  867. Uri absUri;
  868. bool isInvalid;
  869. // Exception loadException;
  870. bool loadFailed;
  871. XmlResolver resolver;
  872. protected DTDEntityBase (DTDObjectModel root)
  873. {
  874. SetRoot (root);
  875. }
  876. internal bool IsInvalid {
  877. get { return isInvalid; }
  878. set { isInvalid = value; }
  879. }
  880. public bool LoadFailed {
  881. get { return loadFailed; }
  882. set { loadFailed = value; }
  883. }
  884. public string Name {
  885. get { return name; }
  886. set { name = value; }
  887. }
  888. public string PublicId {
  889. get { return publicId; }
  890. set { publicId = value; }
  891. }
  892. public string SystemId {
  893. get { return systemId; }
  894. set { systemId = value; }
  895. }
  896. public string LiteralEntityValue {
  897. get { return literalValue; }
  898. set { literalValue = value; }
  899. }
  900. public string ReplacementText {
  901. get { return replacementText; }
  902. set { replacementText = value; }
  903. }
  904. public XmlResolver XmlResolver {
  905. set { resolver = value; }
  906. }
  907. public string ActualUri {
  908. get {
  909. if (uriString == null) {
  910. if (resolver == null || SystemId == null || SystemId.Length == 0)
  911. uriString = BaseURI;
  912. else {
  913. Uri baseUri = null;
  914. try {
  915. if (BaseURI != null && BaseURI.Length > 0)
  916. baseUri = new Uri (BaseURI);
  917. } catch (UriFormatException) {
  918. }
  919. absUri = resolver.ResolveUri (baseUri, SystemId);
  920. uriString = absUri != null ? absUri.ToString () : String.Empty;
  921. }
  922. }
  923. return uriString;
  924. }
  925. }
  926. public void Resolve ()
  927. {
  928. if (ActualUri == String.Empty) {
  929. LoadFailed = true;
  930. LiteralEntityValue = String.Empty;
  931. return;
  932. }
  933. if (Root.ExternalResources.ContainsKey (ActualUri))
  934. LiteralEntityValue = (string) Root.ExternalResources [ActualUri];
  935. Stream s = null;
  936. try {
  937. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  938. XmlTextReaderImpl xtr = new XmlTextReaderImpl (ActualUri, s, Root.NameTable);
  939. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  940. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  941. Root.ExternalResources.Add (ActualUri, LiteralEntityValue);
  942. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  943. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  944. } catch (Exception ex) {
  945. // loadException = ex;
  946. LiteralEntityValue = String.Empty;
  947. LoadFailed = true;
  948. // throw NotWFError ("Cannot resolve external entity. URI is " + ActualUri + " .");
  949. } finally {
  950. if (s != null)
  951. s.Close ();
  952. }
  953. }
  954. }
  955. internal class DTDEntityDeclaration : DTDEntityBase
  956. {
  957. string entityValue;
  958. string notationName;
  959. ArrayList ReferencingEntities = new ArrayList ();
  960. bool scanned;
  961. bool recursed;
  962. bool hasExternalReference;
  963. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  964. {
  965. }
  966. public string NotationName {
  967. get { return notationName; }
  968. set { notationName = value; }
  969. }
  970. public bool HasExternalReference {
  971. get {
  972. if (!scanned)
  973. ScanEntityValue (new ArrayList ());
  974. return hasExternalReference;
  975. }
  976. }
  977. public string EntityValue {
  978. get {
  979. if (this.IsInvalid)
  980. return String.Empty;
  981. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  982. return String.Empty;
  983. if (entityValue == null) {
  984. if (NotationName != null)
  985. entityValue = "";
  986. else if (SystemId == null || SystemId == String.Empty) {
  987. entityValue = ReplacementText;
  988. if (entityValue == null)
  989. entityValue = String.Empty;
  990. } else {
  991. entityValue = ReplacementText;
  992. }
  993. // Check illegal recursion.
  994. ScanEntityValue (new ArrayList ());
  995. }
  996. return entityValue;
  997. }
  998. }
  999. // It returns whether the entity contains references to external entities.
  1000. public void ScanEntityValue (ArrayList refs)
  1001. {
  1002. // To modify this code, beware nesting between this and EntityValue.
  1003. string value = EntityValue;
  1004. if (this.SystemId != null)
  1005. hasExternalReference = true;
  1006. if (recursed)
  1007. throw NotWFError ("Entity recursion was found.");
  1008. recursed = true;
  1009. if (scanned) {
  1010. foreach (string referenced in refs)
  1011. if (this.ReferencingEntities.Contains (referenced))
  1012. throw NotWFError (String.Format (
  1013. "Nested entity was found between {0} and {1}",
  1014. referenced, Name));
  1015. recursed = false;
  1016. return;
  1017. }
  1018. int len = value.Length;
  1019. int start = 0;
  1020. for (int i=0; i<len; i++) {
  1021. switch (value [i]) {
  1022. case '&':
  1023. start = i+1;
  1024. break;
  1025. case ';':
  1026. if (start == 0)
  1027. break;
  1028. string name = value.Substring (start, i - start);
  1029. if (name.Length == 0)
  1030. throw NotWFError ("Entity reference name is missing.");
  1031. if (name [0] == '#')
  1032. break; // character reference
  1033. if (XmlChar.GetPredefinedEntity (name) >= 0)
  1034. break; // predefined reference
  1035. this.ReferencingEntities.Add (name);
  1036. DTDEntityDeclaration decl = Root.EntityDecls [name];
  1037. if (decl != null) {
  1038. if (decl.SystemId != null)
  1039. hasExternalReference = true;
  1040. refs.Add (Name);
  1041. decl.ScanEntityValue (refs);
  1042. foreach (string str in decl.ReferencingEntities)
  1043. ReferencingEntities.Add (str);
  1044. refs.Remove (Name);
  1045. value = value.Remove (start - 1, name.Length + 2);
  1046. value = value.Insert (start - 1, decl.EntityValue);
  1047. i -= name.Length + 1; // not +2, because of immediate i++ .
  1048. len = value.Length;
  1049. }
  1050. start = 0;
  1051. break;
  1052. }
  1053. }
  1054. if (start != 0)
  1055. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  1056. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  1057. scanned = true;
  1058. recursed = false;
  1059. }
  1060. }
  1061. internal class DTDNotationDeclaration : DTDNode
  1062. {
  1063. string name;
  1064. string localName;
  1065. string prefix;
  1066. string publicId;
  1067. string systemId;
  1068. public string Name {
  1069. get { return name; }
  1070. set { name = value; }
  1071. }
  1072. public string PublicId {
  1073. get { return publicId; }
  1074. set { publicId = value; }
  1075. }
  1076. public string SystemId {
  1077. get { return systemId; }
  1078. set { systemId = value; }
  1079. }
  1080. public string LocalName {
  1081. get { return localName; }
  1082. set { localName = value; }
  1083. }
  1084. public string Prefix {
  1085. get { return prefix; }
  1086. set { prefix = value; }
  1087. }
  1088. internal DTDNotationDeclaration (DTDObjectModel root)
  1089. {
  1090. SetRoot (root);
  1091. }
  1092. }
  1093. internal class DTDParameterEntityDeclarationCollection
  1094. {
  1095. Hashtable peDecls = new Hashtable ();
  1096. DTDObjectModel root;
  1097. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  1098. {
  1099. this.root = root;
  1100. }
  1101. public DTDParameterEntityDeclaration this [string name] {
  1102. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  1103. }
  1104. public void Add (string name, DTDParameterEntityDeclaration decl)
  1105. {
  1106. // PEDecl can be overriden.
  1107. if (peDecls [name] != null)
  1108. return;
  1109. decl.SetRoot (root);
  1110. peDecls.Add (name, decl);
  1111. }
  1112. public ICollection Keys {
  1113. get { return peDecls.Keys; }
  1114. }
  1115. public ICollection Values {
  1116. get { return peDecls.Values; }
  1117. }
  1118. }
  1119. internal class DTDParameterEntityDeclaration : DTDEntityBase
  1120. {
  1121. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  1122. {
  1123. }
  1124. }
  1125. internal enum DTDContentOrderType
  1126. {
  1127. None,
  1128. Seq,
  1129. Or
  1130. }
  1131. internal enum DTDAttributeOccurenceType
  1132. {
  1133. None,
  1134. Required,
  1135. Optional,
  1136. Fixed
  1137. }
  1138. internal enum DTDOccurence
  1139. {
  1140. One,
  1141. Optional,
  1142. ZeroOrMore,
  1143. OneOrMore
  1144. }
  1145. }