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