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