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