XmlSchemaInference.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. //
  2. // XmlSchemaInference.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C)2004 Novell Inc.
  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. #if NET_2_0
  30. using System;
  31. using System.Collections;
  32. using System.Xml;
  33. using System.Xml.Schema;
  34. using QName = System.Xml.XmlQualifiedName;
  35. using Form = System.Xml.Schema.XmlSchemaForm;
  36. using Use = System.Xml.Schema.XmlSchemaUse;
  37. using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
  38. using SOMObject = System.Xml.Schema.XmlSchemaObject;
  39. using Import = System.Xml.Schema.XmlSchemaImport;
  40. using Element = System.Xml.Schema.XmlSchemaElement;
  41. using Attr = System.Xml.Schema.XmlSchemaAttribute;
  42. using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
  43. using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
  44. using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
  45. using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
  46. using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
  47. using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
  48. using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
  49. using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
  50. using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
  51. using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
  52. using SimpleTypeRst = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
  53. using SimpleList = System.Xml.Schema.XmlSchemaSimpleTypeList;
  54. using SimpleUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
  55. using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
  56. using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
  57. using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
  58. using Particle = System.Xml.Schema.XmlSchemaParticle;
  59. using Sequence = System.Xml.Schema.XmlSchemaSequence;
  60. using Choice = System.Xml.Schema.XmlSchemaChoice;
  61. namespace System.Xml.Schema
  62. {
  63. [MonoTODO]
  64. // FIXME:
  65. // - merge primitive types
  66. // - infer gYearMonth too
  67. // - in some cases sequence should contain element whose minOccurs=0
  68. // (no obvious rules right now)
  69. // - reject some non-supported schema components
  70. public sealed class XmlSchemaInference
  71. {
  72. public enum InferenceOption {
  73. Restricted,
  74. Relaxed,
  75. }
  76. InferenceOption occurrence = InferenceOption.Restricted;
  77. InferenceOption typeInference = InferenceOption.Restricted;
  78. public XmlSchemaInference ()
  79. {
  80. }
  81. public InferenceOption Occurrence {
  82. get { return occurrence; }
  83. set { occurrence = value; }
  84. }
  85. public InferenceOption TypeInference {
  86. get { return TypeInference; }
  87. set { typeInference = value; }
  88. }
  89. public XmlSchemaSet InferSchema (XmlReader xmlReader)
  90. {
  91. return InferSchema (xmlReader, new XmlSchemaSet ());
  92. }
  93. public XmlSchemaSet InferSchema (XmlReader xmlReader,
  94. XmlSchemaSet schemas)
  95. {
  96. return XsdInference.Process (xmlReader, schemas,
  97. occurrence == InferenceOption.Relaxed,
  98. typeInference == InferenceOption.Relaxed);
  99. }
  100. }
  101. class XsdInference
  102. {
  103. public static XmlSchemaSet Process (XmlReader xmlReader,
  104. XmlSchemaSet schemas,
  105. bool laxOccurrence,
  106. bool laxTypeInference)
  107. {
  108. XsdInference impl = new XsdInference (xmlReader,
  109. schemas, laxOccurrence, laxTypeInference);
  110. impl.Run ();
  111. return impl.schemas;
  112. }
  113. public const string NamespaceXml =
  114. "http://www.w3.org/XML/1998/namespace";
  115. public const string NamespaceXmlns =
  116. "http://www.w3.org/2000/xmlns/";
  117. public const string XdtNamespace =
  118. "http://www.w3.org/2003/11/xpath-datatypes";
  119. static readonly QName QNameString = new QName (
  120. "string", XmlSchema.Namespace);
  121. static readonly QName QNameBoolean = new QName (
  122. "boolean", XmlSchema.Namespace);
  123. static readonly QName QNameAnyType = new QName (
  124. "anyType", XmlSchema.Namespace);
  125. static readonly QName QNameByte = new QName (
  126. "byte", XmlSchema.Namespace);
  127. static readonly QName QNameUByte = new QName (
  128. "unsignedByte", XmlSchema.Namespace);
  129. static readonly QName QNameShort = new QName (
  130. "short", XmlSchema.Namespace);
  131. static readonly QName QNameUShort = new QName (
  132. "unsignedShort", XmlSchema.Namespace);
  133. static readonly QName QNameInt = new QName (
  134. "int", XmlSchema.Namespace);
  135. static readonly QName QNameUInt = new QName (
  136. "unsignedInt", XmlSchema.Namespace);
  137. static readonly QName QNameLong = new QName (
  138. "long", XmlSchema.Namespace);
  139. static readonly QName QNameULong = new QName (
  140. "unsignedLong", XmlSchema.Namespace);
  141. static readonly QName QNameDecimal = new QName (
  142. "decimal", XmlSchema.Namespace);
  143. static readonly QName QNameUDecimal = new QName (
  144. "unsignedDecimal", XmlSchema.Namespace);
  145. static readonly QName QNameDouble = new QName (
  146. "double", XmlSchema.Namespace);
  147. static readonly QName QNameFloat = new QName (
  148. "float", XmlSchema.Namespace);
  149. static readonly QName QNameDateTime = new QName (
  150. "dateTime", XmlSchema.Namespace);
  151. static readonly QName QNameDuration = new QName (
  152. "duration", XmlSchema.Namespace);
  153. XmlReader source;
  154. XmlSchemaSet schemas;
  155. bool laxOccurrence;
  156. bool laxTypeInference;
  157. Hashtable newElements = new Hashtable ();
  158. Hashtable newAttributes = new Hashtable ();
  159. private XsdInference (XmlReader xmlReader,
  160. XmlSchemaSet schemas,
  161. bool laxOccurrence,
  162. bool laxTypeInference)
  163. {
  164. this.source = xmlReader;
  165. this.schemas = schemas;
  166. this.laxOccurrence = laxOccurrence;
  167. this.laxTypeInference = laxTypeInference;
  168. }
  169. private void Run ()
  170. {
  171. // XmlSchemaSet need to be compiled.
  172. schemas.Compile ();
  173. // move to top-level element
  174. source.MoveToContent ();
  175. int depth = source.Depth;
  176. if (source.NodeType != XmlNodeType.Element)
  177. throw new ArgumentException ("Argument XmlReader content is expected to be an element.");
  178. QName qname = new QName (source.LocalName,
  179. source.NamespaceURI);
  180. Element el = GetGlobalElement (qname);
  181. if (el == null) {
  182. el = CreateGlobalElement (qname);
  183. InferElement (el, qname.Namespace, true);
  184. }
  185. else
  186. InferElement (el, qname.Namespace, false);
  187. // FIXME: compile again.
  188. // foreach (XmlSchema schema in schemas.Schemas ())
  189. // schemas.Reprocess (schema);
  190. }
  191. private void AddImport (string current, string import)
  192. {
  193. foreach (XmlSchema schema in schemas.Schemas (current)) {
  194. bool exists = false;
  195. foreach (XmlSchemaExternal e in schema.Includes) {
  196. Import imp = e as Import;
  197. if (imp != null &&
  198. imp.Namespace == import)
  199. exists = true;
  200. }
  201. if (exists)
  202. continue;
  203. Import newimp = new Import ();
  204. newimp.Namespace = import;
  205. schema.Includes.Add (newimp);
  206. }
  207. }
  208. private void IncludeXmlAttributes ()
  209. {
  210. if (schemas.Schemas (NamespaceXml).Count == 0)
  211. // FIXME: do it from resources.
  212. schemas.Add (NamespaceXml,
  213. "http://www.w3.org/2001/xml.xsd");
  214. }
  215. private void InferElement (Element el, string ns, bool isNew)
  216. {
  217. // Quick check for reference to another definition
  218. // (i.e. element ref='...' that should be redirected)
  219. if (el.RefName != QName.Empty) {
  220. Element body = GetGlobalElement (el.RefName);
  221. if (body == null) {
  222. body = CreateElement (el.RefName);
  223. InferElement (body, ns, true);
  224. }
  225. else
  226. InferElement (body, ns, isNew);
  227. return;
  228. }
  229. // Attributes
  230. if (source.MoveToFirstAttribute ()) {
  231. InferAttributes (el, ns, isNew);
  232. source.MoveToElement ();
  233. }
  234. // Content
  235. if (source.IsEmptyElement) {
  236. InferAsEmptyElement (el, ns, isNew);
  237. source.Read ();
  238. source.MoveToContent ();
  239. }
  240. else {
  241. InferContent (el, ns, isNew);
  242. source.ReadEndElement ();
  243. }
  244. if (el.SchemaType == null &&
  245. el.SchemaTypeName == QName.Empty)
  246. el.SchemaTypeName = QNameString;
  247. }
  248. #region Attribute Inference
  249. private Hashtable CollectAttrTable (SOMList attList)
  250. {
  251. // get attribute definition table.
  252. Hashtable table = new Hashtable ();
  253. foreach (XmlSchemaObject obj in attList) {
  254. Attr attr = obj as Attr;
  255. if (attr == null)
  256. throw Error (obj, String.Format ("Attribute inference only supports direct attribute definition. {0} is not supported.", obj.GetType ()));
  257. if (attr.RefName != QName.Empty)
  258. table.Add (attr.RefName, attr);
  259. else
  260. table.Add (new QName (attr.Name, ""),
  261. attr);
  262. }
  263. return table;
  264. }
  265. private void InferAttributes (Element el, string ns, bool isNew)
  266. {
  267. // Now this element is going to have complexType.
  268. // It currently not, then we have to replace it.
  269. ComplexType ct = null;
  270. SOMList attList = null;
  271. Hashtable table = null;
  272. do {
  273. switch (source.NamespaceURI) {
  274. case NamespaceXml:
  275. if (schemas.Schemas (
  276. NamespaceXml) .Count == 0)
  277. IncludeXmlAttributes ();
  278. break;
  279. case XmlSchema.InstanceNamespace:
  280. if (source.LocalName == "nil")
  281. el.IsNillable = true;
  282. // all other xsi:* atts are ignored
  283. continue;
  284. case NamespaceXmlns:
  285. continue;
  286. }
  287. if (ct == null) {
  288. ct = ToComplexType (el);
  289. attList = GetAttributes (ct);
  290. table = CollectAttrTable (attList);
  291. }
  292. QName attrName = new QName (
  293. source.LocalName, source.NamespaceURI);
  294. Attr attr = table [attrName] as Attr;
  295. if (attr == null) {
  296. attList.Add (InferNewAttribute (
  297. attrName, isNew, ns));
  298. } else {
  299. table.Remove (attrName);
  300. if (attr.RefName != null &&
  301. attr.RefName != QName.Empty)
  302. continue; // just a reference
  303. InferMergedAttribute (attr);
  304. }
  305. } while (source.MoveToNextAttribute ());
  306. // mark all attr definitions that did not appear
  307. // as optional.
  308. if (table != null)
  309. foreach (Attr attr in table.Values)
  310. attr.Use = Use.Optional;
  311. }
  312. private XmlSchemaAttribute InferNewAttribute (
  313. QName attrName, bool isNewTypeDefinition, string ns)
  314. {
  315. Attr attr = null;
  316. bool mergedRequired = false;
  317. if (attrName.Namespace.Length > 0) {
  318. // global attribute; might be already defined.
  319. attr = GetGlobalAttribute (attrName) as Attr;
  320. if (attr == null) {
  321. attr = CreateGlobalAttribute (attrName);
  322. attr.SchemaTypeName =
  323. InferSimpleType (source.Value);
  324. } else {
  325. InferMergedAttribute (attr);
  326. mergedRequired =
  327. attr.Use == Use.Required;
  328. }
  329. attr = new Attr ();
  330. attr.RefName = attrName;
  331. AddImport (ns, attrName.Namespace);
  332. } else {
  333. // local attribute
  334. attr = new Attr ();
  335. attr.Name = attrName.Name;
  336. attr.SchemaTypeName =
  337. InferSimpleType (source.Value);
  338. }
  339. if (!laxOccurrence &&
  340. (isNewTypeDefinition || mergedRequired))
  341. attr.Use = Use.Required;
  342. else
  343. attr.Use = Use.Optional;
  344. return attr;
  345. }
  346. // validate string value agains attr and
  347. // if invalid, then relax the type.
  348. private void InferMergedAttribute (Attr attr)
  349. {
  350. attr.SchemaTypeName = InferMergedType (source.Value,
  351. attr.SchemaTypeName);
  352. attr.SchemaType = null;
  353. }
  354. private QName InferMergedType (string value, QName typeName)
  355. {
  356. // examine value against specified type and
  357. // if unacceptable, then return a relaxed type.
  358. SimpleType st = XmlSchemaType.GetBuiltInSimpleType (
  359. typeName);
  360. if (st == null) // non-primitive type => see above.
  361. return QNameString;
  362. do {
  363. try {
  364. st.Datatype.ParseValue (value,
  365. source.NameTable,
  366. source as IXmlNamespaceResolver);
  367. return typeName;
  368. } catch {
  369. st = st.BaseXmlSchemaType as XmlSchemaSimpleType;
  370. typeName = st != null ? st.QualifiedName : QName.Empty;
  371. }
  372. } while (typeName != QName.Empty);
  373. return QNameString;
  374. }
  375. private SOMList GetAttributes (ComplexType ct)
  376. {
  377. if (ct.ContentModel == null)
  378. return ct.Attributes;
  379. SimpleModel sc = ct.ContentModel as SimpleModel;
  380. if (sc != null) {
  381. SimpleExt sce = sc.Content as SimpleExt;
  382. if (sce != null)
  383. return sce.Attributes;
  384. SimpleRst scr = sc.Content as SimpleRst;
  385. if (scr != null)
  386. return scr.Attributes;
  387. else
  388. throw Error (sc, "Invalid simple content model.");
  389. }
  390. ComplexModel cc = ct.ContentModel as ComplexModel;
  391. if (cc != null) {
  392. ComplexExt cce = cc.Content as ComplexExt;
  393. if (cce != null)
  394. return cce.Attributes;
  395. ComplexRst ccr = cc.Content as ComplexRst;
  396. if (ccr != null)
  397. return ccr.Attributes;
  398. else
  399. throw Error (cc, "Invalid simple content model.");
  400. }
  401. throw Error (cc, "Invalid complexType. Should not happen.");
  402. }
  403. private ComplexType ToComplexType (Element el)
  404. {
  405. QName name = el.SchemaTypeName;
  406. XmlSchemaType type = el.SchemaType;
  407. // 1. element type is complex.
  408. ComplexType ct = type as ComplexType;
  409. if (ct != null)
  410. return ct;
  411. // 2. reference to global complexType.
  412. XmlSchemaType globalType = schemas.GlobalTypes [name]
  413. as XmlSchemaType;
  414. ct = globalType as ComplexType;
  415. if (ct != null)
  416. return ct;
  417. ct = new ComplexType ();
  418. el.SchemaType = ct;
  419. el.SchemaTypeName = QName.Empty;
  420. // 3. base type name is xs:anyType or no specification.
  421. // <xs:complexType />
  422. if (name == QNameAnyType)
  423. return ct;
  424. else if (type == null && name == QName.Empty)
  425. return ct;
  426. SimpleModel sc = new SimpleModel ();
  427. ct.ContentModel = sc;
  428. // 4. type is simpleType
  429. // -> extension of existing simple type.
  430. SimpleType st = type as SimpleType;
  431. if (st != null) {
  432. SimpleRst scr = new SimpleRst ();
  433. scr.BaseType = st;
  434. sc.Content = scr;
  435. return ct;
  436. }
  437. SimpleExt sce = new SimpleExt ();
  438. sc.Content = sce;
  439. // 5. type name points to primitive type
  440. // -> simple extension of a primitive type
  441. st = XmlSchemaType.GetBuiltInSimpleType (name);
  442. if (st != null) {
  443. sce.BaseTypeName = name;
  444. return ct;
  445. }
  446. // 6. type name points to global simpleType.
  447. st = globalType as SimpleType;
  448. if (st != null) {
  449. sce.BaseTypeName = name;
  450. return ct;
  451. }
  452. throw Error (el, "Unexpected schema component that contains simpleTypeName that could not be resolved.");
  453. }
  454. #endregion
  455. #region Element Type
  456. private void InferAsEmptyElement (Element el, string ns,
  457. bool isNew)
  458. {
  459. ComplexType ct = el.SchemaType as ComplexType;
  460. if (ct != null) {
  461. SimpleModel sm =
  462. ct.ContentModel as SimpleModel;
  463. if (sm != null) {
  464. ToEmptiableSimpleContent (sm, isNew);
  465. return;
  466. }
  467. ComplexModel cm = ct.ContentModel
  468. as ComplexModel;
  469. if (cm != null) {
  470. ToEmptiableComplexContent (cm, isNew);
  471. return;
  472. }
  473. if (ct.Particle != null)
  474. ct.Particle.MinOccurs = 0;
  475. return;
  476. }
  477. SimpleType st = el.SchemaType as SimpleType;
  478. if (st != null) {
  479. st = MakeBaseTypeAsEmptiable (st);
  480. switch (st.QualifiedName.Namespace) {
  481. case XmlSchema.Namespace:
  482. case XdtNamespace:
  483. el.SchemaTypeName = st.QualifiedName;
  484. break;
  485. default:
  486. el.SchemaType =st;
  487. break;
  488. }
  489. }
  490. }
  491. private SimpleType MakeBaseTypeAsEmptiable (SimpleType st)
  492. {
  493. switch (st.QualifiedName.Namespace) {
  494. case XmlSchema.Namespace:
  495. case XdtNamespace:
  496. // If a primitive type
  497. return XmlSchemaType.GetBuiltInSimpleType (
  498. XmlTypeCode.String);
  499. }
  500. SimpleTypeRst str = st.Content as SimpleTypeRst;
  501. if (str != null) {
  502. ArrayList al = null;
  503. foreach (SchemaFacet f in str.Facets) {
  504. if (f is LengthFacet ||
  505. f is MinLengthFacet) {
  506. if (al == null)
  507. al = new ArrayList ();
  508. al.Add (f);
  509. }
  510. }
  511. foreach (SchemaFacet f in al)
  512. str.Facets.Remove (f);
  513. if (str.BaseType != null)
  514. str.BaseType =
  515. MakeBaseTypeAsEmptiable (st);
  516. else
  517. // It might have a reference to an
  518. // external simple type, but there is
  519. // no assurance that any of those
  520. // external types allow an empty
  521. // string. So just set base type as
  522. // xs:string.
  523. str.BaseTypeName = QNameString;
  524. } // union/list can have empty string value.
  525. return st;
  526. }
  527. private void ToEmptiableSimpleContent (
  528. SimpleModel sm, bool isNew)
  529. {
  530. SimpleExt se = sm.Content as SimpleExt;
  531. if (se != null)
  532. se.BaseTypeName = QNameString;
  533. else {
  534. SimpleRst sr = sm.Content
  535. as SimpleRst;
  536. if (sr == null)
  537. throw Error (sm, "Invalid simple content model was passed.");
  538. sr.BaseTypeName = QNameString;
  539. sr.BaseType = null;
  540. }
  541. }
  542. private void ToEmptiableComplexContent (
  543. ComplexModel cm, bool isNew)
  544. {
  545. ComplexExt ce = cm.Content
  546. as ComplexExt;
  547. if (ce != null) {
  548. if (ce.Particle != null)
  549. ce.Particle.MinOccurs = 0;
  550. else if (ce.BaseTypeName != null &&
  551. ce.BaseTypeName != QName.Empty &&
  552. ce.BaseTypeName != QNameAnyType)
  553. throw Error (ce, "Complex type content extension has a reference to an external component that is not supported.");
  554. }
  555. else {
  556. ComplexRst cr = cm.Content
  557. as ComplexRst;
  558. if (cr == null)
  559. throw Error (cm, "Invalid complex content model was passed.");
  560. if (cr.Particle != null)
  561. cr.Particle.MinOccurs = 0;
  562. else if (cr.BaseTypeName != null &&
  563. cr.BaseTypeName != QName.Empty &&
  564. cr.BaseTypeName != QNameAnyType)
  565. throw Error (cr, "Complex type content extension has a reference to an external component that is not supported.");
  566. }
  567. }
  568. private void InferContent (Element el, string ns, bool isNew)
  569. {
  570. source.Read ();
  571. source.MoveToContent ();
  572. switch (source.NodeType) {
  573. case XmlNodeType.EndElement:
  574. InferAsEmptyElement (el, ns, isNew);
  575. break;
  576. case XmlNodeType.Element:
  577. InferComplexContent (el, ns, isNew);
  578. break;
  579. case XmlNodeType.Text:
  580. case XmlNodeType.CDATA:
  581. case XmlNodeType.SignificantWhitespace:
  582. InferTextContent (el, isNew);
  583. source.MoveToContent ();
  584. if (source.NodeType == XmlNodeType.Element)
  585. goto case XmlNodeType.Element;
  586. break;
  587. case XmlNodeType.Whitespace:
  588. InferContent (el, ns, isNew); // skip and retry
  589. break;
  590. }
  591. }
  592. private void InferComplexContent (Element el, string ns,
  593. bool isNew)
  594. {
  595. ComplexType ct = ToComplexType (el);
  596. ToComplexContentType (ct);
  597. int position = 0;
  598. bool consumed = false;
  599. do {
  600. switch (source.NodeType) {
  601. case XmlNodeType.Element:
  602. Sequence s = PopulateSequence (ct);
  603. Choice c = s.Items.Count > 0 ?
  604. s.Items [0] as Choice :
  605. null;
  606. if (c != null)
  607. ProcessLax (c, ns);
  608. else
  609. ProcessSequence (ct, s, ns,
  610. ref position,
  611. ref consumed,
  612. isNew);
  613. source.MoveToContent ();
  614. break;
  615. case XmlNodeType.Text:
  616. case XmlNodeType.CDATA:
  617. case XmlNodeType.SignificantWhitespace:
  618. MarkAsMixed (ct);
  619. source.ReadString ();
  620. source.MoveToContent ();
  621. break;
  622. case XmlNodeType.EndElement:
  623. return; // finished
  624. case XmlNodeType.None:
  625. throw new NotImplementedException ("Internal Error: Should not happen.");
  626. }
  627. } while (true);
  628. }
  629. private void InferTextContent (Element el, bool isNew)
  630. {
  631. string value = source.ReadString ();
  632. if (el.SchemaType == null) {
  633. if (el.SchemaTypeName == QName.Empty) {
  634. // no type information -> infer type
  635. if (isNew)
  636. el.SchemaTypeName =
  637. InferSimpleType (
  638. value);
  639. else
  640. el.SchemaTypeName =
  641. QNameString;
  642. return;
  643. }
  644. switch (el.SchemaTypeName.Namespace) {
  645. case XmlSchema.Namespace:
  646. case XdtNamespace:
  647. // existing primitive type
  648. el.SchemaTypeName = InferMergedType (
  649. value, el.SchemaTypeName);
  650. break;
  651. default:
  652. ComplexType ct = schemas.GlobalTypes [
  653. el.SchemaTypeName]
  654. as ComplexType;
  655. // If it is complex, then just set
  656. // mixed='true' (type cannot be set.)
  657. // If it is simple, then we cannot
  658. // make sure that string value is
  659. // valid. So just set as xs:string.
  660. if (ct != null)
  661. MarkAsMixed (ct);
  662. else
  663. el.SchemaTypeName = QNameString;
  664. break;
  665. }
  666. return;
  667. }
  668. // simpleType
  669. SimpleType st = el.SchemaType as SimpleType;
  670. if (st != null) {
  671. // If simple, then (described above)
  672. el.SchemaType = null;
  673. el.SchemaTypeName = QNameString;
  674. return;
  675. }
  676. // complexType
  677. ComplexType ect = el.SchemaType as ComplexType;
  678. SimpleModel sm = ect.ContentModel as SimpleModel;
  679. if (sm == null) {
  680. // - ComplexContent
  681. MarkAsMixed (ect);
  682. return;
  683. }
  684. // - SimpleContent
  685. SimpleExt se = sm.Content as SimpleExt;
  686. if (se != null)
  687. se.BaseTypeName = InferMergedType (value,
  688. se.BaseTypeName);
  689. SimpleRst sr = sm.Content as SimpleRst;
  690. if (sr != null) {
  691. sr.BaseTypeName = InferMergedType (value,
  692. sr.BaseTypeName);
  693. sr.BaseType = null;
  694. }
  695. }
  696. private void MarkAsMixed (ComplexType ct)
  697. {
  698. ComplexModel cm = ct.ContentModel as ComplexModel;
  699. if (cm != null)
  700. cm.IsMixed = true;
  701. else
  702. ct.IsMixed = true;
  703. }
  704. #endregion
  705. #region Particles
  706. private void ProcessLax (Choice c, string ns)
  707. {
  708. foreach (Particle p in c.Items) {
  709. Element el = p as Element;
  710. if (el == null)
  711. throw Error (c, String.Format ("Target schema item contains unacceptable particle {0}. Only element is allowed here."));
  712. if (ElementMatches (el, ns)) {
  713. InferElement (el, ns, false);
  714. return;
  715. }
  716. }
  717. // append a new element particle to lax term.
  718. Element nel = new Element ();
  719. if (source.NamespaceURI == ns)
  720. nel.Name = source.LocalName;
  721. else {
  722. nel.RefName = new QName (source.LocalName,
  723. source.NamespaceURI);
  724. AddImport (ns, source.NamespaceURI);
  725. }
  726. InferElement (nel, source.NamespaceURI, true);
  727. c.Items.Add (nel);
  728. }
  729. private bool ElementMatches (Element el, string ns)
  730. {
  731. bool matches = false;
  732. if (el.RefName != QName.Empty) {
  733. if (el.RefName.Name == source.LocalName &&
  734. el.RefName.Namespace ==
  735. source.NamespaceURI)
  736. matches = true;
  737. }
  738. else if (el.Name == source.LocalName &&
  739. ns == source.NamespaceURI)
  740. matches = true;
  741. return matches;
  742. }
  743. private void ProcessSequence (ComplexType ct, Sequence s,
  744. string ns, ref int position, ref bool consumed,
  745. bool isNew)
  746. {
  747. for (int i = 0; i < position; i++) {
  748. Element iel = s.Items [i] as Element;
  749. if (ElementMatches (iel, ns)) {
  750. // Sequence element type violation
  751. // might happen (might not, but we
  752. // cannot backtrack here). So switch
  753. // to sequence of choice* here.
  754. ProcessLax (ToSequenceOfChoice (s), ns);
  755. return;
  756. }
  757. }
  758. if (s.Items.Count <= position) {
  759. QName name = new QName (source.LocalName,
  760. source.NamespaceURI);
  761. Element nel = CreateElement (name);
  762. if (laxOccurrence)
  763. nel.MinOccurs = 0;
  764. InferElement (nel, ns, true);
  765. if (ns == name.Namespace)
  766. s.Items.Add (nel);
  767. else {
  768. Element re = new Element ();
  769. if (laxOccurrence)
  770. re.MinOccurs = 0;
  771. re.RefName = name;
  772. AddImport (ns, name.Namespace);
  773. s.Items.Add (re);
  774. }
  775. consumed = true;
  776. return;
  777. }
  778. Element el = s.Items [position] as Element;
  779. if (el == null)
  780. throw Error (s, String.Format ("Target complex type content sequence has an unacceptable type of particle {0}", s.Items [position]));
  781. bool matches = ElementMatches (el, ns);
  782. if (matches) {
  783. if (consumed)
  784. el.MaxOccursString = "unbounded";
  785. InferElement (el, source.NamespaceURI, false);
  786. source.MoveToContent ();
  787. switch (source.NodeType) {
  788. case XmlNodeType.None:
  789. if (source.NodeType ==
  790. XmlNodeType.Element)
  791. goto case XmlNodeType.Element;
  792. else if (source.NodeType ==
  793. XmlNodeType.EndElement)
  794. goto case XmlNodeType.EndElement;
  795. break;
  796. case XmlNodeType.Element:
  797. ProcessSequence (ct, s, ns, ref position,
  798. ref consumed, isNew);
  799. break;
  800. case XmlNodeType.Text:
  801. case XmlNodeType.CDATA:
  802. case XmlNodeType.SignificantWhitespace:
  803. MarkAsMixed (ct);
  804. source.ReadString ();
  805. goto case XmlNodeType.None;
  806. case XmlNodeType.Whitespace:
  807. source.ReadString ();
  808. goto case XmlNodeType.None;
  809. case XmlNodeType.EndElement:
  810. return;
  811. default:
  812. source.Read ();
  813. break;
  814. }
  815. }
  816. else {
  817. if (consumed) {
  818. position++;
  819. consumed = false;
  820. ProcessSequence (ct, s, ns,
  821. ref position, ref consumed,
  822. isNew);
  823. }
  824. else
  825. ProcessLax (ToSequenceOfChoice (s), ns);
  826. }
  827. }
  828. // Note that it does not return the changed sequence.
  829. private Choice ToSequenceOfChoice (Sequence s)
  830. {
  831. Choice c = new Choice ();
  832. if (laxOccurrence)
  833. c.MinOccurs = 0;
  834. c.MaxOccursString = "unbounded";
  835. foreach (Particle p in s.Items)
  836. c.Items.Add (p);
  837. s.Items.Clear ();
  838. s.Items.Add (c);
  839. return c;
  840. }
  841. // It makes complexType not to have Simple content model.
  842. private void ToComplexContentType (ComplexType type)
  843. {
  844. SimpleModel sm = type.ContentModel as SimpleModel;
  845. if (sm == null)
  846. return;
  847. SOMList atts = GetAttributes (type);
  848. foreach (SOMObject o in atts)
  849. type.Attributes.Add (o);
  850. // FIXME: need to copy AnyAttribute.
  851. // (though not considered right now)
  852. type.ContentModel = null;
  853. type.IsMixed = true;
  854. }
  855. private Sequence PopulateSequence (ComplexType ct)
  856. {
  857. Particle p = PopulateParticle (ct);
  858. Sequence s = p as Sequence;
  859. if (s != null)
  860. return s;
  861. else
  862. throw Error (ct, String.Format ("Target complexType contains unacceptable type of particle {0}", p));
  863. }
  864. private Sequence CreateSequence ()
  865. {
  866. Sequence s = new Sequence ();
  867. if (laxOccurrence)
  868. s.MinOccurs = 0;
  869. return s;
  870. }
  871. private Particle PopulateParticle (ComplexType ct)
  872. {
  873. if (ct.ContentModel == null) {
  874. if (ct.Particle == null)
  875. ct.Particle = CreateSequence ();
  876. return ct.Particle;
  877. }
  878. ComplexModel cm = ct.ContentModel as ComplexModel;
  879. if (cm != null) {
  880. ComplexExt ce = cm.Content as ComplexExt;
  881. if (ce != null) {
  882. if (ce.Particle == null)
  883. ce.Particle = CreateSequence ();
  884. return ce.Particle;
  885. }
  886. ComplexRst cr = cm.Content as ComplexRst;
  887. if (cr != null) {
  888. if (cr.Particle == null)
  889. cr.Particle = CreateSequence ();
  890. return cr.Particle;
  891. }
  892. }
  893. throw Error (ct, "Schema inference internal error. The complexType should have been converted to have a complex content.");
  894. }
  895. #endregion
  896. #region String Value
  897. // primitive type inference.
  898. // When running lax type inference, it just returns xs:string.
  899. private QName InferSimpleType (string value)
  900. {
  901. if (laxTypeInference)
  902. return QNameString;
  903. switch (value) {
  904. // 0 and 1 are not infered as byte unlike MS.XSDInfer
  905. // case "0":
  906. // case "1":
  907. case "true":
  908. case "false":
  909. return QNameBoolean;
  910. }
  911. try {
  912. long dec = XmlConvert.ToInt64 (value);
  913. if (byte.MinValue <= dec && dec <= byte.MaxValue)
  914. return QNameUByte;
  915. if (sbyte.MinValue <= dec && dec <= sbyte.MaxValue)
  916. return QNameByte;
  917. if (ushort.MinValue <= dec && dec <= ushort.MaxValue)
  918. return QNameUShort;
  919. if (short.MinValue <= dec && dec <= short.MaxValue)
  920. return QNameShort;
  921. if (uint.MinValue <= dec && dec <= uint.MaxValue)
  922. return QNameUInt;
  923. if (int.MinValue <= dec && dec <= int.MaxValue)
  924. return QNameInt;
  925. return QNameLong;
  926. } catch (Exception) {
  927. }
  928. try {
  929. XmlConvert.ToUInt64 (value);
  930. return QNameULong;
  931. } catch (Exception) {
  932. }
  933. try {
  934. XmlConvert.ToDecimal (value);
  935. return QNameDecimal;
  936. } catch (Exception) {
  937. }
  938. try {
  939. double dbl = XmlConvert.ToDouble (value);
  940. if (float.MinValue <= dbl &&
  941. dbl <= float.MaxValue)
  942. return QNameFloat;
  943. else
  944. return QNameDouble;
  945. } catch (Exception) {
  946. }
  947. try {
  948. // FIXME: also try DateTimeSerializationMode
  949. // and gYearMonth
  950. XmlConvert.ToDateTime (value);
  951. return QNameDateTime;
  952. } catch (Exception) {
  953. }
  954. try {
  955. XmlConvert.ToTimeSpan (value);
  956. return QNameDuration;
  957. } catch (Exception) {
  958. }
  959. // xs:string
  960. return QNameString;
  961. }
  962. #endregion
  963. #region Utilities
  964. private Element GetGlobalElement (QName name)
  965. {
  966. Element el = newElements [name] as Element;
  967. if (el == null)
  968. el = schemas.GlobalElements [name] as Element;
  969. return el;
  970. }
  971. private Attr GetGlobalAttribute (QName name)
  972. {
  973. Attr a = newElements [name] as Attr;
  974. if (a == null)
  975. a = schemas.GlobalAttributes [name] as Attr;
  976. return a;
  977. }
  978. private Element CreateElement (QName name)
  979. {
  980. Element el = new Element ();
  981. el.Name = name.Name;
  982. return el;
  983. }
  984. private Element CreateGlobalElement (QName name)
  985. {
  986. Element el = CreateElement (name);
  987. XmlSchema schema = PopulateSchema (name.Namespace);
  988. schema.Items.Add (el);
  989. newElements.Add (name, el);
  990. return el;
  991. }
  992. private Attr CreateGlobalAttribute (QName name)
  993. {
  994. Attr attr = new Attr ();
  995. XmlSchema schema = PopulateSchema (name.Namespace);
  996. attr.Name = name.Name;
  997. schema.Items.Add (attr);
  998. newAttributes.Add (name, attr);
  999. return attr;
  1000. }
  1001. // Note that the return value never assures that all the
  1002. // components in the parameter ns must reside in it.
  1003. private XmlSchema PopulateSchema (string ns)
  1004. {
  1005. ICollection list = schemas.Schemas (ns);
  1006. if (list.Count > 0) {
  1007. IEnumerator e = list.GetEnumerator ();
  1008. e.MoveNext ();
  1009. return (XmlSchema) e.Current;
  1010. }
  1011. XmlSchema s = new XmlSchema ();
  1012. if (ns != null && ns.Length > 0)
  1013. s.TargetNamespace = ns;
  1014. s.ElementFormDefault = Form.Qualified;
  1015. s.AttributeFormDefault = Form.Unqualified;
  1016. schemas.Add (s);
  1017. return s;
  1018. }
  1019. private XmlSchemaInferenceException Error (
  1020. XmlSchemaObject sourceObj,
  1021. string message)
  1022. {
  1023. // This override is mainly for schema component error.
  1024. return Error (sourceObj, false, message);
  1025. }
  1026. private XmlSchemaInferenceException Error (
  1027. XmlSchemaObject sourceObj,
  1028. bool useReader,
  1029. string message)
  1030. {
  1031. string msg = String.Concat (
  1032. message,
  1033. sourceObj != null ?
  1034. String.Format (". Related schema component is {0}",
  1035. sourceObj.SourceUri,
  1036. sourceObj.LineNumber,
  1037. sourceObj.LinePosition) :
  1038. String.Empty,
  1039. useReader ?
  1040. String.Format (". {0}", source.BaseURI) :
  1041. String.Empty);
  1042. IXmlLineInfo li = source as IXmlLineInfo;
  1043. if (useReader && li != null)
  1044. return new XmlSchemaInferenceException (
  1045. msg, null, li.LineNumber,
  1046. li.LinePosition);
  1047. else
  1048. return new XmlSchemaInferenceException (msg);
  1049. }
  1050. #endregion
  1051. }
  1052. }
  1053. #endif