2003-10-26 Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
[mono.git] / mcs / class / System.XML / Mono.Xml.Schema / XsdValidatingReader.cs
1 //
2 // Mono.Xml.Schema.XsdValidatingReader.cs
3 //
4 // Author:
5 //      Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
6 //
7 //      (C)2003 Atsushi Enomoto
8 //
9 // Note:
10 //
11 // This class doesn't support set_XmlResolver, since it isn't common to XmlReader interface. 
12 // Try to set that of xml reader which is used to construct this object.
13 //
14 using System;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Text;
18 using System.Xml;
19 using System.Xml.Schema;
20 using Mono.Xml;
21
22 namespace Mono.Xml.Schema
23 {
24         public class XsdValidatingReader : XmlReader, IXmlLineInfo, IHasXmlSchemaInfo, IHasXmlParserContext
25         {
26                 char [] wsChars = new char [] {' ', '\t', '\n', '\r'};
27
28                 XmlReader reader;
29                 XmlValidatingReader xvReader;
30                 IXmlLineInfo readerLineInfo;
31                 bool laxElementValidation = true;
32                 bool reportNoValidationError;
33                 XmlSchemaCollection schemas = new XmlSchemaCollection ();
34                 bool namespaces = true;
35
36                 ArrayList idList = new ArrayList ();
37                 ArrayList missingIDReferences = new ArrayList ();
38                 string thisElementId;
39
40                 ArrayList keyTables = new ArrayList ();
41                 ArrayList currentKeyFieldConsumers = new ArrayList ();
42
43                 XsdValidationStateManager stateManager = new XsdValidationStateManager ();
44                 XsdValidationContext context = new XsdValidationContext ();
45                 XsdValidationState childParticleState;
46
47                 int xsiNilDepth = -1;
48                 StringBuilder storedCharacters = new StringBuilder ();
49                 bool shouldValidateCharacters;
50                 int skipValidationDepth = -1;
51
52                 XmlSchemaAttribute [] defaultAttributes = new XmlSchemaAttribute [0];
53                 int currentDefaultAttribute = -1;
54                 XmlQualifiedName currentQName;
55
56                 ArrayList elementQNameStack = new ArrayList ();
57                 bool popContext;
58
59                 // Property Cache.
60                 int nonDefaultAttributeCount;
61                 bool defaultAttributeConsumed;
62
63                 // Validation engine cached object
64                 ArrayList defaultAttributesCache = new ArrayList ();
65                 ArrayList tmpKeyrefPool = new ArrayList ();
66
67 #region .ctor
68                 public XsdValidatingReader (XmlReader reader)
69                         : this (reader, null)
70                 {
71                 }
72                 
73                 public XsdValidatingReader (XmlReader reader, XmlReader validatingReader)
74                 {
75                         this.reader = reader;
76                         xvReader = validatingReader as XmlValidatingReader;
77                         if (xvReader != null) {
78                                 if (xvReader.ValidationType == ValidationType.None)
79                                         reportNoValidationError = true;
80                         }
81                         readerLineInfo = reader as IXmlLineInfo;
82                 }
83 #endregion
84                 // Provate Properties
85                 private XmlQualifiedName CurrentQName {
86                         get {
87                                 if (currentQName == null)
88                                         currentQName = new XmlQualifiedName (LocalName, NamespaceURI);
89                                 return currentQName;
90                         }
91                 }
92
93                 internal ArrayList CurrentKeyFieldConsumers {
94                         get { return currentKeyFieldConsumers; }
95                 }
96
97                 // Public Non-overrides
98
99                 public bool Namespaces {
100                         get { return namespaces; }
101                         set { namespaces = value; }
102                 }
103
104                 public XmlReader Reader {
105                         get { return reader; }
106                 }
107
108                 // This should be changed before the first Read() call.
109                 public XmlSchemaCollection Schemas {
110                         get { return schemas; }
111                 }
112
113                 public object SchemaType {
114                         get {
115                                 if (ReadState != ReadState.Interactive)
116                                         return null;
117
118                                 switch (NodeType) {
119                                 case XmlNodeType.Element:
120                                         if (context.ActualType != null)
121                                                 return context.ActualType;
122                                         else if (context.Element != null)
123                                                 return context.Element.ElementType;
124                                         else
125                                                 return null;
126                                 case XmlNodeType.Attribute:
127                                         // TODO: Default attribute support
128                                         XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
129                                         if (ct != null) {
130                                                 XmlSchemaAttribute attdef = ct.AttributeUses [CurrentQName] as XmlSchemaAttribute;
131                                                 if (attdef !=null)
132                                                         return attdef.AttributeType;
133                                         }
134                                         return null;
135                                 default:
136                                         return null;
137                                 }
138                         }
139                 }
140
141                 // This property is never used in Mono.
142                 public ValidationType ValidationType {
143                         get {
144                                 if (reportNoValidationError)
145                                         return ValidationType.None;
146                                 else
147                                         return ValidationType.Schema;
148                         }
149                 }
150
151                 // It is used only for independent XmlReader use, not for XmlValidatingReader.
152                 public object ReadTypedValue ()
153                 {
154                         XmlSchemaDatatype dt = SchemaType as XmlSchemaDatatype;
155                         XmlSchemaSimpleType st = SchemaType as XmlSchemaSimpleType;
156                         if (st != null)
157                                 dt = st.Datatype;
158                         if (dt == null)
159                                 return null;
160
161                         switch (NodeType) {
162                         case XmlNodeType.Element:
163                                 if (IsEmptyElement)
164                                         return null;
165
166                                 storedCharacters.Length = 0;
167                                 bool loop = true;
168                                 do {
169                                         Read ();
170                                         switch (NodeType) {
171                                         case XmlNodeType.SignificantWhitespace:
172                                         case XmlNodeType.Text:
173                                         case XmlNodeType.CDATA:
174                                                 storedCharacters.Append (Value);
175                                                 break;
176                                         case XmlNodeType.Comment:
177                                                 break;
178                                         default:
179                                                 loop = false;
180                                                 break;
181                                         }
182                                 } while (loop && !EOF);
183                                 return dt.ParseValue (storedCharacters.ToString (), NameTable, ParserContext.NamespaceManager);
184                         case XmlNodeType.Attribute:
185                                 return dt.ParseValue (Value, NameTable, ParserContext.NamespaceManager);
186                         }
187                         return null;
188                 }
189
190                 public ValidationEventHandler ValidationEventHandler;
191
192                 // Public Overrided Properties
193
194                 public override int AttributeCount {
195                         get {
196                                 /*
197                                 if (NodeType == XmlNodeType.Element)
198                                         return attributeCount;
199                                 else if (IsDefault)
200                                         return 0;
201                                 else
202                                         return reader.AttributeCount;
203                                 */
204                                 return nonDefaultAttributeCount + defaultAttributes.Length;
205                         }
206                 }
207
208                 public override string BaseURI {
209                         get { return reader.BaseURI; }
210                 }
211
212                 // If this class is used to implement XmlValidatingReader,
213                 // it should be left to DTDValidatingReader. In other cases,
214                 // it depends on the reader's ability.
215                 public override bool CanResolveEntity {
216                         get { return reader.CanResolveEntity; }
217                 }
218
219                 public override int Depth {
220                         get {
221                                 if (currentDefaultAttribute < 0)
222                                         return reader.Depth;
223                                 if (this.defaultAttributeConsumed)
224                                         return reader.Depth + 2;
225                                 return reader.Depth + 1;
226                         }
227                 }
228
229                 public override bool EOF {
230                         get { return reader.EOF; }
231                 }
232
233                 public override bool HasValue {
234                         get {
235                                 if (currentDefaultAttribute < 0)
236                                         return reader.HasValue;
237                                 return true;
238                         }
239                 }
240
241                 public override bool IsDefault {
242                         get {
243                                 if (currentDefaultAttribute < 0)
244                                         return reader.IsDefault;
245                                 return true;
246                         }
247                 }
248
249                 public override bool IsEmptyElement {
250                         get {
251                                 if (currentDefaultAttribute < 0)
252                                         return reader.IsEmptyElement;
253                                 return false;
254                         }
255                 }
256
257                 public override string this [int i] {
258                         get { return GetAttribute (i); }
259                 }
260
261                 public override string this [string name] {
262                         get { return GetAttribute (name); }
263                 }
264
265                 public override string this [string localName, string ns] {
266                         get { return GetAttribute (localName, ns); }
267                 }
268
269                 int IXmlLineInfo.LineNumber {
270                         get { return readerLineInfo != null ? readerLineInfo.LineNumber : 0; }
271                 }
272
273                 int IXmlLineInfo.LinePosition {
274                         get { return readerLineInfo != null ? readerLineInfo.LinePosition : 0; }
275                 }
276
277                 public override string LocalName {
278                         get {
279                                 if (currentDefaultAttribute < 0)
280                                         return reader.LocalName;
281                                 if (defaultAttributeConsumed)
282                                         return String.Empty;
283                                 return defaultAttributes [currentDefaultAttribute].QualifiedName.Name;
284                         }
285                 }
286
287                 public override string Name {
288                         get {
289                                 if (currentDefaultAttribute < 0)
290                                         return reader.Name;
291                                 if (defaultAttributeConsumed)
292                                         return String.Empty;
293
294                                 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
295                                 string prefix = Prefix;
296                                 if (prefix == String.Empty)
297                                         return qname.Name;
298                                 else
299                                         return String.Concat (prefix, ":", qname.Name);
300                         }
301                 }
302
303                 public override string NamespaceURI {
304                         get {
305                                 if (currentDefaultAttribute < 0)
306                                         return reader.NamespaceURI;
307                                 if (defaultAttributeConsumed)
308                                         return String.Empty;
309                                 return defaultAttributes [currentDefaultAttribute].QualifiedName.Namespace;
310                         }
311                 }
312
313                 public override XmlNameTable NameTable {
314                         get { return reader.NameTable; }
315                 }
316
317                 public override XmlNodeType NodeType {
318                         get {
319                                 if (currentDefaultAttribute < 0)
320                                         return reader.NodeType;
321                                 if (defaultAttributeConsumed)
322                                         return XmlNodeType.Text;
323                                 return XmlNodeType.Attribute;
324                         }
325                 }
326
327                 public XmlParserContext ParserContext {
328                         get { return XmlSchemaUtil.GetParserContext (reader); }
329                 }
330
331                 public override string Prefix {
332                         get {
333                                 if (currentDefaultAttribute < 0)
334                                         return reader.Prefix;
335                                 if (defaultAttributeConsumed)
336                                         return String.Empty;
337                                 XmlQualifiedName qname = defaultAttributes [currentDefaultAttribute].QualifiedName;
338                                 string prefix = this.ParserContext.NamespaceManager.LookupPrefix (qname.Namespace);
339                                 if (prefix == null)
340                                         return String.Empty;
341                                 else
342                                         return prefix;
343                         }
344                 }
345
346                 public override char QuoteChar {
347                         get { return reader.QuoteChar; }
348                 }
349
350                 public override ReadState ReadState {
351                         get { return reader.ReadState; }
352                 }
353
354                 public override string Value {
355                         get {
356                                 if (currentDefaultAttribute < 0)
357                                         return reader.Value;
358                                 return defaultAttributes [currentDefaultAttribute].ValidatedDefaultValue;
359                         }
360                 }
361
362                 XmlQualifiedName qnameXmlLang = new XmlQualifiedName ("lang", XmlNamespaceManager.XmlnsXml);
363
364                 public override string XmlLang {
365                         get {
366                                 string xmlLang = reader.XmlLang;
367                                 if (xmlLang != null)
368                                         return xmlLang;
369                                 int idx = this.FindDefaultAttribute ("lang", XmlNamespaceManager.XmlnsXml);
370                                 if (idx < 0)
371                                         return null;
372                                 return defaultAttributes [idx].ValidatedDefaultValue;
373                         }
374                 }
375
376                 public override XmlSpace XmlSpace {
377                         get {
378                                 XmlSpace space = reader.XmlSpace;
379                                 if (space != XmlSpace.None)
380                                         return space;
381                                 int idx = this.FindDefaultAttribute ("space", XmlNamespaceManager.XmlnsXml);
382                                 if (idx < 0)
383                                         return XmlSpace.None;
384                                 return (XmlSpace) Enum.Parse (typeof (XmlSpace), defaultAttributes [idx].ValidatedDefaultValue, false);
385                         }
386                 }
387
388                 // Private Methods
389
390                 private XmlQualifiedName QualifyName (string name)
391                 {
392                         int colonAt = name.IndexOf (':');
393                         if (colonAt < 0)
394                                 return new XmlQualifiedName (name, null);
395                         else
396                                 return new XmlQualifiedName (name.Substring (colonAt + 1),
397                                         LookupNamespace (name.Substring (0, colonAt)));
398                 }
399
400                 private void HandleError (string error)
401                 {
402                         HandleError (error, null);
403                 }
404
405                 private void HandleError (string error, Exception innerException)
406                 {
407                         if (reportNoValidationError)    // extra quick check
408                                 return;
409
410                         XmlSchemaException schemaException = new XmlSchemaException (error, 
411                                         this, this.BaseURI, null, innerException);
412                         HandleError (schemaException);
413                 }
414
415                 private void HandleError (XmlSchemaException schemaException)
416                 {
417                         if (reportNoValidationError)
418                                 return;
419
420                         ValidationEventArgs e = new ValidationEventArgs (schemaException,
421                                 schemaException.Message, XmlSeverityType.Error);
422
423                         if (this.ValidationEventHandler != null)
424                                 this.ValidationEventHandler (this, e);
425                         else if (xvReader != null)
426                                 xvReader.OnValidationEvent (this, e);
427                         else
428 #if NON_MONO_ENV
429                                 this.xvReader.OnValidationEvent (this, e);
430 #else
431                                 throw e.Exception;
432 #endif
433                 }
434
435                 private XmlSchemaElement FindElement (string name, string ns)
436                 {
437                         foreach (XmlSchema target in schemas) {
438                                 XmlSchema matches = target.Schemas [reader.NamespaceURI];
439                                 if (matches != null) {
440                                         XmlSchemaElement result = target.Elements [new XmlQualifiedName (reader.LocalName, reader.NamespaceURI)] as XmlSchemaElement;
441                                         if (result != null)
442                                                 return result;
443                                 }
444                         }
445                         return null;
446                 }
447
448                 private XmlSchemaType FindType (XmlQualifiedName qname)
449                 {
450                         foreach (XmlSchema target in schemas) {
451                                 XmlSchemaType type = target.SchemaTypes [qname] as XmlSchemaType;
452                                 if (type != null)
453                                         return type;
454                         }
455                         return null;
456                 }
457
458                 private void ValidateStartElementParticle ()
459                 {
460                         stateManager.CurrentElement = null;
461                         context.ParticleState = context.ParticleState.EvaluateStartElement (reader.LocalName, reader.NamespaceURI);
462                         if (context.ParticleState == XsdValidationState.Invalid)
463                                 HandleError ("Invalid start element: " + reader.NamespaceURI + ":" + reader.LocalName);
464
465                         context.Element = stateManager.CurrentElement;
466                         if (context.Element != null)
467                                 context.SchemaType = context.Element.ElementType;
468                 }
469
470                 private void ValidateEndElementParticle ()
471                 {
472                         if (childParticleState != null) {
473                                 if (!childParticleState.EvaluateEndElement ()) {
474                                         HandleError ("Invalid end element: " + reader.Name);
475                                 }
476                         }
477                         context.PopScope (reader.Depth);
478                 }
479
480                 // Utility for missing validation completion related to child items.
481                 private void ValidateCharacters ()
482                 {
483                         // TODO: value context validation here.
484                         if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
485                                 HandleError ("Element item appeared, while current element context is nil.");
486
487                         storedCharacters.Append (reader.Value);
488                 }
489
490                 // Utility for missing validation completion related to child items.
491                 private void ValidateEndCharacters ()
492                 {
493                         if (context.ActualType == null)
494                                 return;
495
496                         string value = storedCharacters.ToString ();
497
498                         if (storedCharacters.Length == 0) {
499                                 // 3.3.4 Element Locally Valid (Element) 5.1.2
500                                 // TODO: check entire DefaultValid (3.3.6)
501                                 if (context.Element != null && context.Element.ValidatedDefaultValue != null)
502                                         value = context.Element.ValidatedDefaultValue;
503                         }
504
505                         XmlSchemaDatatype dt = context.ActualType as XmlSchemaDatatype;
506                         XmlSchemaSimpleType st = context.ActualType as XmlSchemaSimpleType;
507                         if (dt == null) {
508                                 if (st != null) {
509 //                                      if (st.Variety == XmlSchemaDerivationMethod.Restriction)
510                                         dt = st.Datatype;
511                                 } else {
512                                         XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
513                                         dt = ct.Datatype;
514                                         switch (ct.ContentType) {
515                                         case XmlSchemaContentType.ElementOnly:
516                                         case XmlSchemaContentType.Empty:
517                                                 if (storedCharacters.Length > 0)
518                                                         HandleError ("Character content not allowed.");
519                                                 break;
520                                         }
521                                 }
522                         }
523                         if (dt != null) {
524                                 // 3.3.4 Element Locally Valid (Element) :: 5.2.2.2. Fixed value constraints
525                                 if (context.Element != null && context.Element.ValidatedFixedValue != null)
526                                         if (value != context.Element.ValidatedFixedValue)
527                                                 HandleError ("Fixed value constraint was not satisfied.");
528                                 AssessStringValid (st, dt, value);
529                         }
530
531                         // Identity field value
532                         while (this.currentKeyFieldConsumers.Count > 0) {
533                                 XsdKeyEntryField field = this.currentKeyFieldConsumers [0] as XsdKeyEntryField;
534                                 if (field.Identity != null)
535                                         HandleError ("Two or more identical field was found. Former value is '" + field.Identity + "' .");
536                                 object identity = null;
537                                 if (dt != null) {
538                                         try {
539                                                 identity = dt.ParseValue (value, NameTable, ParserContext.NamespaceManager);
540                                         } catch (Exception ex) { // FIXME: (wishlist) This is bad manner ;-(
541                                                 HandleError ("Identity value is invalid against its data type " + dt.TokenizedType, ex);
542                                         }
543                                 }
544                                 if (identity == null)
545                                         identity = value;
546                                 
547                                 if (!field.SetIdentityField (identity, dt as XsdAnySimpleType, this))
548                                         HandleError ("Two or more identical key value was found: '" + value + "' .");
549                                 this.currentKeyFieldConsumers.RemoveAt (0);
550                         }
551
552                         shouldValidateCharacters = false;
553                 }
554
555                 // 3.14.4 String Valid 
556                 private void AssessStringValid (XmlSchemaSimpleType st,
557                         XmlSchemaDatatype dt, string value)
558                 {
559                         XmlSchemaDatatype validatedDatatype = dt;
560                         if (st != null) {
561                                 string normalized = validatedDatatype.Normalize (value);
562                                 string [] values;
563                                 XmlSchemaDatatype itemDatatype;
564                                 XmlSchemaSimpleType itemSimpleType;
565                                 switch (st.DerivedBy) {
566                                 case XmlSchemaDerivationMethod.List:
567                                         XmlSchemaSimpleTypeList listContent = st.Content as XmlSchemaSimpleTypeList;
568                                         values = normalized.Split (wsChars);
569                                         itemDatatype = listContent.ValidatedListItemType as XmlSchemaDatatype;
570                                         itemSimpleType = listContent.ValidatedListItemType as XmlSchemaSimpleType;
571                                         foreach (string each in values) {
572                                                 if (each == String.Empty)
573                                                         continue;
574                                                 // validate against ValidatedItemType
575                                                 if (itemDatatype != null) {
576                                                         try {
577                                                                 itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
578                                                         } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-(
579                                                                 HandleError ("List type value contains one or more invalid values.", ex);
580                                                                 break;
581                                                         }
582                                                 }
583                                                 else
584                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
585                                         }
586                                         break;
587                                 case XmlSchemaDerivationMethod.Union:
588                                         XmlSchemaSimpleTypeUnion union = st.Content as XmlSchemaSimpleTypeUnion;
589                                         {
590                                                 string each = normalized;
591                                                 // validate against ValidatedItemType
592                                                 bool passed = false;
593                                                 foreach (object eachType in union.ValidatedTypes) {
594                                                         itemDatatype = eachType as XmlSchemaDatatype;
595                                                         itemSimpleType = eachType as XmlSchemaSimpleType;
596                                                         if (itemDatatype != null) {
597                                                                 try {
598                                                                         itemDatatype.ParseValue (each, NameTable, ParserContext.NamespaceManager);
599                                                                 } catch (Exception) { // FIXME: (wishlist) better exception handling ;-(
600                                                                         continue;
601                                                                 }
602                                                         }
603                                                         else {
604                                                                 try {
605                                                                         AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each);
606                                                                 } catch (XmlSchemaException) {
607                                                                         continue;
608                                                                 }
609                                                         }
610                                                         passed = true;
611                                                         break;
612                                                 }
613                                                 if (!passed) {
614                                                         HandleError ("Union type value contains one or more invalid values.");
615                                                         break;
616                                                 }
617                                         }
618                                         break;
619                                 case XmlSchemaDerivationMethod.Restriction:
620                                         XmlSchemaSimpleTypeRestriction str = st.Content as XmlSchemaSimpleTypeRestriction;
621                                         // facet validation
622                                         if (str != null) {
623                                                 if (!str.ValidateValueWithFacets (normalized, NameTable)) {
624                                                         HandleError ("Specified value was invalid against the facets.");
625                                                         break;
626                                                 }
627                                         }
628                                         validatedDatatype = st.Datatype;
629                                         break;
630                                 }
631                         }
632                         if (validatedDatatype != null) {
633                                 try {
634                                         validatedDatatype.ParseValue (value, NameTable, ParserContext.NamespaceManager);
635                                 } catch (Exception ex) {        // FIXME: (wishlist) It is bad manner ;-(
636                                         HandleError ("Invalidly typed data was specified.", ex);
637                                 }
638                         }
639                 }
640
641                 private object GetLocalTypeDefinition (string name)
642                 {
643                         object xsiType = null;
644                         XmlQualifiedName typeQName = QualifyName (name);
645                         if (typeQName.Namespace == XmlSchema.Namespace) {
646                                 if (typeQName.Name == "anyType")
647                                         xsiType = XmlSchemaComplexType.AnyType;
648                                 else
649                                         xsiType = XmlSchemaDatatype.FromName (typeQName);
650                         }
651                         else
652                                 xsiType = FindType (typeQName);
653                         return xsiType;
654                 }
655
656                 // It is common to ElementLocallyValid::4 and SchemaValidityAssessment::1.2.1.2.4
657                 private void AssessLocalTypeDerivationOK (object xsiType, object baseType, XmlSchemaDerivationMethod flag)
658                 {
659                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
660                         XmlSchemaComplexType baseComplexType = baseType as XmlSchemaComplexType;
661                         XmlSchemaComplexType xsiComplexType = xsiSchemaType as XmlSchemaComplexType;
662                         if (xsiType != baseType) {
663                                 // Extracted (not extraneous) check for 3.4.6 TypeDerivationOK.
664                                 if (baseComplexType != null)
665                                         flag |= baseComplexType.BlockResolved;
666                                 if (flag == XmlSchemaDerivationMethod.All) {
667                                         HandleError ("Prohibited element type substitution.");
668                                         return;
669                                 } else if (xsiSchemaType != null && (flag & xsiSchemaType.DerivedBy) != 0) {
670                                         HandleError ("Prohibited element type substitution.");
671                                         return;
672                                 }
673                         }
674
675                         if (xsiComplexType != null)
676                                 try {
677                                         xsiComplexType.ValidateTypeDerivationOK (baseType, null, null);
678                                 } catch (XmlSchemaException ex) {
679 //                                      HandleError ("Locally specified schema complex type derivation failed. " + ex.Message, ex);
680                                         HandleError (ex);
681                                 }
682                         else {
683                                 XmlSchemaSimpleType xsiSimpleType = xsiType as XmlSchemaSimpleType;
684                                 if (xsiSimpleType != null) {
685                                         try {
686                                                 xsiSimpleType.ValidateTypeDerivationOK (baseType, null, null, true);
687                                         } catch (XmlSchemaException ex) {
688 //                                              HandleError ("Locally specified schema simple type derivation failed. " + ex.Message, ex);
689                                                 HandleError (ex);
690                                         }
691                                 }
692                                 else if (xsiType is XmlSchemaDatatype) {
693                                         // do nothing
694                                 }
695                                 else
696                                         HandleError ("Primitive data type cannot be derived type using xsi:type specification.");
697                         }
698                 }
699
700                 // Section 3.3.4 of the spec.
701                 private void AssessStartElementSchemaValidity ()
702                 {
703                         // If the reader is inside xsi:nil (and failed on validation),
704                         // then simply skip its content.
705                         if (xsiNilDepth >= 0 && xsiNilDepth < reader.Depth)
706                                 HandleError ("Element item appeared, while current element context is nil.");
707
708                         context.Load (reader.Depth);
709                         if (childParticleState != null) {
710                                 context.ParticleState = childParticleState;
711                                 childParticleState = null;
712                         }
713
714                         // If validation state exists, then first assess particle validity.
715                         if (context.ParticleState != null) {
716                                 ValidateStartElementParticle ();
717                         }
718
719                         string xsiNilValue = GetAttribute ("nil", XmlSchema.InstanceNamespace);
720                         if (xsiNilValue != null)
721                                 xsiNilValue = xsiNilValue.Trim (XmlChar.WhitespaceChars);
722                         bool isXsiNil = xsiNilValue == "true";
723                         if (isXsiNil && this.xsiNilDepth < 0)
724                                 xsiNilDepth = reader.Depth;
725
726                         // [Schema Validity Assessment (Element) 1.2]
727                         // Evaluate "local type definition" from xsi:type.
728                         // (See spec 3.3.4 Schema Validity Assessment (Element) 1.2.1.2.3.
729                         // Note that Schema Validity Assessment(Element) 1.2 takes
730                         // precedence than 1.1 of that.
731
732                         string xsiTypeName = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
733                         if (xsiTypeName != null) {
734                                 xsiTypeName = xsiTypeName.Trim (XmlChar.WhitespaceChars);
735                                 object xsiType = GetLocalTypeDefinition (xsiTypeName);
736                                 if (xsiType == null)
737                                         HandleError ("The instance type was not found: " + xsiTypeName + " .");
738                                 else {
739                                         XmlSchemaType xsiSchemaType = xsiType as XmlSchemaType;
740                                         if (xsiSchemaType != null && this.context.Element != null) {
741                                                 XmlSchemaType elemBaseType = context.Element.ElementType as XmlSchemaType;
742                                                 if (elemBaseType != null && (xsiSchemaType.DerivedBy & elemBaseType.FinalResolved) != 0)
743                                                         HandleError ("The instance type is prohibited by the type of the context element.");
744                                                 if (elemBaseType != xsiType && (xsiSchemaType.DerivedBy & this.context.Element.BlockResolved) != 0)
745                                                         HandleError ("The instance type is prohibited by the context element.");
746                                         }
747                                         XmlSchemaComplexType xsiComplexType = xsiType as XmlSchemaComplexType;
748                                         if (xsiComplexType != null && xsiComplexType.IsAbstract)
749                                                 HandleError ("The instance type is abstract: " + xsiTypeName + " .");
750                                         else {
751                                                 // If current schema type exists, then this xsi:type must be
752                                                 // valid extension of that type. See 1.2.1.2.4.
753                                                 if (context.Element != null) {
754                                                         // FIXME: supply *correct* base type
755                                                         AssessLocalTypeDerivationOK (xsiType, context.Element.ElementType, context.Element.BlockResolved);
756                                                 }
757                                                 AssessStartElementLocallyValidType (xsiType);   // 1.2.2:
758                                                 context.LocalTypeDefinition = xsiType;
759                                         }
760                                 }
761                         }
762
763                         // Create Validation Root, if not exist.
764                         // [Schema Validity Assessment (Element) 1.1]
765                         if (context.Element == null)
766                                 context.Element = FindElement (reader.LocalName, reader.NamespaceURI);
767                         if (context.Element != null) {
768                                 if (xsiTypeName == null) {
769                                         context.SchemaType = context.Element.ElementType;
770                                         AssessElementLocallyValidElement (context.Element, xsiNilValue);        // 1.1.2
771                                 }
772                         } else {
773                                 XmlSchema schema;
774                                 switch (stateManager.ProcessContents) {
775                                 case XmlSchemaContentProcessing.Skip:
776                                         break;
777                                 case XmlSchemaContentProcessing.Lax:
778                                         /*
779                                         schema = schemas [reader.NamespaceURI];
780                                         if (schema != null && !schema.missedSubComponents)
781                                                 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
782                                         */
783                                         break;
784                                 default:
785                                         schema = schemas [reader.NamespaceURI];
786                                         if (xsiTypeName == null && (schema == null || !schema.missedSubComponents))
787                                                 HandleError ("Element declaration for " + reader.LocalName + " is missing.");
788                                         break;
789                                 }
790                         }
791
792                         if (stateManager.ProcessContents == XmlSchemaContentProcessing.Skip)
793                                 skipValidationDepth = reader.Depth;
794
795                         // Finally, create child particle state.
796                         XmlSchemaComplexType xsComplexType = SchemaType as XmlSchemaComplexType;
797                         if (xsComplexType != null)
798                                 childParticleState = stateManager.Create (xsComplexType.ContentTypeParticle);
799                         else if (stateManager.ProcessContents == XmlSchemaContentProcessing.Lax)
800                                 childParticleState = stateManager.Create (XmlSchemaAny.AnyTypeContent);
801                         else
802                                 childParticleState = stateManager.Create (XmlSchemaParticle.Empty);
803
804                         AssessStartIdentityConstraints ();
805
806                         context.PushScope (reader.Depth);
807                 }
808
809                 // 3.3.4 Element Locally Valid (Element)
810                 private void AssessElementLocallyValidElement (XmlSchemaElement element, string xsiNilValue)
811                 {
812                         XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
813                         // 1.
814                         if (element == null)
815                                 HandleError ("Element declaration is required for " + qname);
816                         // 2.
817                         if (element.actualIsAbstract)
818                                 HandleError ("Abstract element declaration was specified for " + qname);
819                         // 3.1.
820                         if (!element.actualIsNillable && xsiNilValue != null)
821                                 HandleError ("This element declaration is not nillable: " + qname);
822                         // 3.2.
823                         // Note that 3.2.1 xsi:nil constraints are to be validated in
824                         else if (xsiNilValue == "true") {
825                                 // AssessElementSchemaValidity() and ValidateCharacters()
826
827                                 if (element.ValidatedFixedValue != null)
828                                         HandleError ("Schema instance nil was specified, where the element declaration for " + qname + "has fixed value constraints.");
829                         }
830                         // 4.
831                         string xsiType = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
832                         if (xsiType != null) {
833                                 context.LocalTypeDefinition = GetLocalTypeDefinition (xsiType);
834                                 AssessLocalTypeDerivationOK (context.LocalTypeDefinition, element.ElementType, element.BlockResolved);
835                         }
836
837                         // 5 Not all things cannot be assessed here.
838                         // It is common to 5.1 and 5.2
839                         if (element.ElementType != null)
840                                 AssessStartElementLocallyValidType (SchemaType);
841
842                         // 6. should be out from here.
843                         // See invokation of AssessStartIdentityConstraints().
844
845                         // 7 is going to be validated in Read() (in case of xmlreader's EOF).
846                 }
847
848                 // 3.3.4 Element Locally Valid (Type)
849                 private void AssessStartElementLocallyValidType (object schemaType)
850                 {
851                         if (schemaType == null) {       // 1.
852                                 HandleError ("Schema type does not exist.");
853                                 return;
854                         }
855                         XmlSchemaComplexType cType = schemaType as XmlSchemaComplexType;
856                         XmlSchemaSimpleType sType = schemaType as XmlSchemaSimpleType;
857                         if (sType != null) {
858                                 // 3.1.1.
859                                 while (reader.MoveToNextAttribute ()) {
860                                         if (reader.NamespaceURI == XmlNamespaceManager.XmlnsXmlns)
861                                                 continue;
862                                         if (reader.NamespaceURI != XmlSchema.InstanceNamespace)
863                                                 HandleError ("Current simple type cannot accept attributes other than schema instance namespace.");
864                                         switch (reader.LocalName) {
865                                         case "type":
866                                         case "nil":
867                                         case "schemaLocation":
868                                         case "noNamespaceSchemaLocation":
869                                                 break;
870                                         default:
871                                                 HandleError ("Unknown schema instance namespace attribute: " + reader.LocalName);
872                                                 break;
873                                         }
874                                 }
875                                 reader.MoveToElement ();
876                                 // 3.1.2 and 3.1.3 cannot be assessed here.
877                         } else if (cType != null) {
878                                 if (cType.IsAbstract) { // 2.
879                                         HandleError ("Target complex type is abstract.");
880                                         return;
881                                 }
882                                 // 3.2
883                                 AssessElementLocallyValidComplexType (cType);
884                         }
885                 }
886
887                 // 3.4.4 Element Locally Valid (Complex Type)
888                 // TODO ("wild IDs constraints.")
889                 private void AssessElementLocallyValidComplexType (XmlSchemaComplexType cType)
890                 {
891                         // 1.
892                         if (cType.IsAbstract)
893                                 HandleError ("Target complex type is abstract.");
894
895                         // 2 (xsi:nil and content prohibition)
896                         // See AssessStartElementSchemaValidity() and ValidateCharacters()
897
898                         string elementNs = reader.NamespaceURI;
899                         // 3. attribute uses and 
900                         // 5. wild IDs
901                         while (reader.MoveToNextAttribute ()) {
902                                 if (reader.NamespaceURI == "http://www.w3.org/2000/xmlns/")
903                                         continue;
904                                 else if (reader.NamespaceURI == XmlSchema.InstanceNamespace)
905                                         continue;
906                                 XmlQualifiedName qname = new XmlQualifiedName (reader.LocalName, reader.NamespaceURI);
907                                 object attMatch = FindAttributeDeclaration (cType, qname, elementNs);
908                                 if (attMatch == null)
909                                         HandleError ("Attribute declaration was not found for " + qname);
910                                 else {
911                                         XmlSchemaAttribute attdecl = attMatch as XmlSchemaAttribute;
912                                         if (attdecl == null) { // i.e. anyAttribute
913                                                 XmlSchemaAnyAttribute anyAttrMatch = attMatch as XmlSchemaAnyAttribute;
914                                         } else {
915                                                 AssessAttributeLocallyValidUse (attdecl);
916                                                 AssessAttributeLocallyValid (attdecl, true);
917                                         }
918                                 }
919                         }
920                         reader.MoveToElement ();
921
922                         // Collect default attributes.
923                         // 4.
924                         // FIXME: FixedValue check maybe extraneous.
925                         foreach (XmlSchemaAttribute attr in cType.AttributeUses) {
926                                 if (reader [attr.QualifiedName.Name, attr.QualifiedName.Namespace] == null) {
927                                         if (attr.ValidatedUse == XmlSchemaUse.Required && 
928                                                 attr.ValidatedFixedValue == null)
929                                                 HandleError ("Required attribute " + attr.QualifiedName + " was not found.");
930                                         else if (attr.ValidatedDefaultValue != null)
931                                                 defaultAttributesCache.Add (attr);
932                                 }
933                         }
934                         defaultAttributes = (XmlSchemaAttribute []) 
935                                 defaultAttributesCache.ToArray (typeof (XmlSchemaAttribute));
936                         context.DefaultAttributes = defaultAttributes;
937                         defaultAttributesCache.Clear ();
938                         // 5. wild IDs was already checked above.
939                 }
940
941                 // Spec 3.10.4 Item Valid (Wildcard)
942                 private bool AttributeWildcardItemValid (XmlSchemaAnyAttribute anyAttr, XmlQualifiedName qname)
943                 {
944                         if (anyAttr.HasValueAny)
945                                 return true;
946                         if (anyAttr.HasValueOther && (anyAttr.TargetNamespace == "" || reader.NamespaceURI != anyAttr.TargetNamespace))
947                                 return true;
948                         if (anyAttr.HasValueTargetNamespace && reader.NamespaceURI == anyAttr.TargetNamespace)
949                                 return true;
950                         if (anyAttr.HasValueLocal && reader.NamespaceURI == "")
951                                 return true;
952                         foreach (string ns in anyAttr.ResolvedNamespaces)
953                                 if (ns == reader.NamespaceURI)
954                                         return true;
955                         return false;
956                 }
957
958                 private XmlSchemaObject FindAttributeDeclaration (XmlSchemaComplexType cType,
959                         XmlQualifiedName qname, string elementNs)
960                 {
961                         XmlSchemaObject result = cType.AttributeUses [qname];
962                         if (result != null)
963                                 return result;
964                         if (cType.AttributeWildcard == null)
965                                 return null;
966
967                         if (!AttributeWildcardItemValid (cType.AttributeWildcard, qname))
968                                 return null;
969
970                         if (cType.AttributeWildcard.ProcessContents == XmlSchemaContentProcessing.Skip)
971                                 return cType.AttributeWildcard;
972                         foreach (XmlSchema schema in schemas) {
973                                 foreach (XmlSchemaAttribute attr in schema.Attributes)
974                                         if (attr.QualifiedName == qname)
975                                                 return attr;
976                         }
977                         if (cType.AttributeWildcard.ProcessContents == XmlSchemaContentProcessing.Lax)
978                                 return cType.AttributeWildcard;
979                         else
980                                 return null;
981                 }
982
983                 // 3.2.4 Attribute Locally Valid and 3.4.4 - 5.wildIDs
984                 // TODO
985                 private void AssessAttributeLocallyValid (XmlSchemaAttribute attr, bool checkWildIDs)
986                 {
987                         // 1.
988                         switch (reader.NamespaceURI) {
989                         case XmlNamespaceManager.XmlnsXml:
990                         case XmlNamespaceManager.XmlnsXmlns:
991                         case XmlSchema.InstanceNamespace:
992                                 break;
993                         }
994                         // TODO 2. - 4.
995                         if (attr.AttributeType == null)
996                                 HandleError ("Attribute type is missing for " + attr.QualifiedName);
997                         XmlSchemaDatatype dt = attr.AttributeType as XmlSchemaDatatype;
998                         if (dt == null)
999                                 dt = ((XmlSchemaSimpleType) attr.AttributeType).Datatype;
1000                         // It is a bit heavy process, so let's omit as long as possible ;-)
1001                         if (dt != XmlSchemaSimpleType.AnySimpleType || attr.ValidatedFixedValue != null) {
1002                                 string normalized = dt.Normalize (reader.Value);
1003                                 object parsedValue = null;
1004                                 try {
1005                                         dt.ParseValue (normalized, reader.NameTable, this.ParserContext.NamespaceManager);
1006                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1007                                         HandleError ("Attribute value is invalid against its data type " + dt.TokenizedType, ex);
1008                                 }
1009                                 if (attr.ValidatedFixedValue != null && attr.ValidatedFixedValue != normalized)
1010                                         HandleError ("The value of the attribute " + attr.QualifiedName + " does not match with its fixed value.");
1011                                 // FIXME: this is extraneous checks in 3.2.4 Attribute Locally Valid.
1012                                 if (checkWildIDs)
1013                                         AssessEachAttributeIdentityConstraint (dt, normalized, parsedValue);
1014                         }
1015                 }
1016
1017                 private void AssessEachAttributeIdentityConstraint (XmlSchemaDatatype dt,
1018                         string normalized, object parsedValue)
1019                 {
1020                         // Get normalized value and (if required) parsedValue if missing.
1021                         switch (dt.TokenizedType) {
1022                         case XmlTokenizedType.IDREFS:
1023                                 if (normalized == null)
1024                                         normalized = dt.Normalize (reader.Value);
1025                                 if (parsedValue == null)
1026                                         parsedValue = dt.ParseValue (normalized, reader.NameTable, ParserContext.NamespaceManager);
1027                                 break;
1028                         case XmlTokenizedType.ID:
1029                         case XmlTokenizedType.IDREF:
1030                                 if (normalized == null)
1031                                         normalized = dt.Normalize (reader.Value);
1032                                 break;
1033                         }
1034
1035                         // Validate identity constraints.
1036                         switch (dt.TokenizedType) {
1037                         case XmlTokenizedType.ID:
1038                                 if (thisElementId != null)
1039                                         HandleError ("ID type attribute was already assigned in the containing element.");
1040                                 thisElementId = normalized;
1041                                 idList.Add (normalized);
1042                                 break;
1043                         case XmlTokenizedType.IDREF:
1044                                 if (missingIDReferences.Contains (normalized))
1045                                         missingIDReferences.Remove (normalized);
1046                                 else
1047                                         missingIDReferences.Add (normalized);
1048                                 break;
1049                         case XmlTokenizedType.IDREFS:
1050                                 foreach (string id in (string []) parsedValue) {
1051                                         if (missingIDReferences.Contains (id))
1052                                                 missingIDReferences.Remove (id);
1053                                         else
1054                                                 missingIDReferences.Add (id);
1055                                 }
1056                                 break;
1057                         }
1058                 }
1059
1060                 // TODO
1061                 private void AssessAttributeLocallyValidUse (XmlSchemaAttribute attr)
1062                 {
1063                         // TODO: value constraint check
1064                         // This is extra check than spec 3.5.4
1065                         if (attr.ValidatedUse == XmlSchemaUse.Prohibited)
1066                                 HandleError ("Attribute " + attr.QualifiedName + " is prohibited in this context.");
1067                 }
1068
1069                 private void AssessEndElementSchemaValidity ()
1070                 {
1071                         if (childParticleState == null)
1072                                 childParticleState = context.ParticleState;
1073                         ValidateEndElementParticle ();  // validate against childrens' state.
1074
1075                         context.Load (reader.Depth);
1076
1077                         // 3.3.4 Assess ElementLocallyValidElement 5: value constraints.
1078                         // 3.3.4 Assess ElementLocallyValidType 3.1.3. = StringValid(3.14.4)
1079                         // => ValidateEndCharacters().
1080
1081                         // Reset Identity constraints.
1082                         for (int i = 0; i < keyTables.Count; i++) {
1083                                 XsdKeyTable keyTable = this.keyTables [i] as XsdKeyTable;
1084                                 if (keyTable.StartDepth == reader.Depth) {
1085                                         EndIdentityValidation (keyTable);
1086                                 } else {
1087                                         for (int k = 0; k < keyTable.Entries.Count; k++) {
1088                                                 XsdKeyEntry entry = keyTable.Entries [k] as XsdKeyEntry;
1089                                                 // Remove finished (maybe key not found) entries.
1090                                                 if (entry.StartDepth == reader.Depth) {
1091                                                         if (entry.KeyFound)
1092                                                                 keyTable.FinishedEntries.Add (entry);
1093                                                         else if (entry.KeySequence.SourceSchemaIdentity is XmlSchemaKey)
1094                                                                 HandleError ("Key sequence is missing.");
1095                                                         keyTable.Entries.RemoveAt (k);
1096                                                         k--;
1097                                                 }
1098                                                 // Pop validated key depth to find two or more fields.
1099                                                 else {
1100                                                         foreach (XsdKeyEntryField kf in entry.KeyFields) {
1101                                                                 if (!kf.FieldFound && kf.FieldFoundDepth == reader.Depth) {
1102                                                                         kf.FieldFoundDepth = 0;
1103                                                                         kf.FieldFoundPath = null;
1104                                                                 }
1105                                                         }
1106                                                 }
1107                                         }
1108                                 }
1109                         }
1110                         for (int i = 0; i < keyTables.Count; i++) {
1111                                 XsdKeyTable keyseq = this.keyTables [i] as XsdKeyTable;
1112                                 if (keyseq.StartDepth == reader.Depth) {
1113 //Console.WriteLine ("Finishing table.");
1114                                         keyTables.RemoveAt (i);
1115                                         i--;
1116                                 }
1117                         }
1118
1119                         // Reset xsi:nil, if required.
1120                         if (xsiNilDepth == reader.Depth)
1121                                 xsiNilDepth = -1;
1122                 }
1123
1124                 // 3.11.4 Identity Constraint Satisfied
1125                 // TODO
1126                 private void AssessStartIdentityConstraints ()
1127                 {
1128                         tmpKeyrefPool.Clear ();
1129                         if (context.Element != null && context.Element.Constraints.Count > 0) {
1130                                 // (a) Create new key sequences, if required.
1131                                 foreach (XmlSchemaIdentityConstraint ident in context.Element.Constraints) {
1132                                         XsdKeyTable seq = CreateNewKeyTable (ident);
1133                                         if (ident is XmlSchemaKeyref)
1134                                                 tmpKeyrefPool.Add (seq);
1135                                 }
1136                         }
1137
1138                         // (b) Evaluate current key sequences.
1139                         foreach (XsdKeyTable seq in this.keyTables) {
1140                                 if (seq.SelectorMatches (this.elementQNameStack, reader) != null) {
1141                                         // creates and registers new entry.
1142                                         XsdKeyEntry entry = new XsdKeyEntry (seq, reader);
1143                                         seq.Entries.Add (entry);
1144                                 }
1145                         }
1146
1147                         // (c) Evaluate field paths.
1148                         foreach (XsdKeyTable seq in this.keyTables) {
1149                                 // If possible, create new field entry candidates.
1150                                 for (int i = 0; i < seq.Entries.Count; i++) {
1151                                         XsdKeyEntry entry = seq.Entries [i] as XsdKeyEntry;
1152 //                                      if (entry.KeyFound)
1153 // FIXME: it should not be skipped for multiple key check!!
1154 //                                              continue;
1155                                         try {
1156                                                 entry.FieldMatches (this.elementQNameStack, this);
1157                                         } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1158                                                 HandleError ("Identity field value is invalid against its data type.", ex);
1159                                         }
1160                                 }
1161                         }
1162                 }
1163
1164                 private XsdKeyTable CreateNewKeyTable (XmlSchemaIdentityConstraint ident)
1165                 {
1166                         XsdKeyTable seq = new XsdKeyTable (ident, this);
1167                         seq.StartDepth = reader.Depth;
1168                         XmlSchemaKeyref keyref = ident as XmlSchemaKeyref;
1169                         this.keyTables.Add (seq);
1170                         return seq;
1171                 }
1172
1173                 private void EndIdentityValidation (XsdKeyTable seq)
1174                 {
1175                         ArrayList errors = new ArrayList ();
1176                         foreach (XsdKeyEntry entry in seq./*NotFound*/Entries) {
1177                                 if (entry.KeyFound)
1178                                         continue;
1179                                 if (seq.SourceSchemaIdentity is XmlSchemaKey)
1180                                         errors.Add ("line " + entry.SelectorLineNumber + "position " + entry.SelectorLinePosition);
1181                         }
1182                         if (errors.Count > 0)
1183                                 HandleError ("Invalid identity constraints were found. Key was not found. "
1184                                         + String.Join (", ", errors.ToArray (typeof (string)) as string []));
1185
1186                         errors.Clear ();
1187                         // Find reference target
1188                         XmlSchemaKeyref xsdKeyref = seq.SourceSchemaIdentity as XmlSchemaKeyref;
1189                         if (xsdKeyref != null) {
1190                                 for (int i = this.keyTables.Count - 1; i >= 0; i--) {
1191                                         XsdKeyTable target = this.keyTables [i] as XsdKeyTable;
1192                                         if (target.SourceSchemaIdentity == xsdKeyref.Target) {
1193                                                 seq.ReferencedKey = target;
1194                                                 foreach (XsdKeyEntry entry in seq.FinishedEntries) {
1195                                                         foreach (XsdKeyEntry targetEntry in target.FinishedEntries) {
1196                                                                 if (entry.CompareIdentity (targetEntry)) {
1197                                                                         entry.KeyRefFound = true;
1198                                                                         break;
1199                                                                 }
1200                                                         }
1201                                                 }
1202                                         }
1203                                 }
1204                                 if (seq.ReferencedKey == null)
1205                                         HandleError ("Target key was not found.");
1206                                 foreach (XsdKeyEntry entry in seq.FinishedEntries) {
1207                                         if (!entry.KeyRefFound)
1208                                                 errors.Add (" line " + entry.SelectorLineNumber + ", position " + entry.SelectorLinePosition);
1209                                 }
1210                                 if (errors.Count > 0)
1211                                         HandleError ("Invalid identity constraints were found. Referenced key was not found: "
1212                                                 + String.Join (" / ", errors.ToArray (typeof (string)) as string []));
1213                         }
1214                 }
1215
1216                 // Overrided Methods
1217
1218                 public override void Close ()
1219                 {
1220                         reader.Close ();
1221                 }
1222
1223                 public override string GetAttribute (int i)
1224                 {
1225                         switch (reader.NodeType) {
1226                         case XmlNodeType.XmlDeclaration:
1227                         case XmlNodeType.DocumentType:
1228                                 return reader.GetAttribute (i);
1229                         }
1230
1231                         if (reader.AttributeCount > i)
1232                                 reader.GetAttribute (i);
1233                         int defIdx = i - nonDefaultAttributeCount;
1234                         if (i < AttributeCount)
1235                                 return defaultAttributes [defIdx].DefaultValue;
1236
1237                         throw new ArgumentOutOfRangeException ("i", i, "Specified attribute index is out of range.");
1238                 }
1239
1240                 public override string GetAttribute (string name)
1241                 {
1242                         switch (reader.NodeType) {
1243                         case XmlNodeType.XmlDeclaration:
1244                         case XmlNodeType.DocumentType:
1245                                 return reader.GetAttribute (name);
1246                         }
1247
1248                         string value = reader.GetAttribute (name);
1249                         if (value != null)
1250                                 return value;
1251
1252                         XmlQualifiedName qname = SplitQName (name);
1253                         return GetDefaultAttribute (qname.Name, qname.Namespace);
1254                 }
1255
1256                 private XmlQualifiedName SplitQName (string name)
1257                 {
1258                         if (!XmlChar.IsName (name))
1259                                 throw new ArgumentException ("Invalid name was specified.", "name");
1260
1261                         Exception ex = null;
1262                         XmlQualifiedName qname = XmlSchemaUtil.ToQName (reader, name, out ex);
1263                         if (ex != null)
1264                                 return XmlQualifiedName.Empty;
1265                         else
1266                                 return qname;
1267                 }
1268
1269                 public override string GetAttribute (string localName, string ns)
1270                 {
1271                         switch (reader.NodeType) {
1272                         case XmlNodeType.XmlDeclaration:
1273                         case XmlNodeType.DocumentType:
1274                                 return reader.GetAttribute (localName, ns);
1275                         }
1276
1277                         string value = reader.GetAttribute (localName, ns);
1278                         if (value != null)
1279                                 return value;
1280
1281                         return GetDefaultAttribute (localName, ns);
1282                 }
1283
1284                 private string GetDefaultAttribute (string localName, string ns)
1285                 {
1286                         int idx = this.FindDefaultAttribute (localName, ns);
1287                         if (idx >= 0)
1288                                 return defaultAttributes [idx].ValidatedDefaultValue;
1289                         else
1290                                 return null;
1291                 }
1292
1293                 private int FindDefaultAttribute (string localName, string ns)
1294                 {
1295                         for (int i = 0; i < this.defaultAttributes.Length; i++) {
1296                                 XmlSchemaAttribute attr = defaultAttributes [i];
1297                                 if (attr.QualifiedName.Name == localName &&
1298                                         attr.QualifiedName.Namespace == ns)
1299                                         return i;
1300                         }
1301                         return -1;
1302                 }
1303
1304                 bool IXmlLineInfo.HasLineInfo ()
1305                 {
1306                         return readerLineInfo != null && readerLineInfo.HasLineInfo ();
1307                 }
1308
1309                 public override string LookupNamespace (string prefix)
1310                 {
1311                         return reader.LookupNamespace (prefix);
1312                 }
1313
1314                 public override void MoveToAttribute (int i)
1315                 {
1316                         switch (reader.NodeType) {
1317                         case XmlNodeType.XmlDeclaration:
1318                         case XmlNodeType.DocumentType:
1319                                 reader.MoveToAttribute (i);
1320                                 return;
1321                         }
1322
1323                         currentQName = null;
1324                         if (i < this.nonDefaultAttributeCount) {
1325                                 reader.MoveToAttribute (i);
1326                                 this.currentDefaultAttribute = -1;
1327                                 this.defaultAttributeConsumed = false;
1328                         }
1329
1330                         if (i < AttributeCount) {
1331                                 this.currentDefaultAttribute = i - nonDefaultAttributeCount;
1332                                 this.defaultAttributeConsumed = false;
1333                         }
1334                         else
1335                                 throw new ArgumentOutOfRangeException ("i", i, "Attribute index is out of range.");
1336                 }
1337
1338                 public override bool MoveToAttribute (string name)
1339                 {
1340                         switch (reader.NodeType) {
1341                         case XmlNodeType.XmlDeclaration:
1342                         case XmlNodeType.DocumentType:
1343                                 return reader.MoveToAttribute (name);
1344                         }
1345
1346                         currentQName = null;
1347                         bool b = reader.MoveToAttribute (name);
1348                         if (b) {
1349                                 this.currentDefaultAttribute = -1;
1350                                 this.defaultAttributeConsumed = false;
1351                                 return true;
1352                         }
1353
1354                         XmlQualifiedName qname = SplitQName (name);
1355                         return MoveToDefaultAttribute (qname.Name, qname.Namespace);
1356                 }
1357
1358                 public override bool MoveToAttribute (string localName, string ns)
1359                 {
1360                         switch (reader.NodeType) {
1361                         case XmlNodeType.XmlDeclaration:
1362                         case XmlNodeType.DocumentType:
1363                                 return reader.MoveToAttribute (localName, ns);
1364                         }
1365
1366                         currentQName = null;
1367                         bool b = reader.MoveToAttribute (localName, ns);
1368                         if (b) {
1369                                 this.currentDefaultAttribute = -1;
1370                                 this.defaultAttributeConsumed = false;
1371                                 return true;
1372                         }
1373
1374                         return MoveToDefaultAttribute (localName, ns);
1375                 }
1376
1377                 private bool MoveToDefaultAttribute (string localName, string ns)
1378                 {
1379                         int idx = this.FindDefaultAttribute (localName, ns);
1380                         if (idx < 0)
1381                                 return false;
1382                         currentDefaultAttribute = idx;
1383                         defaultAttributeConsumed = false;
1384                         return true;
1385                 }
1386
1387                 public override bool MoveToElement ()
1388                 {
1389                         currentDefaultAttribute = -1;
1390                         defaultAttributeConsumed = false;
1391                         currentQName = null;
1392                         return reader.MoveToElement ();
1393                 }
1394
1395                 public override bool MoveToFirstAttribute ()
1396                 {
1397                         switch (reader.NodeType) {
1398                         case XmlNodeType.XmlDeclaration:
1399                         case XmlNodeType.DocumentType:
1400                                 return reader.MoveToFirstAttribute ();
1401                         }
1402
1403                         currentQName = null;
1404                         if (this.nonDefaultAttributeCount > 0) {
1405                                 bool b = reader.MoveToFirstAttribute ();
1406                                 if (b) {
1407                                         currentDefaultAttribute = -1;
1408                                         defaultAttributeConsumed = false;
1409                                 }
1410                                 return b;
1411                         }
1412
1413                         if (this.defaultAttributes.Length > 0) {
1414                                 currentDefaultAttribute = 0;
1415                                 defaultAttributeConsumed = false;
1416                                 return true;
1417                         }
1418                         else
1419                                 return false;
1420                 }
1421
1422                 public override bool MoveToNextAttribute ()
1423                 {
1424                         switch (reader.NodeType) {
1425                         case XmlNodeType.XmlDeclaration:
1426                         case XmlNodeType.DocumentType:
1427                                 return reader.MoveToNextAttribute ();
1428                         }
1429
1430                         currentQName = null;
1431                         if (currentDefaultAttribute >= 0) {
1432                                 if (defaultAttributes.Length == currentDefaultAttribute + 1)
1433                                         return false;
1434                                 currentDefaultAttribute++;
1435                                 defaultAttributeConsumed = false;
1436                                 return true;
1437                         }
1438
1439                         bool b = reader.MoveToNextAttribute ();
1440                         if (b) {
1441                                 currentDefaultAttribute = -1;
1442                                 defaultAttributeConsumed = false;
1443                                 return true;
1444                         }
1445
1446                         if (defaultAttributes.Length > 0) {
1447                                 currentDefaultAttribute = 0;
1448                                 defaultAttributeConsumed = false;
1449                                 return true;
1450                         }
1451                         else
1452                                 return false;
1453                 }
1454
1455                 private void ExamineAdditionalSchema ()
1456                 {
1457                         XmlSchema schema = null;
1458                         string schemaLocation = reader.GetAttribute ("schemaLocation", XmlSchema.InstanceNamespace);
1459                         if (schemaLocation != null) {
1460                                 string [] tmp = XmlSchemaDatatype.FromName ("NMTOKENS").ParseValue (schemaLocation, NameTable, null) as string [];
1461                                 if (tmp.Length % 2 != 0)
1462                                         HandleError ("Invalid schemaLocation attribute format.");
1463                                 for (int i = 0; i < tmp.Length; i += 2) {
1464                                         try {
1465                                                 Uri absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), tmp [i + 1]);
1466                                                 XmlTextReader xtr = new XmlTextReader (absUri.ToString ());
1467                                                 schema = XmlSchema.Read (xtr, null);
1468                                         } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1469                                                 continue;
1470                                         }
1471                                         if (schema.TargetNamespace == null)
1472                                                 schema.TargetNamespace = tmp [i];
1473                                         else if (schema.TargetNamespace != tmp [i])
1474                                                 HandleError ("Specified schema has different target namespace.");
1475                                 }
1476                         }
1477                         if (schema != null) {
1478                                 try {
1479                                         schemas.Add (schema);
1480                                 } catch (XmlSchemaException ex) {
1481                                         HandleError (ex);
1482                                 }
1483                         }
1484                         schema = null;
1485                         string noNsSchemaLocation = reader.GetAttribute ("noNamespaceSchemaLocation", XmlSchema.InstanceNamespace);
1486                         if (noNsSchemaLocation != null) {
1487                                 try {
1488                                         Uri absUri = new Uri ((this.BaseURI != "" ? new Uri (BaseURI) : null), noNsSchemaLocation);
1489                                         XmlTextReader xtr = new XmlTextReader (absUri.ToString ());
1490                                         schema = XmlSchema.Read (xtr, null);
1491                                 } catch (Exception ex) { // FIXME: (wishlist) It is bad manner ;-(
1492                                 }
1493                                 if (schema != null && schema.TargetNamespace != null)
1494                                         HandleError ("Specified schema has different target namespace.");
1495                         }
1496                         if (schema != null) {
1497                                 try {
1498                                         schemas.Add (schema);
1499                                 } catch (XmlSchemaException ex) {
1500                                         HandleError (ex);
1501                                 }
1502                         }
1503                 }
1504
1505                 public override bool Read ()
1506                 {
1507                         nonDefaultAttributeCount = 0;
1508                         currentDefaultAttribute = -1;
1509                         defaultAttributeConsumed = false;
1510                         currentQName = null;
1511                         thisElementId = null;
1512                         defaultAttributes = new XmlSchemaAttribute [0];
1513                         if (popContext) {
1514                                 elementQNameStack.RemoveAt (elementQNameStack.Count - 1);
1515                                 popContext = false;
1516                         }
1517
1518                         bool result = reader.Read ();
1519                         // 3.3.4 ElementLocallyValidElement 7 = Root Valid.
1520                         if (!result && missingIDReferences.Count > 0)
1521                                 HandleError ("There are missing ID references: " +
1522                                         String.Join (" ",
1523                                         this.missingIDReferences.ToArray (typeof (string)) as string []));
1524
1525                         switch (reader.NodeType) {
1526                         case XmlNodeType.Element:
1527                                 nonDefaultAttributeCount = reader.AttributeCount;
1528
1529                                 if (reader.Depth == 0)
1530                                         ExamineAdditionalSchema ();
1531
1532                                 this.elementQNameStack.Add (new XmlQualifiedName (reader.LocalName, reader.NamespaceURI));
1533
1534                                 // If there is no schema information, then no validation is performed.
1535                                 if (schemas.Count == 0)
1536                                         break;
1537
1538 //                              context.Load (reader.Depth);
1539                                 if (skipValidationDepth < 0 || reader.Depth <= skipValidationDepth) {
1540                                         if (shouldValidateCharacters) {
1541                                                 ValidateEndCharacters ();
1542                                                 shouldValidateCharacters = false;
1543                                         }
1544                                         AssessStartElementSchemaValidity ();
1545                                         storedCharacters.Length = 0;
1546                                 } else {
1547                                         context.Clear ();
1548                                 }
1549
1550                                 if (reader.IsEmptyElement)
1551                                         goto case XmlNodeType.EndElement;
1552                                 else
1553                                         shouldValidateCharacters = true;
1554                                 break;
1555                         case XmlNodeType.EndElement:
1556                                 if (reader.Depth == skipValidationDepth) {
1557                                         skipValidationDepth = -1;
1558                                         context.Clear ();
1559                                 } else {
1560 //                                      context.Load (reader.Depth);
1561                                         if (shouldValidateCharacters) {
1562                                                 ValidateEndCharacters ();
1563                                                 shouldValidateCharacters = false;
1564                                         }
1565                                         AssessEndElementSchemaValidity ();
1566                                 }
1567                                 storedCharacters.Length = 0;
1568                                 childParticleState = null;
1569                                 popContext = true;
1570                                 break;
1571
1572                         case XmlNodeType.CDATA:
1573                         case XmlNodeType.SignificantWhitespace:
1574                         case XmlNodeType.Text:
1575                                 XmlSchemaComplexType ct = context.ActualType as XmlSchemaComplexType;
1576                                 if (ct != null && storedCharacters.Length > 0) {
1577                                         switch (ct.ContentType) {
1578                                         case XmlSchemaContentType.ElementOnly:
1579                                         case XmlSchemaContentType.Empty:
1580                                                 HandleError ("Not allowed character content was found.");
1581                                                 break;
1582                                         }
1583                                 }
1584
1585                                 ValidateCharacters ();
1586                                 break;
1587                         }
1588
1589                         return result;
1590                 }
1591
1592                 public override bool ReadAttributeValue ()
1593                 {
1594                         if (currentDefaultAttribute < 0)
1595                                 return reader.ReadAttributeValue ();
1596
1597                         if (this.defaultAttributeConsumed)
1598                                 return false;
1599
1600                         defaultAttributeConsumed = true;
1601                         return true;
1602                 }
1603
1604 #if NET_1_0
1605                 public override string ReadInnerXml ()
1606                 {
1607                         // MS.NET 1.0 has a serious bug here. It skips validation.
1608                         return reader.ReadInnerXml ();
1609                 }
1610
1611                 public override string ReadOuterXml ()
1612                 {
1613                         // MS.NET 1.0 has a serious bug here. It skips validation.
1614                         return reader.ReadOuterXml ();
1615                 }
1616 #endif
1617
1618                 // XmlReader.ReadString() should call derived this.Read().
1619                 public override string ReadString ()
1620                 {
1621 #if NET_1_0
1622                         return reader.ReadString ();
1623 #else
1624                         return base.ReadString ();
1625 #endif
1626                 }
1627
1628                 // This class itself does not have this feature.
1629                 public override void ResolveEntity ()
1630                 {
1631                         reader.ResolveEntity ();
1632                 }
1633
1634                 internal class XsdValidationContext
1635                 {
1636                         Hashtable contextStack;
1637
1638                         public XsdValidationContext ()
1639                         {
1640                                 contextStack = new Hashtable ();
1641                         }
1642
1643                         // Some of them might be missing (See the spec section 5.3, and also 3.3.4).
1644                         public XmlSchemaElement Element;
1645                         public XsdValidationState ParticleState;
1646                         public XmlSchemaAttribute [] DefaultAttributes;
1647
1648                         // Some of them might be missing (See the spec section 5.3).
1649                         public object SchemaType;
1650
1651                         public object LocalTypeDefinition;
1652
1653                         public object ActualType {
1654                                 get {
1655                                         if (LocalTypeDefinition != null)
1656                                                 return LocalTypeDefinition;
1657                                         else
1658                                                 return SchemaType;
1659                                 }
1660                         }
1661
1662                         public void Clear ()
1663                         {
1664                                 Element = null;
1665                                 SchemaType = null;
1666                                 ParticleState = null;
1667                                 LocalTypeDefinition = null;
1668                         }
1669
1670                         public void PushScope (int depth)
1671                         {
1672                                 contextStack [depth] = this.MemberwiseClone ();
1673                         }
1674
1675                         public void PopScope (int depth)
1676                         {
1677                                 Load (depth);
1678                                 contextStack.Remove (depth + 1);
1679                         }
1680
1681                         public void Load (int depth)
1682                         {
1683                                 Clear ();
1684                                 XsdValidationContext restored = (XsdValidationContext) contextStack [depth];
1685                                 if (restored != null) {
1686                                         this.Element = restored.Element;
1687                                         this.ParticleState = restored.ParticleState;
1688                                         this.SchemaType = restored.SchemaType;
1689                                         this.LocalTypeDefinition = restored.LocalTypeDefinition;
1690                                 }
1691                         }
1692                 }
1693
1694                 /*
1695                 internal class XsdValidityState
1696                 {
1697                         ArrayList currentParticles = new ArrayList ();
1698                         ArrayList occured = new ArrayList ();
1699                         Hashtable xsAllConsumed = new Hashtable ();
1700                         XmlSchemaParticle parciele;
1701                         int particleDepth;
1702
1703                         public XsdValidityState (XmlSchemaParticle particle)
1704                         {
1705                                 this.parciele = particle;
1706                                 currentParticles.Add (particle);
1707                         }
1708
1709                 }
1710                 */
1711         }
1712
1713 }