DTDObjectModel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. #if NET_2_0
  213. internal string GenerateEntityAttributeText (string entityName)
  214. {
  215. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  216. if (entity == null)
  217. return null;
  218. return entity.EntityValue;
  219. }
  220. internal XmlTextReaderImpl GenerateEntityContentReader (string entityName, XmlParserContext context)
  221. {
  222. DTDEntityDeclaration entity = EntityDecls [entityName] as DTDEntityDeclaration;
  223. if (entity == null)
  224. return null;
  225. if (entity.SystemId != null) {
  226. Uri baseUri = entity.BaseURI == null ? null : new Uri (entity.BaseURI);
  227. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  228. return new XmlTextReaderImpl (stream, XmlNodeType.Element, context);
  229. }
  230. else
  231. return new XmlTextReaderImpl (entity.EntityValue, XmlNodeType.Element, context);
  232. }
  233. #endif
  234. }
  235. internal class DTDCollectionBase : DictionaryBase
  236. {
  237. DTDObjectModel root;
  238. protected DTDCollectionBase (DTDObjectModel root)
  239. {
  240. this.root = root;
  241. }
  242. protected DTDObjectModel Root {
  243. get { return root; }
  244. }
  245. public ICollection Keys {
  246. get { return InnerHashtable.Keys; }
  247. }
  248. public ICollection Values {
  249. get { return InnerHashtable.Values; }
  250. }
  251. }
  252. internal class DTDElementDeclarationCollection : DTDCollectionBase
  253. {
  254. public DTDElementDeclarationCollection (DTDObjectModel root) : base (root) {}
  255. public DTDElementDeclaration this [string name] {
  256. get { return Get (name); }
  257. }
  258. public DTDElementDeclaration Get (string name)
  259. {
  260. return InnerHashtable [name] as DTDElementDeclaration;
  261. }
  262. public void Add (string name, DTDElementDeclaration decl)
  263. {
  264. if (InnerHashtable.Contains (name)) {
  265. Root.AddError (new XmlSchemaException (String.Format (
  266. "Element declaration for {0} was already added.",
  267. name), null));
  268. return;
  269. }
  270. decl.SetRoot (Root);
  271. InnerHashtable.Add (name, decl);
  272. }
  273. }
  274. internal class DTDAttListDeclarationCollection : DTDCollectionBase
  275. {
  276. public DTDAttListDeclarationCollection (DTDObjectModel root) : base (root) {}
  277. public DTDAttListDeclaration this [string name] {
  278. get { return InnerHashtable [name] as DTDAttListDeclaration; }
  279. }
  280. public void Add (string name, DTDAttListDeclaration decl)
  281. {
  282. DTDAttListDeclaration existing = this [name];
  283. if (existing != null) {
  284. // It is valid, that is additive declaration.
  285. foreach (DTDAttributeDefinition def in decl.Definitions)
  286. if (decl.Get (def.Name) == null)
  287. existing.Add (def);
  288. } else {
  289. decl.SetRoot (Root);
  290. InnerHashtable.Add (name, decl);
  291. }
  292. }
  293. }
  294. internal class DTDEntityDeclarationCollection : DTDCollectionBase
  295. {
  296. public DTDEntityDeclarationCollection (DTDObjectModel root) : base (root) {}
  297. public DTDEntityDeclaration this [string name] {
  298. get { return InnerHashtable [name] as DTDEntityDeclaration; }
  299. }
  300. public void Add (string name, DTDEntityDeclaration decl)
  301. {
  302. if (InnerHashtable [name] != null)
  303. throw new InvalidOperationException (String.Format (
  304. "Entity declaration for {0} was already added.",
  305. name));
  306. decl.SetRoot (Root);
  307. InnerHashtable.Add (name, decl);
  308. }
  309. }
  310. internal class DTDNotationDeclarationCollection : DTDCollectionBase
  311. {
  312. public DTDNotationDeclarationCollection (DTDObjectModel root) : base (root) {}
  313. public DTDNotationDeclaration this [string name] {
  314. get { return InnerHashtable [name] as DTDNotationDeclaration; }
  315. }
  316. public void Add (string name, DTDNotationDeclaration decl)
  317. {
  318. if (InnerHashtable [name] != null)
  319. throw new InvalidOperationException (String.Format (
  320. "Notation declaration for {0} was already added.",
  321. name));
  322. decl.SetRoot (Root);
  323. InnerHashtable.Add (name, decl);
  324. }
  325. }
  326. // This class contains either ElementName or ChildModels.
  327. internal class DTDContentModel : DTDNode
  328. {
  329. DTDObjectModel root;
  330. DTDAutomata compiledAutomata;
  331. string ownerElementName;
  332. string elementName;
  333. DTDContentOrderType orderType = DTDContentOrderType.None;
  334. DTDContentModelCollection childModels = new DTDContentModelCollection ();
  335. DTDOccurence occurence = DTDOccurence.One;
  336. internal DTDContentModel (DTDObjectModel root, string ownerElementName)
  337. {
  338. this.root = root;
  339. this.ownerElementName = ownerElementName;
  340. }
  341. public DTDContentModelCollection ChildModels {
  342. get { return childModels; }
  343. set { childModels = value; }
  344. }
  345. public DTDElementDeclaration ElementDecl {
  346. get { return root.ElementDecls [ownerElementName]; }
  347. }
  348. public string ElementName {
  349. get { return elementName; }
  350. set { elementName = value; }
  351. }
  352. public DTDOccurence Occurence {
  353. get { return occurence; }
  354. set { occurence = value; }
  355. }
  356. public DTDContentOrderType OrderType {
  357. get { return orderType; }
  358. set { orderType = value; }
  359. }
  360. public DTDAutomata GetAutomata ()
  361. {
  362. if (compiledAutomata == null)
  363. Compile ();
  364. return compiledAutomata;
  365. }
  366. public DTDAutomata Compile ()
  367. {
  368. compiledAutomata = CompileInternal ();
  369. return compiledAutomata;
  370. }
  371. internal XmlSchemaParticle CreateXsdParticle ()
  372. {
  373. XmlSchemaParticle p = null;
  374. if (ElementName != null) {
  375. XmlSchemaElement el = new XmlSchemaElement ();
  376. SetLineInfo (el);
  377. el.RefName = new XmlQualifiedName (ElementName);
  378. return el;
  379. } else {
  380. XmlSchemaGroupBase gb =
  381. (OrderType == DTDContentOrderType.Seq) ?
  382. (XmlSchemaGroupBase)
  383. new XmlSchemaSequence () :
  384. new XmlSchemaChoice ();
  385. SetLineInfo (gb);
  386. foreach (DTDContentModel cm in ChildModels.Items)
  387. gb.Items.Add (cm.CreateXsdParticle ());
  388. p = gb;
  389. }
  390. switch (Occurence) {
  391. case DTDOccurence.Optional:
  392. p.MinOccurs = 0;
  393. break;
  394. case DTDOccurence.OneOrMore:
  395. p.MaxOccursString = "unbounded";
  396. break;
  397. case DTDOccurence.ZeroOrMore:
  398. p.MinOccurs = 0;
  399. p.MaxOccursString = "unbounded";
  400. break;
  401. }
  402. return p;
  403. }
  404. private DTDAutomata CompileInternal ()
  405. {
  406. if (ElementDecl.IsAny)
  407. return root.Any;
  408. if (ElementDecl.IsEmpty)
  409. return root.Empty;
  410. DTDAutomata basis = GetBasicContentAutomata ();
  411. switch (Occurence) {
  412. case DTDOccurence.One:
  413. return basis;
  414. case DTDOccurence.Optional:
  415. return Choice (root.Empty, basis);
  416. case DTDOccurence.OneOrMore:
  417. return new DTDOneOrMoreAutomata (root, basis);
  418. case DTDOccurence.ZeroOrMore:
  419. return Choice (root.Empty, new DTDOneOrMoreAutomata (root, basis));
  420. }
  421. throw new InvalidOperationException ();
  422. }
  423. private DTDAutomata GetBasicContentAutomata ()
  424. {
  425. if (ElementName != null)
  426. return new DTDElementAutomata (root, ElementName);
  427. switch (ChildModels.Count) {
  428. case 0:
  429. return root.Empty;
  430. case 1:
  431. return ChildModels [0].GetAutomata ();
  432. }
  433. DTDAutomata current = null;
  434. int childCount = ChildModels.Count;
  435. switch (OrderType) {
  436. case DTDContentOrderType.Seq:
  437. current = Sequence (
  438. ChildModels [childCount - 2].GetAutomata (),
  439. ChildModels [childCount - 1].GetAutomata ());
  440. for (int i = childCount - 2; i > 0; i--)
  441. current = Sequence (
  442. ChildModels [i - 1].GetAutomata (), current);
  443. return current;
  444. case DTDContentOrderType.Or:
  445. current = Choice (
  446. ChildModels [childCount - 2].GetAutomata (),
  447. ChildModels [childCount - 1].GetAutomata ());
  448. for (int i = childCount - 2; i > 0; i--)
  449. current = Choice (
  450. ChildModels [i - 1].GetAutomata (), current);
  451. return current;
  452. default:
  453. throw new InvalidOperationException ("Invalid pattern specification");
  454. }
  455. }
  456. private DTDAutomata Sequence (DTDAutomata l, DTDAutomata r)
  457. {
  458. return root.Factory.Sequence (l, r);
  459. }
  460. private DTDAutomata Choice (DTDAutomata l, DTDAutomata r)
  461. {
  462. return l.MakeChoice (r);
  463. }
  464. }
  465. internal class DTDContentModelCollection
  466. {
  467. ArrayList contentModel = new ArrayList ();
  468. public DTDContentModelCollection ()
  469. {
  470. }
  471. public IList Items {
  472. get { return contentModel; }
  473. }
  474. public DTDContentModel this [int i] {
  475. get { return contentModel [i] as DTDContentModel; }
  476. }
  477. public int Count {
  478. get { return contentModel.Count; }
  479. }
  480. public void Add (DTDContentModel model)
  481. {
  482. contentModel.Add (model);
  483. }
  484. }
  485. internal abstract class DTDNode : IXmlLineInfo
  486. {
  487. DTDObjectModel root;
  488. bool isInternalSubset;
  489. string baseURI;
  490. int lineNumber;
  491. int linePosition;
  492. public virtual string BaseURI {
  493. get { return baseURI; }
  494. set { baseURI = value; }
  495. }
  496. public bool IsInternalSubset {
  497. get { return isInternalSubset; }
  498. set { isInternalSubset = value; }
  499. }
  500. public int LineNumber {
  501. get { return lineNumber; }
  502. set { lineNumber = value; }
  503. }
  504. public int LinePosition {
  505. get { return linePosition; }
  506. set { linePosition = value; }
  507. }
  508. public bool HasLineInfo ()
  509. {
  510. return lineNumber != 0;
  511. }
  512. internal void SetRoot (DTDObjectModel root)
  513. {
  514. this.root = root;
  515. if (baseURI == null)
  516. this.BaseURI = root.BaseURI;
  517. }
  518. protected DTDObjectModel Root {
  519. get { return root; }
  520. }
  521. internal XmlException NotWFError (string message)
  522. {
  523. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  524. }
  525. public void SetLineInfo (XmlSchemaObject obj)
  526. {
  527. obj.SourceUri = BaseURI;
  528. obj.LineNumber = LineNumber;
  529. obj.LinePosition = LinePosition;
  530. }
  531. }
  532. internal class DTDElementDeclaration : DTDNode
  533. {
  534. DTDObjectModel root;
  535. DTDContentModel contentModel;
  536. string name;
  537. bool isEmpty;
  538. bool isAny;
  539. bool isMixedContent;
  540. internal DTDElementDeclaration (DTDObjectModel root)
  541. {
  542. this.root = root;
  543. }
  544. public string Name {
  545. get { return name; }
  546. set { name = value; }
  547. }
  548. public bool IsEmpty {
  549. get { return isEmpty; }
  550. set { isEmpty = value; }
  551. }
  552. public bool IsAny {
  553. get { return isAny; }
  554. set { isAny = value; }
  555. }
  556. public bool IsMixedContent {
  557. get { return isMixedContent; }
  558. set { isMixedContent = value; }
  559. }
  560. public DTDContentModel ContentModel {
  561. get {
  562. if (contentModel == null)
  563. contentModel = new DTDContentModel (root, Name);
  564. return contentModel;
  565. }
  566. }
  567. public DTDAttListDeclaration Attributes {
  568. get {
  569. return Root.AttListDecls [Name];
  570. }
  571. }
  572. internal XmlSchemaElement CreateXsdElement ()
  573. {
  574. XmlSchemaElement el = new XmlSchemaElement ();
  575. SetLineInfo (el);
  576. el.Name = Name;
  577. if (IsEmpty) {
  578. el.SchemaType = new XmlSchemaComplexType ();
  579. SetLineInfo (el.SchemaType);
  580. }
  581. else if (IsAny)
  582. el.SchemaTypeName = new XmlQualifiedName (
  583. "anyType", XmlSchema.Namespace);
  584. else {
  585. XmlSchemaComplexType ct = new XmlSchemaComplexType ();
  586. SetLineInfo (ct);
  587. foreach (DTDAttributeDefinition a in
  588. Attributes.Definitions)
  589. ct.Attributes.Add (a.CreateXsdAttribute ());
  590. if (IsMixedContent)
  591. ct.IsMixed = true;
  592. ct.Particle = ContentModel.CreateXsdParticle ();
  593. el.SchemaType = ct;
  594. }
  595. return el;
  596. }
  597. }
  598. internal class DTDAttributeDefinition : DTDNode
  599. {
  600. string name;
  601. XmlSchemaDatatype datatype;
  602. ArrayList enumeratedLiterals;
  603. string unresolvedDefault;
  604. ArrayList enumeratedNotations;
  605. DTDAttributeOccurenceType occurenceType = DTDAttributeOccurenceType.None;
  606. string resolvedDefaultValue;
  607. string resolvedNormalizedDefaultValue;
  608. internal DTDAttributeDefinition (DTDObjectModel root)
  609. {
  610. this.SetRoot (root);
  611. }
  612. public string Name {
  613. get { return name; }
  614. set { name =value; }
  615. }
  616. public XmlSchemaDatatype Datatype {
  617. get { return datatype; }
  618. set { datatype = value; }
  619. }
  620. public DTDAttributeOccurenceType OccurenceType {
  621. get { return this.occurenceType; }
  622. set { this.occurenceType = value; }
  623. }
  624. // entity reference inside enumerated values are not allowed,
  625. // but on the other hand, they are allowed inside default value.
  626. // Then I decided to use string ArrayList for enumerated values,
  627. // and unresolved string value for DefaultValue.
  628. public ArrayList EnumeratedAttributeDeclaration {
  629. get {
  630. if (enumeratedLiterals == null)
  631. enumeratedLiterals = new ArrayList ();
  632. return this.enumeratedLiterals;
  633. }
  634. }
  635. public ArrayList EnumeratedNotations {
  636. get {
  637. if (enumeratedNotations == null)
  638. enumeratedNotations = new ArrayList ();
  639. return this.enumeratedNotations;
  640. }
  641. }
  642. public string DefaultValue {
  643. get {
  644. if (resolvedDefaultValue == null)
  645. resolvedDefaultValue = ComputeDefaultValue ();
  646. return resolvedDefaultValue;
  647. }
  648. }
  649. public string NormalizedDefaultValue {
  650. get {
  651. if (resolvedNormalizedDefaultValue == null) {
  652. string s = ComputeDefaultValue ();
  653. try {
  654. object o = Datatype.ParseValue (s, null, null);
  655. resolvedNormalizedDefaultValue =
  656. (o is string []) ?
  657. String.Join (" ", (string []) o) :
  658. o is IFormattable ? ((IFormattable) o).ToString (null, CultureInfo.InvariantCulture) : o.ToString ();
  659. } catch (Exception) {
  660. // This is for non-error-reporting reader
  661. resolvedNormalizedDefaultValue = Datatype.Normalize (s);
  662. }
  663. }
  664. return resolvedNormalizedDefaultValue;
  665. }
  666. }
  667. public string UnresolvedDefaultValue {
  668. get { return this.unresolvedDefault; }
  669. set { this.unresolvedDefault = value; }
  670. }
  671. public char QuoteChar {
  672. get {
  673. return UnresolvedDefaultValue.Length > 0 ?
  674. this.UnresolvedDefaultValue [0] :
  675. '"';
  676. }
  677. }
  678. internal XmlSchemaAttribute CreateXsdAttribute ()
  679. {
  680. XmlSchemaAttribute a = new XmlSchemaAttribute ();
  681. SetLineInfo (a);
  682. a.Name = Name;
  683. a.DefaultValue = resolvedNormalizedDefaultValue;
  684. XmlQualifiedName qname = XmlQualifiedName.Empty;
  685. ArrayList enumeration = null;
  686. if (enumeratedNotations != null && enumeratedNotations.Count > 0) {
  687. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace);
  688. enumeration = enumeratedNotations;
  689. }
  690. else if (enumeratedLiterals != null)
  691. enumeration = enumeratedLiterals;
  692. else {
  693. switch (Datatype.TokenizedType) {
  694. case XmlTokenizedType.ID:
  695. qname = new XmlQualifiedName ("ID", XmlSchema.Namespace); break;
  696. case XmlTokenizedType.IDREF:
  697. qname = new XmlQualifiedName ("IDREF", XmlSchema.Namespace); break;
  698. case XmlTokenizedType.IDREFS:
  699. qname = new XmlQualifiedName ("IDREFS", XmlSchema.Namespace); break;
  700. case XmlTokenizedType.ENTITY:
  701. qname = new XmlQualifiedName ("ENTITY", XmlSchema.Namespace); break;
  702. case XmlTokenizedType.ENTITIES:
  703. qname = new XmlQualifiedName ("ENTITIES", XmlSchema.Namespace); break;
  704. case XmlTokenizedType.NMTOKEN:
  705. qname = new XmlQualifiedName ("NMTOKEN", XmlSchema.Namespace); break;
  706. case XmlTokenizedType.NMTOKENS:
  707. qname = new XmlQualifiedName ("NMTOKENS", XmlSchema.Namespace); break;
  708. case XmlTokenizedType.NOTATION:
  709. qname = new XmlQualifiedName ("NOTATION", XmlSchema.Namespace); break;
  710. }
  711. }
  712. if (enumeration != null) {
  713. XmlSchemaSimpleType st = new XmlSchemaSimpleType ();
  714. SetLineInfo (st);
  715. XmlSchemaSimpleTypeRestriction r =
  716. new XmlSchemaSimpleTypeRestriction ();
  717. SetLineInfo (r);
  718. r.BaseTypeName = qname;
  719. foreach (string name in enumeratedNotations) {
  720. XmlSchemaEnumerationFacet f =
  721. new XmlSchemaEnumerationFacet ();
  722. SetLineInfo (f);
  723. r.Facets.Add (f);
  724. f.Value = name;
  725. }
  726. }
  727. else if (qname != XmlQualifiedName.Empty)
  728. a.SchemaTypeName = qname;
  729. return a;
  730. }
  731. internal string ComputeDefaultValue ()
  732. {
  733. if (UnresolvedDefaultValue == null)
  734. return null;
  735. StringBuilder sb = new StringBuilder ();
  736. int pos = 0;
  737. int next = 0;
  738. string value = this.UnresolvedDefaultValue;
  739. while ((next = value.IndexOf ('&', pos)) >= 0) {
  740. int semicolon = value.IndexOf (';', next);
  741. if (value [next + 1] == '#') {
  742. // character reference.
  743. char c = value [next + 2];
  744. NumberStyles style = NumberStyles.Integer;
  745. string spec;
  746. if (c == 'x' || c == 'X') {
  747. spec = value.Substring (next + 3, semicolon - next - 3);
  748. style |= NumberStyles.HexNumber;
  749. }
  750. else
  751. spec = value.Substring (next + 2, semicolon - next - 2);
  752. sb.Append ((char) int.Parse (spec, style, CultureInfo.InvariantCulture));
  753. } else {
  754. sb.Append (value.Substring (pos, next - 1));
  755. string name = value.Substring (next + 1, semicolon - 2);
  756. int predefined = XmlChar.GetPredefinedEntity (name);
  757. if (predefined >= 0)
  758. sb.Append (predefined);
  759. else
  760. sb.Append (Root.ResolveEntity (name));
  761. }
  762. pos = semicolon + 1;
  763. }
  764. sb.Append (value.Substring (pos));
  765. // strip quote chars
  766. string ret = sb.ToString (1, sb.Length - 2);
  767. sb.Length = 0;
  768. return ret;
  769. }
  770. }
  771. internal class DTDAttListDeclaration : DTDNode
  772. {
  773. string name;
  774. Hashtable attributeOrders = new Hashtable ();
  775. ArrayList attributes = new ArrayList ();
  776. internal DTDAttListDeclaration (DTDObjectModel root)
  777. {
  778. SetRoot (root);
  779. }
  780. public string Name {
  781. get { return name; }
  782. set { name = value; }
  783. }
  784. public DTDAttributeDefinition this [int i] {
  785. get { return Get (i); }
  786. }
  787. public DTDAttributeDefinition this [string name] {
  788. get { return Get (name); }
  789. }
  790. public DTDAttributeDefinition Get (int i)
  791. {
  792. return attributes [i] as DTDAttributeDefinition;
  793. }
  794. public DTDAttributeDefinition Get (string name)
  795. {
  796. object o = attributeOrders [name];
  797. if (o != null)
  798. return attributes [(int) o] as DTDAttributeDefinition;
  799. else
  800. return null;
  801. }
  802. public IList Definitions {
  803. get { return attributes; }
  804. }
  805. public void Add (DTDAttributeDefinition def)
  806. {
  807. if (attributeOrders [def.Name] != null)
  808. throw new InvalidOperationException (String.Format (
  809. "Attribute definition for {0} was already added at element {1}.",
  810. def.Name, this.Name));
  811. def.SetRoot (Root);
  812. attributeOrders.Add (def.Name, attributes.Count);
  813. attributes.Add (def);
  814. }
  815. public int Count {
  816. get { return attributeOrders.Count; }
  817. }
  818. }
  819. internal class DTDEntityBase : DTDNode
  820. {
  821. string name;
  822. string publicId;
  823. string systemId;
  824. string literalValue;
  825. string replacementText;
  826. bool isInvalid;
  827. // Exception loadException;
  828. bool loadFailed;
  829. protected DTDEntityBase (DTDObjectModel root)
  830. {
  831. SetRoot (root);
  832. }
  833. internal bool IsInvalid {
  834. get { return isInvalid; }
  835. set { isInvalid = value; }
  836. }
  837. public bool LoadFailed {
  838. get { return loadFailed; }
  839. set { loadFailed = value; }
  840. }
  841. public string Name {
  842. get { return name; }
  843. set { name = value; }
  844. }
  845. public string PublicId {
  846. get { return publicId; }
  847. set { publicId = value; }
  848. }
  849. public string SystemId {
  850. get { return systemId; }
  851. set { systemId = value; }
  852. }
  853. public string LiteralEntityValue {
  854. get { return literalValue; }
  855. set { literalValue = value; }
  856. }
  857. public string ReplacementText {
  858. get { return replacementText; }
  859. set { replacementText = value; }
  860. }
  861. public void Resolve (XmlResolver resolver)
  862. {
  863. if (resolver == null || SystemId == null || SystemId.Length == 0) {
  864. LoadFailed = true;
  865. LiteralEntityValue = String.Empty;
  866. return;
  867. }
  868. Uri baseUri = null;
  869. try {
  870. if (BaseURI != null && BaseURI.Length > 0)
  871. baseUri = new Uri (BaseURI);
  872. } catch (UriFormatException) {
  873. }
  874. Uri absUri = resolver.ResolveUri (baseUri, SystemId);
  875. string absPath = absUri != null ? absUri.ToString () : String.Empty;
  876. if (Root.ExternalResources.ContainsKey (absPath))
  877. LiteralEntityValue = (string) Root.ExternalResources [absPath];
  878. Stream s = null;
  879. try {
  880. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  881. XmlTextReaderImpl xtr = new XmlTextReaderImpl (absPath, s, Root.NameTable);
  882. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  883. this.BaseURI = absPath;
  884. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  885. Root.ExternalResources.Add (absPath, LiteralEntityValue);
  886. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  887. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  888. } catch (Exception ex) {
  889. // loadException = ex;
  890. LiteralEntityValue = String.Empty;
  891. LoadFailed = true;
  892. // throw NotWFError ("Cannot resolve external entity. URI is " + absPath + " .");
  893. } finally {
  894. if (s != null)
  895. s.Close ();
  896. }
  897. }
  898. }
  899. internal class DTDEntityDeclaration : DTDEntityBase
  900. {
  901. string entityValue;
  902. string notationName;
  903. ArrayList ReferencingEntities = new ArrayList ();
  904. bool scanned;
  905. bool recursed;
  906. bool hasExternalReference;
  907. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  908. {
  909. }
  910. public string NotationName {
  911. get { return notationName; }
  912. set { notationName = value; }
  913. }
  914. public bool HasExternalReference {
  915. get {
  916. if (!scanned)
  917. ScanEntityValue (new ArrayList ());
  918. return hasExternalReference;
  919. }
  920. }
  921. public string EntityValue {
  922. get {
  923. if (this.IsInvalid)
  924. return String.Empty;
  925. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  926. return String.Empty;
  927. if (entityValue == null) {
  928. if (NotationName != null)
  929. entityValue = "";
  930. else if (SystemId == null || SystemId == String.Empty) {
  931. entityValue = ReplacementText;
  932. if (entityValue == null)
  933. entityValue = String.Empty;
  934. } else {
  935. entityValue = ReplacementText;
  936. }
  937. // Check illegal recursion.
  938. ScanEntityValue (new ArrayList ());
  939. }
  940. return entityValue;
  941. }
  942. }
  943. // It returns whether the entity contains references to external entities.
  944. public void ScanEntityValue (ArrayList refs)
  945. {
  946. // To modify this code, beware nesting between this and EntityValue.
  947. string value = EntityValue;
  948. if (this.SystemId != null)
  949. hasExternalReference = true;
  950. if (recursed)
  951. throw NotWFError ("Entity recursion was found.");
  952. recursed = true;
  953. if (scanned) {
  954. foreach (string referenced in refs)
  955. if (this.ReferencingEntities.Contains (referenced))
  956. throw NotWFError (String.Format (
  957. "Nested entity was found between {0} and {1}",
  958. referenced, Name));
  959. recursed = false;
  960. return;
  961. }
  962. int len = value.Length;
  963. int start = 0;
  964. for (int i=0; i<len; i++) {
  965. switch (value [i]) {
  966. case '&':
  967. start = i+1;
  968. break;
  969. case ';':
  970. if (start == 0)
  971. break;
  972. string name = value.Substring (start, i - start);
  973. if (name.Length == 0)
  974. throw NotWFError ("Entity reference name is missing.");
  975. if (name [0] == '#')
  976. break; // character reference
  977. if (XmlChar.GetPredefinedEntity (name) >= 0)
  978. break; // predefined reference
  979. this.ReferencingEntities.Add (name);
  980. DTDEntityDeclaration decl = Root.EntityDecls [name];
  981. if (decl != null) {
  982. if (decl.SystemId != null)
  983. hasExternalReference = true;
  984. refs.Add (Name);
  985. decl.ScanEntityValue (refs);
  986. foreach (string str in decl.ReferencingEntities)
  987. ReferencingEntities.Add (str);
  988. refs.Remove (Name);
  989. value = value.Remove (start - 1, name.Length + 2);
  990. value = value.Insert (start - 1, decl.EntityValue);
  991. i -= name.Length + 1; // not +2, because of immediate i++ .
  992. len = value.Length;
  993. }
  994. start = 0;
  995. break;
  996. }
  997. }
  998. if (start != 0)
  999. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  1000. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  1001. scanned = true;
  1002. recursed = false;
  1003. }
  1004. }
  1005. internal class DTDNotationDeclaration : DTDNode
  1006. {
  1007. string name;
  1008. string localName;
  1009. string prefix;
  1010. string publicId;
  1011. string systemId;
  1012. public string Name {
  1013. get { return name; }
  1014. set { name = value; }
  1015. }
  1016. public string PublicId {
  1017. get { return publicId; }
  1018. set { publicId = value; }
  1019. }
  1020. public string SystemId {
  1021. get { return systemId; }
  1022. set { systemId = value; }
  1023. }
  1024. public string LocalName {
  1025. get { return localName; }
  1026. set { localName = value; }
  1027. }
  1028. public string Prefix {
  1029. get { return prefix; }
  1030. set { prefix = value; }
  1031. }
  1032. internal DTDNotationDeclaration (DTDObjectModel root)
  1033. {
  1034. SetRoot (root);
  1035. }
  1036. }
  1037. internal class DTDParameterEntityDeclarationCollection
  1038. {
  1039. Hashtable peDecls = new Hashtable ();
  1040. DTDObjectModel root;
  1041. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  1042. {
  1043. this.root = root;
  1044. }
  1045. public DTDParameterEntityDeclaration this [string name] {
  1046. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  1047. }
  1048. public void Add (string name, DTDParameterEntityDeclaration decl)
  1049. {
  1050. // PEDecl can be overriden.
  1051. if (peDecls [name] != null)
  1052. return;
  1053. decl.SetRoot (root);
  1054. peDecls.Add (name, decl);
  1055. }
  1056. public ICollection Keys {
  1057. get { return peDecls.Keys; }
  1058. }
  1059. public ICollection Values {
  1060. get { return peDecls.Values; }
  1061. }
  1062. }
  1063. internal class DTDParameterEntityDeclaration : DTDEntityBase
  1064. {
  1065. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  1066. {
  1067. }
  1068. }
  1069. internal enum DTDContentOrderType
  1070. {
  1071. None,
  1072. Seq,
  1073. Or
  1074. }
  1075. internal enum DTDAttributeOccurenceType
  1076. {
  1077. None,
  1078. Required,
  1079. Optional,
  1080. Fixed
  1081. }
  1082. internal enum DTDOccurence
  1083. {
  1084. One,
  1085. Optional,
  1086. ZeroOrMore,
  1087. OneOrMore
  1088. }
  1089. }